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