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 the main L2CAP entry points
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "bt_l2c_main"
26 
27 #include <bluetooth/log.h>
28 #include <string.h>
29 #include <com_android_bluetooth_flags.h>
30 
31 #include "hal/snoop_logger.h"
32 #include "internal_include/bt_target.h"
33 #include "main/shim/entry.h"
34 #include "osi/include/allocator.h"
35 #include "stack/include/bt_hdr.h"
36 #include "stack/include/bt_psm_types.h"
37 #include "stack/include/bt_types.h"
38 #include "stack/include/hcimsgs.h"  // HCID_GET_
39 #include "stack/include/l2cap_acl_interface.h"
40 #include "stack/include/l2cap_hci_link_interface.h"
41 #include "stack/include/l2cap_interface.h"
42 #include "stack/include/l2cap_module.h"
43 #include "stack/include/l2cdefs.h"
44 #include "stack/l2cap/l2c_int.h"
45 
46 using namespace bluetooth;
47 bool is_l2c_cleanup_inprogress;
48 
49 /******************************************************************************/
50 /*            L O C A L    F U N C T I O N     P R O T O T Y P E S            */
51 /******************************************************************************/
52 static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len);
53 
54 /******************************************************************************/
55 /*               G L O B A L      L 2 C A P       D A T A                     */
56 /******************************************************************************/
57 tL2C_CB l2cb;
58 
59 /*******************************************************************************
60  *
61  * Function         l2c_rcv_acl_data
62  *
63  * Description      This function is called from the HCI Interface when an ACL
64  *                  data packet is received.
65  *
66  * Returns          void
67  *
68  ******************************************************************************/
l2c_rcv_acl_data(BT_HDR * p_msg)69 void l2c_rcv_acl_data(BT_HDR* p_msg) {
70   uint8_t* p = (uint8_t*)(p_msg + 1) + p_msg->offset;
71 
72   /* Extract the handle */
73   uint16_t handle;
74   STREAM_TO_UINT16(handle, p);
75   uint8_t pkt_type = HCID_GET_EVENT(handle);
76   handle = HCID_GET_HANDLE(handle);
77 
78   /* Since the HCI Transport is putting segmented packets back together, we */
79   /* should never get a valid packet with the type set to "continuation"    */
80   if (pkt_type == L2CAP_PKT_CONTINUE) {
81     log::warn("L2CAP - received packet continuation");
82     osi_free(p_msg);
83     return;
84   }
85 
86   uint16_t hci_len;
87   STREAM_TO_UINT16(hci_len, p);
88   if (hci_len < L2CAP_PKT_OVERHEAD || hci_len != p_msg->len - 4) {
89     /* Remote-declared packet size must match HCI_ACL size - ACL header (4) */
90     log::warn("L2CAP - got incorrect hci header");
91     osi_free(p_msg);
92     return;
93   }
94 
95   uint16_t l2cap_len, rcv_cid;
96   STREAM_TO_UINT16(l2cap_len, p);
97   STREAM_TO_UINT16(rcv_cid, p);
98 
99   /* Find the LCB based on the handle */
100   tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle);
101   if (!p_lcb) {
102     log::error("L2CAP - rcvd ACL for unknown handle:{} ls:{} cid:{}", handle, p_msg->layer_specific,
103                rcv_cid);
104     osi_free(p_msg);
105     return;
106   }
107 
108   /* Update the buffer header */
109   p_msg->offset += 4;
110 
111   /* for BLE channel, always notify connection when ACL data received on the
112    * link */
113   if (p_lcb && p_lcb->transport == BT_TRANSPORT_LE && p_lcb->link_state != LST_DISCONNECTING) {
114     /* only process fixed channel data as channel open indication when link is
115      * not in disconnecting mode */
116     l2cble_notify_le_connection(p_lcb->remote_bd_addr);
117   }
118 
119   /* Find the CCB for this CID */
120   tL2C_CCB* p_ccb = NULL;
121   if (rcv_cid >= L2CAP_BASE_APPL_CID) {
122     p_ccb = l2cu_find_ccb_by_cid(p_lcb, rcv_cid);
123     if (!p_ccb) {
124       log::warn("L2CAP - unknown CID: 0x{:04x}", rcv_cid);
125       osi_free(p_msg);
126       return;
127     }
128   }
129 
130   p_msg->len = hci_len - L2CAP_PKT_OVERHEAD;
131   p_msg->offset += L2CAP_PKT_OVERHEAD;
132 
133   if (l2cap_len != p_msg->len) {
134     log::warn("L2CAP - bad length in pkt. Exp: {}  Act: {}", l2cap_len, p_msg->len);
135     osi_free(p_msg);
136     return;
137   }
138 
139   /* Send the data through the channel state machine */
140   if (rcv_cid == L2CAP_SIGNALLING_CID) {
141     process_l2cap_cmd(p_lcb, p, l2cap_len);
142     osi_free(p_msg);
143     return;
144   }
145 
146   if (rcv_cid == L2CAP_CONNECTIONLESS_CID) {
147     /* process_connectionless_data (p_lcb); */
148     osi_free(p_msg);
149     return;
150   }
151 
152   if (rcv_cid == L2CAP_BLE_SIGNALLING_CID) {
153     l2cble_process_sig_cmd(p_lcb, p, l2cap_len);
154     osi_free(p_msg);
155     return;
156   }
157 
158   if ((rcv_cid >= L2CAP_FIRST_FIXED_CHNL) && (rcv_cid <= L2CAP_LAST_FIXED_CHNL) &&
159       (l2cb.fixed_reg[rcv_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb != NULL)) {
160     /* only process fixed channel data when link is open or wait for data
161      * indication */
162     if (!p_lcb || p_lcb->link_state == LST_DISCONNECTING ||
163         !l2cu_initialize_fixed_ccb(p_lcb, rcv_cid)) {
164       osi_free(p_msg);
165       return;
166     }
167 
168     /* If no CCB for this channel, allocate one */
169     p_ccb = p_lcb->p_fixed_ccbs[rcv_cid - L2CAP_FIRST_FIXED_CHNL];
170     p_ccb->metrics.rx(p_msg->len);
171 
172     if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_BASIC_MODE) {
173       l2c_fcr_proc_pdu(p_ccb, p_msg);
174     } else {
175       l2cu_fixed_channel_data_cb(p_lcb, rcv_cid, p_msg);
176     }
177     return;
178   }
179 
180   if (!p_ccb) {
181     osi_free(p_msg);
182     return;
183   }
184 
185   if (p_lcb->transport == BT_TRANSPORT_LE) {
186     l2c_lcc_proc_pdu(p_ccb, p_msg);
187 
188     /* The remote device has one less credit left */
189     --p_ccb->remote_credit_count;
190 
191     /* If the credits left on the remote device are getting low, send some */
192     if (p_ccb->remote_credit_count <= ::L2CA_LeCreditThreshold()) {
193       uint16_t credits = L2CA_LeCreditDefault() - p_ccb->remote_credit_count;
194       p_ccb->remote_credit_count = L2CA_LeCreditDefault();
195 
196       /* Return back credits */
197       l2c_csm_execute(p_ccb, L2CEVT_L2CA_SEND_FLOW_CONTROL_CREDIT, &credits);
198     }
199   } else {
200     /* Basic mode packets go straight to the state machine */
201     if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) {
202       l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_msg);
203     } else {
204       /* eRTM or streaming mode, so we need to validate states first */
205       if ((p_ccb->chnl_state == CST_OPEN) || (p_ccb->chnl_state == CST_CONFIG)) {
206         l2c_fcr_proc_pdu(p_ccb, p_msg);
207       } else {
208         osi_free(p_msg);
209       }
210     }
211   }
212 }
213 
214 /*******************************************************************************
215  *
216  * Function         process_l2cap_cmd
217  *
218  * Description      This function is called when a packet is received on the
219  *                  L2CAP signalling CID
220  *
221  * Returns          void
222  *
223  ******************************************************************************/
process_l2cap_cmd(tL2C_LCB * p_lcb,uint8_t * p,uint16_t pkt_len)224 static void process_l2cap_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len) {
225   tL2C_RCB* p_rcb;
226 
227   /* if l2c free was already called that indicates stack being shutdown, donot process
228    * any command*/
229   if (com::android::bluetooth::flags::avoid_l2c_processing_while_stack_shutdown() &&
230       is_l2c_cleanup_inprogress) {
231     log::warn("Do not process any events when stack is being shutdown");
232     return;
233   }
234 
235   /* if l2cap command received in CID 1 on top of an LE link, ignore this
236    * command */
237   if (p_lcb->transport == BT_TRANSPORT_LE) {
238     log::info("Dropping data on CID 1 for LE link");
239     return;
240   }
241 
242   /* Reject the packet if it exceeds the default Signalling Channel MTU */
243   bool pkt_size_rej = false;
244   if (pkt_len > L2CAP_DEFAULT_MTU) {
245     /* Core Spec requires a single response to the first command found in a
246      * multi-command L2cap packet.  If only responses in the packet, then it
247      * will be ignored. Here we simply mark the bad packet and decide which cmd
248      * ID to reject later */
249     pkt_size_rej = true;
250     log::warn("Signaling pkt_len={} exceeds MTU size {}", pkt_len, L2CAP_DEFAULT_MTU);
251   }
252 
253   uint8_t* p_next_cmd = p;
254   uint8_t* p_pkt_end = p + pkt_len;
255   uint8_t last_id = 0;
256   bool first_cmd = true;
257 
258   tL2CAP_CFG_INFO cfg_info;
259   memset(&cfg_info, 0, sizeof(cfg_info));
260 
261   /* An L2CAP packet may contain multiple commands */
262   while (true) {
263     /* Smallest command is 4 bytes */
264     p = p_next_cmd;
265     if (p > (p_pkt_end - 4)) {
266       /* Reject to the previous endpoint if reliable channel is being used.
267        * This is required in L2CAP/COS/CED/BI-02-C */
268       if (!first_cmd &&
269           (cfg_info.fcr.mode == L2CAP_FCR_BASIC_MODE || cfg_info.fcr.mode == L2CAP_FCR_ERTM_MODE) &&
270           p != p_pkt_end) {
271         l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, last_id, 0, 0);
272       }
273       break;
274     }
275 
276     uint8_t cmd_code, id;
277     uint16_t cmd_len;
278     STREAM_TO_UINT8(cmd_code, p);
279     STREAM_TO_UINT8(id, p);
280     STREAM_TO_UINT16(cmd_len, p);
281 
282     last_id = id;
283     first_cmd = false;
284 
285     if (cmd_len > BT_SMALL_BUFFER_SIZE) {
286       log::warn("Command size {} exceeds limit {}", cmd_len, BT_SMALL_BUFFER_SIZE);
287       l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_MTU_EXCEEDED, id, 0, 0);
288       return;
289     }
290 
291     /* Check command length does not exceed packet length */
292     p_next_cmd = p + cmd_len;
293     if (p_next_cmd > p_pkt_end) {
294       log::warn("cmd_len > pkt_len, pkt_len={}, cmd_len={}, code={}", pkt_len, cmd_len, cmd_code);
295       break;
296     }
297 
298     log::debug("cmd: {}, id:{}, cmd_len:{}", l2cap_command_code_text(cmd_code), id, cmd_len);
299 
300     /* Bad L2CAP packet length, look for cmd to reject */
301     if (pkt_size_rej) {
302       /* If command found rejected it and we're done, otherwise keep looking */
303       if (l2c_is_cmd_rejected(cmd_code, id, p_lcb)) {
304         log::warn("Rejected command {} due to bad packet length", cmd_code);
305         return;
306       } else {
307         log::warn("No need to reject command {} for bad packet len", cmd_code);
308         continue; /* Look for next cmd/response in current packet */
309       }
310     }
311 
312     switch (cmd_code) {
313       case L2CAP_CMD_REJECT:
314         uint16_t rej_reason;
315         if (p + 2 > p_next_cmd) {
316           log::warn("Not enough data for L2CAP_CMD_REJECT");
317           return;
318         }
319         STREAM_TO_UINT16(rej_reason, p);
320         if (rej_reason == L2CAP_CMD_REJ_MTU_EXCEEDED) {
321           uint16_t rej_mtu;
322           if (p + 2 > p_next_cmd) {
323             log::warn("Not enough data for L2CAP_CMD_REJ_MTU_EXCEEDED");
324             return;
325           }
326           STREAM_TO_UINT16(rej_mtu, p);
327           /* What to do with the MTU reject ? We have negotiated an MTU. For now
328            * we will ignore it and let a higher protocol timeout take care of it
329            */
330           log::warn("MTU rej Handle: {} MTU: {}", p_lcb->Handle(), rej_mtu);
331         }
332         if (rej_reason == L2CAP_CMD_REJ_INVALID_CID) {
333           uint16_t lcid, rcid;
334           if (p + 4 > p_next_cmd) {
335             log::warn("Not enough data for L2CAP_CMD_REJ_INVALID_CID");
336             return;
337           }
338           STREAM_TO_UINT16(rcid, p);
339           STREAM_TO_UINT16(lcid, p);
340 
341           log::warn("Rejected due to invalid CID, LCID: 0x{:04x} RCID: 0x{:04x}", lcid, rcid);
342 
343           /* Remote CID invalid. Treat as a disconnect */
344           tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
345           if ((p_ccb != NULL) && (p_ccb->remote_cid == rcid)) {
346             /* Fake link disconnect - no reply is generated */
347             log::warn("Remote CID is invalid, treat as disconnected");
348             l2c_csm_execute(p_ccb, L2CEVT_LP_DISCONNECT_IND, NULL);
349           }
350         } else if (rej_reason == L2CAP_CMD_REJ_NOT_UNDERSTOOD && p_lcb->w4_info_rsp) {
351           /* SonyEricsson Info request Bug workaround (Continue connection) */
352           alarm_cancel(p_lcb->info_resp_timer);
353 
354           p_lcb->w4_info_rsp = false;
355           tL2C_CONN_INFO ci = {
356                   .bd_addr = p_lcb->remote_bd_addr,
357                   .hci_status = HCI_SUCCESS,
358                   .psm{},
359                   .l2cap_result{},
360                   .l2cap_status{},
361                   .remote_cid{},
362                   .lcids{},
363                   .peer_mtu{},
364           };
365 
366           /* For all channels, send the event through their FSMs */
367           for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
368             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_INFO_RSP, &ci);
369           }
370         }
371         break;
372 
373       case L2CAP_CMD_CONN_REQ: {
374         tL2C_CONN_INFO con_info{};
375         uint16_t rcid{};
376         if (p + 4 > p_next_cmd) {
377           log::warn("Not enough data for L2CAP_CMD_CONN_REQ");
378           return;
379         }
380         STREAM_TO_UINT16(con_info.psm, p);
381         STREAM_TO_UINT16(rcid, p);
382         p_rcb = l2cu_find_rcb_by_psm(con_info.psm);
383         if (!p_rcb) {
384           log::warn("Rcvd conn req for unknown PSM: {}", con_info.psm);
385           l2cu_reject_connection(p_lcb, rcid, id, tL2CAP_CONN::L2CAP_CONN_NO_PSM);
386           break;
387         } else {
388           if (!p_rcb->api.pL2CA_ConnectInd_Cb) {
389             log::warn("Rcvd conn req for outgoing-only connection PSM: {}", con_info.psm);
390             l2cu_reject_connection(p_lcb, rcid, id, tL2CAP_CONN::L2CAP_CONN_NO_PSM);
391             break;
392           }
393         }
394         tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
395         if (p_ccb == nullptr) {
396           log::error("Unable to allocate CCB");
397           l2cu_reject_connection(p_lcb, rcid, id, tL2CAP_CONN::L2CAP_CONN_NO_RESOURCES);
398           break;
399         }
400         p_ccb->remote_id = id;
401         p_ccb->p_rcb = p_rcb;
402         p_ccb->remote_cid = rcid;
403         p_ccb->connection_initiator = L2CAP_INITIATOR_REMOTE;
404 
405         if (p_rcb->psm == BT_PSM_RFCOMM) {
406           bluetooth::shim::GetSnoopLogger()->AddRfcommL2capChannel(
407                   p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid);
408         } else if (p_rcb->log_packets) {
409           bluetooth::shim::GetSnoopLogger()->AcceptlistL2capChannel(
410                   p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid);
411         }
412 
413         l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_REQ, &con_info);
414         break;
415       }
416 
417       case L2CAP_CMD_CONN_RSP: {
418         tL2C_CONN_INFO con_info{};
419         uint16_t lcid{};
420         if (p + 8 > p_next_cmd) {
421           log::warn("Not enough data for L2CAP_CMD_CONN_REQ");
422           return;
423         }
424         STREAM_TO_UINT16(con_info.remote_cid, p);
425         STREAM_TO_UINT16(lcid, p);
426         uint16_t result_u16;
427         STREAM_TO_UINT16(result_u16, p);
428         con_info.l2cap_result = static_cast<tL2CAP_CONN>(result_u16);
429         STREAM_TO_UINT16(con_info.l2cap_status, p);
430 
431         tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
432         if (!p_ccb) {
433           log::warn("no CCB for conn rsp, LCID: {} RCID: {}", lcid, con_info.remote_cid);
434           break;
435         }
436         if (p_ccb->local_id != id) {
437           log::warn("con rsp - bad ID. Exp: {} Got: {}", p_ccb->local_id, id);
438           break;
439         }
440 
441         if (con_info.l2cap_result == tL2CAP_CONN::L2CAP_CONN_OK) {
442           l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP, &con_info);
443         } else if (con_info.l2cap_result == tL2CAP_CONN::L2CAP_CONN_PENDING) {
444           l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_PND, &con_info);
445         } else {
446           l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONNECT_RSP_NEG, &con_info);
447 
448           p_rcb = p_ccb->p_rcb;
449           if (p_rcb->psm == BT_PSM_RFCOMM) {
450             bluetooth::shim::GetSnoopLogger()->AddRfcommL2capChannel(
451                     p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid);
452           } else if (p_rcb->log_packets) {
453             bluetooth::shim::GetSnoopLogger()->AcceptlistL2capChannel(
454                     p_lcb->Handle(), p_ccb->local_cid, p_ccb->remote_cid);
455           }
456         }
457 
458         break;
459       }
460 
461       case L2CAP_CMD_CONFIG_REQ: {
462         uint8_t* p_cfg_end = p + cmd_len;
463         bool cfg_rej = false;
464         uint16_t cfg_rej_len = 0;
465 
466         uint16_t lcid;
467         if (p + 4 > p_next_cmd) {
468           log::warn("Not enough data for L2CAP_CMD_CONFIG_REQ");
469           return;
470         }
471         STREAM_TO_UINT16(lcid, p);
472         STREAM_TO_UINT16(cfg_info.flags, p);
473 
474         uint8_t* p_cfg_start = p;
475 
476         cfg_info.flush_to_present = cfg_info.mtu_present = cfg_info.qos_present =
477                 cfg_info.fcr_present = cfg_info.fcs_present = false;
478 
479         while (p < p_cfg_end) {
480           uint8_t cfg_code, cfg_len;
481           if (p + 2 > p_next_cmd) {
482             log::warn("Not enough data for L2CAP_CMD_CONFIG_REQ sub_event");
483             return;
484           }
485           STREAM_TO_UINT8(cfg_code, p);
486           STREAM_TO_UINT8(cfg_len, p);
487 
488           switch (cfg_code & 0x7F) {
489             case L2CAP_CFG_TYPE_MTU:
490               cfg_info.mtu_present = true;
491               if (cfg_len != 2) {
492                 return;
493               }
494               if (p + cfg_len > p_next_cmd) {
495                 return;
496               }
497               STREAM_TO_UINT16(cfg_info.mtu, p);
498               break;
499 
500             case L2CAP_CFG_TYPE_FLUSH_TOUT:
501               cfg_info.flush_to_present = true;
502               if (cfg_len != 2) {
503                 return;
504               }
505               if (p + cfg_len > p_next_cmd) {
506                 return;
507               }
508               STREAM_TO_UINT16(cfg_info.flush_to, p);
509               break;
510 
511             case L2CAP_CFG_TYPE_QOS:
512               cfg_info.qos_present = true;
513               if (cfg_len != 2 + 5 * 4) {
514                 return;
515               }
516               if (p + cfg_len > p_next_cmd) {
517                 return;
518               }
519               STREAM_TO_UINT8(cfg_info.qos.qos_flags, p);
520               STREAM_TO_UINT8(cfg_info.qos.service_type, p);
521               STREAM_TO_UINT32(cfg_info.qos.token_rate, p);
522               STREAM_TO_UINT32(cfg_info.qos.token_bucket_size, p);
523               STREAM_TO_UINT32(cfg_info.qos.peak_bandwidth, p);
524               STREAM_TO_UINT32(cfg_info.qos.latency, p);
525               STREAM_TO_UINT32(cfg_info.qos.delay_variation, p);
526               break;
527 
528             case L2CAP_CFG_TYPE_FCR:
529               cfg_info.fcr_present = true;
530               if (cfg_len != 3 + 3 * 2) {
531                 return;
532               }
533               if (p + cfg_len > p_next_cmd) {
534                 return;
535               }
536               STREAM_TO_UINT8(cfg_info.fcr.mode, p);
537               STREAM_TO_UINT8(cfg_info.fcr.tx_win_sz, p);
538               STREAM_TO_UINT8(cfg_info.fcr.max_transmit, p);
539               STREAM_TO_UINT16(cfg_info.fcr.rtrans_tout, p);
540               STREAM_TO_UINT16(cfg_info.fcr.mon_tout, p);
541               STREAM_TO_UINT16(cfg_info.fcr.mps, p);
542               break;
543 
544             case L2CAP_CFG_TYPE_FCS:
545               cfg_info.fcs_present = true;
546               if (cfg_len != 1) {
547                 return;
548               }
549               if (p + cfg_len > p_next_cmd) {
550                 return;
551               }
552               STREAM_TO_UINT8(cfg_info.fcs, p);
553               break;
554 
555             case L2CAP_CFG_TYPE_EXT_FLOW:
556               cfg_info.ext_flow_spec_present = true;
557               if (cfg_len != 2 + 2 + 3 * 4) {
558                 return;
559               }
560               if (p + cfg_len > p_next_cmd) {
561                 return;
562               }
563               STREAM_TO_UINT8(cfg_info.ext_flow_spec.id, p);
564               STREAM_TO_UINT8(cfg_info.ext_flow_spec.stype, p);
565               STREAM_TO_UINT16(cfg_info.ext_flow_spec.max_sdu_size, p);
566               STREAM_TO_UINT32(cfg_info.ext_flow_spec.sdu_inter_time, p);
567               STREAM_TO_UINT32(cfg_info.ext_flow_spec.access_latency, p);
568               STREAM_TO_UINT32(cfg_info.ext_flow_spec.flush_timeout, p);
569               break;
570 
571             default:
572               /* sanity check option length */
573               if ((cfg_len + L2CAP_CFG_OPTION_OVERHEAD) <= cmd_len) {
574                 if (p + cfg_len > p_next_cmd) {
575                   return;
576                 }
577                 p += cfg_len;
578                 if ((cfg_code & 0x80) == 0) {
579                   cfg_rej_len += cfg_len + L2CAP_CFG_OPTION_OVERHEAD;
580                   cfg_rej = true;
581                 }
582               } else {
583                 /* bad length; force loop exit */
584                 p = p_cfg_end;
585                 cfg_rej = true;
586               }
587               break;
588           }
589         }
590 
591         tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
592         if (p_ccb) {
593           p_ccb->remote_id = id;
594           if (cfg_rej) {
595             l2cu_send_peer_config_rej(p_ccb, p_cfg_start,
596                                       (uint16_t)(cmd_len - L2CAP_CONFIG_REQ_LEN), cfg_rej_len);
597           } else {
598             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONFIG_REQ, &cfg_info);
599           }
600         } else {
601           /* updated spec says send command reject on invalid cid */
602           l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_INVALID_CID, id, 0, 0);
603         }
604         break;
605       }
606 
607       case L2CAP_CMD_CONFIG_RSP: {
608         uint8_t* p_cfg_end = p + cmd_len;
609         uint16_t lcid;
610         if (p + 6 > p_next_cmd) {
611           log::warn("Not enough data for L2CAP_CMD_CONFIG_RSP");
612           return;
613         }
614         STREAM_TO_UINT16(lcid, p);
615         STREAM_TO_UINT16(cfg_info.flags, p);
616         uint16_t cfg_result;
617         STREAM_TO_UINT16(cfg_result, p);
618         cfg_info.result = static_cast<tL2CAP_CFG_RESULT>(cfg_result);
619         cfg_info.flush_to_present = cfg_info.mtu_present = cfg_info.qos_present =
620                 cfg_info.fcr_present = cfg_info.fcs_present = false;
621 
622         while (p < p_cfg_end) {
623           uint8_t cfg_code, cfg_len;
624           if (p + 2 > p_next_cmd) {
625             log::warn("Not enough data for L2CAP_CMD_CONFIG_RSP sub_event");
626             return;
627           }
628           STREAM_TO_UINT8(cfg_code, p);
629           STREAM_TO_UINT8(cfg_len, p);
630 
631           switch (cfg_code & 0x7F) {
632             case L2CAP_CFG_TYPE_MTU:
633               cfg_info.mtu_present = true;
634               if (p + 2 > p_next_cmd) {
635                 log::warn("Not enough data for L2CAP_CFG_TYPE_MTU");
636                 return;
637               }
638               STREAM_TO_UINT16(cfg_info.mtu, p);
639               break;
640 
641             case L2CAP_CFG_TYPE_FLUSH_TOUT:
642               cfg_info.flush_to_present = true;
643               if (p + 2 > p_next_cmd) {
644                 log::warn("Not enough data for L2CAP_CFG_TYPE_FLUSH_TOUT");
645                 return;
646               }
647               STREAM_TO_UINT16(cfg_info.flush_to, p);
648               break;
649 
650             case L2CAP_CFG_TYPE_QOS:
651               cfg_info.qos_present = true;
652               if (p + 2 + 5 * 4 > p_next_cmd) {
653                 log::warn("Not enough data for L2CAP_CFG_TYPE_QOS");
654                 return;
655               }
656               STREAM_TO_UINT8(cfg_info.qos.qos_flags, p);
657               STREAM_TO_UINT8(cfg_info.qos.service_type, p);
658               STREAM_TO_UINT32(cfg_info.qos.token_rate, p);
659               STREAM_TO_UINT32(cfg_info.qos.token_bucket_size, p);
660               STREAM_TO_UINT32(cfg_info.qos.peak_bandwidth, p);
661               STREAM_TO_UINT32(cfg_info.qos.latency, p);
662               STREAM_TO_UINT32(cfg_info.qos.delay_variation, p);
663               break;
664 
665             case L2CAP_CFG_TYPE_FCR:
666               cfg_info.fcr_present = true;
667               if (p + 3 + 3 * 2 > p_next_cmd) {
668                 log::warn("Not enough data for L2CAP_CFG_TYPE_FCR");
669                 return;
670               }
671               STREAM_TO_UINT8(cfg_info.fcr.mode, p);
672               STREAM_TO_UINT8(cfg_info.fcr.tx_win_sz, p);
673               STREAM_TO_UINT8(cfg_info.fcr.max_transmit, p);
674               STREAM_TO_UINT16(cfg_info.fcr.rtrans_tout, p);
675               STREAM_TO_UINT16(cfg_info.fcr.mon_tout, p);
676               STREAM_TO_UINT16(cfg_info.fcr.mps, p);
677               break;
678 
679             case L2CAP_CFG_TYPE_FCS:
680               cfg_info.fcs_present = true;
681               if (p + 1 > p_next_cmd) {
682                 log::warn("Not enough data for L2CAP_CFG_TYPE_FCS");
683                 return;
684               }
685               STREAM_TO_UINT8(cfg_info.fcs, p);
686               break;
687 
688             case L2CAP_CFG_TYPE_EXT_FLOW:
689               cfg_info.ext_flow_spec_present = true;
690               if (p + 2 + 2 + 3 * 4 > p_next_cmd) {
691                 log::warn("Not enough data for L2CAP_CFG_TYPE_EXT_FLOW");
692                 return;
693               }
694               STREAM_TO_UINT8(cfg_info.ext_flow_spec.id, p);
695               STREAM_TO_UINT8(cfg_info.ext_flow_spec.stype, p);
696               STREAM_TO_UINT16(cfg_info.ext_flow_spec.max_sdu_size, p);
697               STREAM_TO_UINT32(cfg_info.ext_flow_spec.sdu_inter_time, p);
698               STREAM_TO_UINT32(cfg_info.ext_flow_spec.access_latency, p);
699               STREAM_TO_UINT32(cfg_info.ext_flow_spec.flush_timeout, p);
700               break;
701           }
702         }
703 
704         tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
705         if (p_ccb) {
706           if (p_ccb->local_id != id) {
707             log::warn("cfg rsp - bad ID. Exp: {} Got: {}", p_ccb->local_id, id);
708             break;
709           }
710           if (cfg_info.result == tL2CAP_CFG_RESULT::L2CAP_CFG_OK) {
711             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONFIG_RSP, &cfg_info);
712           } else {
713             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_CONFIG_RSP_NEG, &cfg_info);
714           }
715         } else {
716           log::warn("Rcvd cfg rsp for unknown CID: 0x{:04x}", lcid);
717         }
718         break;
719       }
720 
721       case L2CAP_CMD_DISC_REQ: {
722         uint16_t lcid{}, rcid{};
723         if (p + 4 > p_next_cmd) {
724           log::warn("Not enough data for L2CAP_CMD_DISC_REQ");
725           return;
726         }
727         STREAM_TO_UINT16(lcid, p);
728         STREAM_TO_UINT16(rcid, p);
729 
730         tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
731         if (p_ccb) {
732           if (p_ccb->remote_cid == rcid) {
733             tL2C_CONN_INFO con_info{};
734             p_ccb->remote_id = id;
735             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_REQ, &con_info);
736           }
737         } else {
738           l2cu_send_peer_disc_rsp(p_lcb, id, lcid, rcid);
739         }
740 
741         break;
742       }
743 
744       case L2CAP_CMD_DISC_RSP: {
745         uint16_t lcid{}, rcid{};
746         if (p + 4 > p_next_cmd) {
747           log::warn("Not enough data for L2CAP_CMD_DISC_RSP");
748           return;
749         }
750         STREAM_TO_UINT16(rcid, p);
751         STREAM_TO_UINT16(lcid, p);
752 
753         tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, lcid);
754         if (p_ccb) {
755           if ((p_ccb->remote_cid == rcid) && (p_ccb->local_id == id)) {
756             tL2C_CONN_INFO con_info{};
757             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DISCONNECT_RSP, &con_info);
758           }
759         }
760         break;
761       }
762 
763       case L2CAP_CMD_ECHO_REQ:
764         l2cu_send_peer_echo_rsp(p_lcb, id, p, cmd_len);
765         break;
766 
767       case L2CAP_CMD_INFO_REQ: {
768         uint16_t info_type;
769         if (p + 2 > p_next_cmd) {
770           log::warn("Not enough data for L2CAP_CMD_INFO_REQ");
771           return;
772         }
773         STREAM_TO_UINT16(info_type, p);
774         l2cu_send_peer_info_rsp(p_lcb, id, info_type);
775         break;
776       }
777 
778       case L2CAP_CMD_INFO_RSP:
779         /* Stop the link connect timer if sent before L2CAP connection is up */
780         if (p_lcb->w4_info_rsp) {
781           alarm_cancel(p_lcb->info_resp_timer);
782           p_lcb->w4_info_rsp = false;
783         }
784 
785         uint16_t info_type, result;
786         if (p + 4 > p_next_cmd) {
787           log::warn("Not enough data for L2CAP_CMD_INFO_RSP");
788           return;
789         }
790         STREAM_TO_UINT16(info_type, p);
791         STREAM_TO_UINT16(result, p);
792 
793         if ((info_type == L2CAP_EXTENDED_FEATURES_INFO_TYPE) &&
794             (result == L2CAP_INFO_RESP_RESULT_SUCCESS)) {
795           if (p + 4 > p_next_cmd) {
796             log::warn("Not enough data for L2CAP_CMD_INFO_RSP sub_event");
797             return;
798           }
799           STREAM_TO_UINT32(p_lcb->peer_ext_fea, p);
800 
801           if (p_lcb->peer_ext_fea & L2CAP_EXTFEA_FIXED_CHNLS) {
802             l2cu_send_peer_info_req(p_lcb, L2CAP_FIXED_CHANNELS_INFO_TYPE);
803             break;
804           } else {
805             l2cu_process_fixed_chnl_resp(p_lcb);
806           }
807         }
808 
809         if (info_type == L2CAP_FIXED_CHANNELS_INFO_TYPE) {
810           if (result == L2CAP_INFO_RESP_RESULT_SUCCESS) {
811             if (p + L2CAP_FIXED_CHNL_ARRAY_SIZE > p_next_cmd) {
812               return;
813             }
814             memcpy(p_lcb->peer_chnl_mask, p, L2CAP_FIXED_CHNL_ARRAY_SIZE);
815           }
816 
817           l2cu_process_fixed_chnl_resp(p_lcb);
818         }
819         {
820           tL2C_CONN_INFO ci = {
821                   .bd_addr = p_lcb->remote_bd_addr,
822                   .hci_status = HCI_SUCCESS,
823                   .psm{},
824                   .l2cap_result{},
825                   .l2cap_status{},
826                   .remote_cid{},
827                   .lcids{},
828                   .peer_mtu{},
829           };
830           for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb) {
831             l2c_csm_execute(p_ccb, L2CEVT_L2CAP_INFO_RSP, &ci);
832           }
833         }
834         break;
835 
836       default:
837         log::warn("Bad cmd code: {}", cmd_code);
838         l2cu_send_peer_cmd_reject(p_lcb, L2CAP_CMD_REJ_NOT_UNDERSTOOD, id, 0, 0);
839         return;
840     }
841   }
842 }
843 
844 /*******************************************************************************
845  *
846  * Function         l2c_init
847  *
848  * Description      This function is called once at startup to initialize
849  *                  all the L2CAP structures
850  *
851  * Returns          void
852  *
853  ******************************************************************************/
l2c_init(void)854 void l2c_init(void) {
855   int16_t xx;
856 
857   memset(&l2cb, 0, sizeof(tL2C_CB));
858 
859   /* the LE PSM is increased by 1 before being used */
860   l2cb.le_dyn_psm = LE_DYNAMIC_PSM_START - 1;
861 
862   /* Put all the channel control blocks on the free queue */
863   for (xx = 0; xx < MAX_L2CAP_CHANNELS - 1; xx++) {
864     l2cb.ccb_pool[xx].p_next_ccb = &l2cb.ccb_pool[xx + 1];
865   }
866 
867   /* it will be set to L2CAP_PKT_START_NON_FLUSHABLE if controller supports */
868   l2cb.non_flushable_pbf = L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT;
869 
870   l2cb.p_free_ccb_first = &l2cb.ccb_pool[0];
871   l2cb.p_free_ccb_last = &l2cb.ccb_pool[MAX_L2CAP_CHANNELS - 1];
872 
873   /* Set the default idle timeout */
874   l2cb.idle_timeout = L2CAP_LINK_INACTIVITY_TOUT;
875 
876 #if (L2CAP_CONFORMANCE_TESTING == TRUE)
877   /* Conformance testing needs a dynamic response */
878   l2cb.test_info_resp = L2CAP_EXTFEA_SUPPORTED_MASK;
879 #endif
880 
881   /* Number of ACL buffers to use for high priority channel */
882 
883   l2cb.l2c_ble_fixed_chnls_mask =
884           L2CAP_FIXED_CHNL_ATT_BIT | L2CAP_FIXED_CHNL_BLE_SIG_BIT | L2CAP_FIXED_CHNL_SMP_BIT;
885   is_l2c_cleanup_inprogress = false;
886 }
887 
l2c_free(void)888 void l2c_free(void) { is_l2c_cleanup_inprogress = true; }
889 
l2c_ccb_timer_timeout(void * data)890 void l2c_ccb_timer_timeout(void* data) {
891   tL2C_CCB* p_ccb = (tL2C_CCB*)data;
892 
893   l2c_csm_execute(p_ccb, L2CEVT_TIMEOUT, NULL);
894 }
895 
l2c_fcrb_ack_timer_timeout(void * data)896 void l2c_fcrb_ack_timer_timeout(void* data) {
897   tL2C_CCB* p_ccb = (tL2C_CCB*)data;
898 
899   l2c_csm_execute(p_ccb, L2CEVT_ACK_TIMEOUT, NULL);
900 }
901 
l2c_lcb_timer_timeout(void * data)902 void l2c_lcb_timer_timeout(void* data) {
903   tL2C_LCB* p_lcb = (tL2C_LCB*)data;
904 
905   l2c_link_timeout(p_lcb);
906 }
907 
908 /*******************************************************************************
909  *
910  * Function         l2c_data_write
911  *
912  * Description      API functions call this function to write data.
913  *
914  * Returns          tL2CAP_DW_RESULT::L2CAP_DW_SUCCESS, if data accepted,
915  *                  else false
916  *                  tL2CAP_DW_RESULT::L2CAP_DW_CONGESTED, if data accepted
917  *                  and the channel is congested
918  *                  tL2CAP_DW_RESULT::L2CAP_DW_FAILED, if error
919  *
920  ******************************************************************************/
l2c_data_write(uint16_t cid,BT_HDR * p_data,uint16_t flags)921 tL2CAP_DW_RESULT l2c_data_write(uint16_t cid, BT_HDR* p_data, uint16_t flags) {
922   /* Find the channel control block. We don't know the link it is on. */
923   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
924   if (!p_ccb) {
925     log::warn("L2CAP - no CCB for L2CA_DataWrite, CID: {}", cid);
926     osi_free(p_data);
927     return tL2CAP_DW_RESULT::FAILED;
928   }
929 
930   /* Sending message bigger than mtu size of peer is a violation of protocol */
931   uint16_t mtu;
932 
933   if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
934     mtu = p_ccb->peer_conn_cfg.mtu;
935   } else {
936     mtu = p_ccb->peer_cfg.mtu;
937   }
938 
939   if (p_data->len > mtu) {
940     log::warn(
941             "L2CAP - CID: 0x{:04x}  cannot send message bigger than peer's mtu "
942             "size: len={} mtu={}",
943             cid, p_data->len, mtu);
944     osi_free(p_data);
945     return tL2CAP_DW_RESULT::FAILED;
946   }
947 
948   /* channel based, packet based flushable or non-flushable */
949   p_data->layer_specific = flags;
950 
951   /* If already congested, do not accept any more packets */
952   if (p_ccb->cong_sent) {
953     log::error(
954             "L2CAP - CID: 0x{:04x} cannot send, already congested  "
955             "xmit_hold_q.count: {}  buff_quota: {}",
956             p_ccb->local_cid, fixed_queue_length(p_ccb->xmit_hold_q), p_ccb->buff_quota);
957 
958     osi_free(p_data);
959     return tL2CAP_DW_RESULT::FAILED;
960   }
961 
962   l2c_csm_execute(p_ccb, L2CEVT_L2CA_DATA_WRITE, p_data);
963 
964   if (p_ccb->cong_sent) {
965     return tL2CAP_DW_RESULT::CONGESTED;
966   }
967 
968   return tL2CAP_DW_RESULT::SUCCESS;
969 }
970