1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "l2cap.c" 39 40 /* 41 * l2cap.c 42 * Logical Link Control and Adaption Protocol (L2CAP) 43 */ 44 45 #include "l2cap.h" 46 #include "hci.h" 47 #include "hci_dump.h" 48 #include "bluetooth_sdp.h" 49 #include "bluetooth_psm.h" 50 #include "btstack_bool.h" 51 #include "btstack_debug.h" 52 #include "btstack_event.h" 53 #include "btstack_memory.h" 54 55 #ifdef ENABLE_LE_DATA_CHANNELS 56 // TODO avoid dependency on higher layer: used to trigger pairing for outgoing connections 57 #include "ble/sm.h" 58 #endif 59 60 #include <stdarg.h> 61 #include <string.h> 62 63 /* 64 * @brief L2CAP Supervisory function in S-Frames 65 */ 66 typedef enum { 67 L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0, 68 L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 69 L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 70 L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT 71 } l2cap_supervisory_function_t; 72 73 /** 74 * @brief L2CAP Information Types used in Information Request & Response 75 */ 76 typedef enum { 77 L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1, 78 L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED, 79 L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED, 80 } l2cap_info_type_t; 81 82 /** 83 * @brief L2CAP Configuration Option Types used in Configurateion Request & Response 84 */ 85 typedef enum { 86 L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1, 87 L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT, 88 L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE, 89 L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL, 90 L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE, 91 L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION, 92 L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE, 93 } l2cap_config_option_type_t; 94 95 96 #define L2CAP_SIG_ID_INVALID 0 97 98 // size of HCI ACL + L2CAP Header for regular data packets (8) 99 #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE) 100 101 // L2CAP Configuration Result Codes 102 #define L2CAP_CONF_RESULT_SUCCESS 0x0000 103 #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS 0x0001 104 #define L2CAP_CONF_RESULT_REJECT 0x0002 105 #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS 0x0003 106 #define L2CAP_CONF_RESULT_PENDING 0x0004 107 #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED 0x0005 108 109 // L2CAP Reject Result Codes 110 #define L2CAP_REJ_CMD_UNKNOWN 0x0000 111 112 // Response Timeout eXpired 113 #define L2CAP_RTX_TIMEOUT_MS 10000 114 115 // Extended Response Timeout eXpired 116 #define L2CAP_ERTX_TIMEOUT_MS 120000 117 118 // nr of buffered acl packets in outgoing queue to get max performance 119 #define NR_BUFFERED_ACL_PACKETS 3 120 121 // used to cache l2cap rejects, echo, and informational requests 122 #define NR_PENDING_SIGNALING_RESPONSES 3 123 124 // nr of credits provided to remote if credits fall below watermark 125 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5 126 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5 127 128 // offsets for L2CAP SIGNALING COMMANDS 129 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET 0 130 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET 1 131 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2 132 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET 4 133 134 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC) 135 #define L2CAP_USES_CHANNELS 136 #endif 137 138 // prototypes 139 static void l2cap_run(void); 140 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 141 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ); 142 static void l2cap_notify_channel_can_send(void); 143 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel); 144 static uint8_t l2cap_next_sig_id(void); 145 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid); 146 #ifdef ENABLE_CLASSIC 147 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel); 148 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel); 149 static void l2cap_finialize_channel_close(l2cap_channel_t *channel); 150 static inline l2cap_service_t * l2cap_get_service(uint16_t psm); 151 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status); 152 static void l2cap_emit_channel_closed(l2cap_channel_t *channel); 153 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel); 154 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel); 155 #endif 156 #ifdef ENABLE_LE_DATA_CHANNELS 157 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status); 158 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel); 159 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel); 160 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel); 161 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel); 162 static void l2cap_le_send_pdu(l2cap_channel_t *channel); 163 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm); 164 #endif 165 #ifdef L2CAP_USES_CHANNELS 166 static uint16_t l2cap_next_local_cid(void); 167 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid); 168 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code); 169 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size); 170 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid); 171 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type, 172 uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level); 173 static void l2cap_free_channel_entry(l2cap_channel_t * channel); 174 #endif 175 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 176 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel); 177 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts); 178 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts); 179 #endif 180 181 // l2cap_fixed_channel_t entries 182 #ifdef ENABLE_BLE 183 static l2cap_fixed_channel_t l2cap_fixed_channel_att; 184 static l2cap_fixed_channel_t l2cap_fixed_channel_sm; 185 #endif 186 #ifdef ENABLE_CLASSIC 187 static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless; 188 #endif 189 190 #ifdef ENABLE_CLASSIC 191 static btstack_linked_list_t l2cap_services; 192 static uint8_t require_security_level2_for_outgoing_sdp; 193 static bd_addr_t l2cap_outgoing_classic_addr; 194 #endif 195 196 #ifdef ENABLE_LE_DATA_CHANNELS 197 static btstack_linked_list_t l2cap_le_services; 198 #endif 199 200 // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM 201 static btstack_linked_list_t l2cap_channels; 202 #ifdef L2CAP_USES_CHANNELS 203 // next channel id for new connections 204 static uint16_t local_source_cid = 0x40; 205 #endif 206 // next signaling sequence number 207 static uint8_t sig_seq_nr = 0xff; 208 209 // used to cache l2cap rejects, echo, and informational requests 210 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES]; 211 static int signaling_responses_pending; 212 static btstack_packet_callback_registration_t hci_event_callback_registration; 213 214 #ifdef ENABLE_BLE 215 // only used for connection parameter update events 216 static btstack_packet_handler_t l2cap_event_packet_handler; 217 static uint16_t l2cap_le_custom_max_mtu; 218 #endif 219 220 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 221 222 // enable for testing 223 // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16 224 225 /* 226 * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1 227 */ 228 static const uint16_t crc16_table[256] = { 229 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 230 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 231 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 232 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 233 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 234 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 235 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 236 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 237 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 238 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 239 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 240 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 241 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 242 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 243 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 244 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040, 245 }; 246 247 static uint16_t crc16_calc(uint8_t * data, uint16_t len){ 248 uint16_t crc = 0; // initial value = 0 249 while (len--){ 250 crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ]; 251 } 252 return crc; 253 } 254 255 static inline uint16_t l2cap_encanced_control_field_for_information_frame(uint8_t tx_seq, int final, uint8_t req_seq, l2cap_segmentation_and_reassembly_t sar){ 256 return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0; 257 } 258 259 static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){ 260 return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1; 261 } 262 263 static int l2cap_next_ertm_seq_nr(int seq_nr){ 264 return (seq_nr + 1) & 0x3f; 265 } 266 267 static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){ 268 // get num free tx buffers 269 int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames; 270 // calculate num tx buffers for remote MTU 271 int num_tx_buffers_for_max_remote_mtu; 272 uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps); 273 if (channel->remote_mtu <= effective_mps){ 274 // MTU fits into single packet 275 num_tx_buffers_for_max_remote_mtu = 1; 276 } else { 277 // include SDU Length 278 num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps; 279 } 280 log_debug("num_free_tx_buffers %u, num_tx_buffers_for_max_remote_mtu %u", num_free_tx_buffers, num_tx_buffers_for_max_remote_mtu); 281 return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers; 282 } 283 284 static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){ 285 log_info("Retransmit unacknowleged frames"); 286 l2cap_channel->unacked_frames = 0;; 287 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index; 288 } 289 290 static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){ 291 channel->tx_write_index++; 292 if (channel->tx_write_index < channel->num_tx_buffers) return; 293 channel->tx_write_index = 0; 294 } 295 296 static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){ 297 log_info("Start Monitor timer"); 298 btstack_run_loop_remove_timer(&channel->monitor_timer); 299 btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback); 300 btstack_run_loop_set_timer_context(&channel->monitor_timer, channel); 301 btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms); 302 btstack_run_loop_add_timer(&channel->monitor_timer); 303 } 304 305 static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){ 306 log_info("Stop Monitor timer"); 307 btstack_run_loop_remove_timer(&channel->monitor_timer); 308 } 309 310 static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){ 311 log_info("Start Retransmission timer"); 312 btstack_run_loop_remove_timer(&channel->retransmission_timer); 313 btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback); 314 btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel); 315 btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms); 316 btstack_run_loop_add_timer(&channel->retransmission_timer); 317 } 318 319 static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){ 320 log_info("Stop Retransmission timer"); 321 btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer); 322 } 323 324 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){ 325 log_info("Monitor timeout"); 326 l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts); 327 328 // TODO: we assume that it's the oldest packet 329 l2cap_ertm_tx_packet_state_t * tx_state; 330 tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index]; 331 332 // check retry count 333 if (tx_state->retry_count < l2cap_channel->remote_max_transmit){ 334 // increment retry count 335 tx_state->retry_count++; 336 337 // start retransmit 338 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel); 339 340 // start monitor timer 341 l2cap_ertm_start_monitor_timer(l2cap_channel); 342 343 // send RR/P=1 344 l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1; 345 } else { 346 log_info("Monitor timer expired & retry count >= max transmit -> disconnect"); 347 l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 348 } 349 l2cap_run(); 350 } 351 352 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){ 353 log_info("Retransmission timeout"); 354 l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts); 355 356 // TODO: we assume that it's the oldest packet 357 l2cap_ertm_tx_packet_state_t * tx_state; 358 tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index]; 359 360 // set retry count = 1 361 tx_state->retry_count = 1; 362 363 // start retransmit 364 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel); 365 366 // start monitor timer 367 l2cap_ertm_start_monitor_timer(l2cap_channel); 368 369 // send RR/P=1 370 l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1; 371 l2cap_run(); 372 } 373 374 static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){ 375 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index]; 376 hci_reserve_packet_buffer(); 377 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 378 uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar); 379 log_info("I-Frame: control 0x%04x", control); 380 little_endian_store_16(acl_buffer, 8, control); 381 (void)memcpy(&acl_buffer[8 + 2], 382 &channel->tx_packets_data[index * channel->local_mps], 383 tx_state->len); 384 // (re-)start retransmission timer on 385 l2cap_ertm_start_retransmission_timer(channel); 386 // send 387 return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len); 388 } 389 390 static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){ 391 // get next index for storing packets 392 int index = channel->tx_write_index; 393 394 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index]; 395 tx_state->tx_seq = channel->next_tx_seq; 396 tx_state->sar = sar; 397 tx_state->retry_count = 0; 398 399 uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps]; 400 log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len); 401 int pos = 0; 402 if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){ 403 little_endian_store_16(tx_packet, 0, sdu_length); 404 pos += 2; 405 } 406 (void)memcpy(&tx_packet[pos], data, len); 407 tx_state->len = pos + len; 408 409 // update 410 channel->num_stored_tx_frames++; 411 channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq); 412 l2cap_ertm_next_tx_write_index(channel); 413 414 log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames); 415 416 } 417 418 static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){ 419 if (len > channel->remote_mtu){ 420 log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid); 421 return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU; 422 } 423 424 if (!l2cap_ertm_can_store_packet_now(channel)){ 425 log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid); 426 return BTSTACK_ACL_BUFFERS_FULL; 427 } 428 429 // check if it needs to get fragmented 430 uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps); 431 if (len > effective_mps){ 432 // fragmentation needed. 433 l2cap_segmentation_and_reassembly_t sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU; 434 int chunk_len; 435 while (len){ 436 switch (sar){ 437 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU: 438 chunk_len = effective_mps - 2; // sdu_length 439 l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len); 440 len -= chunk_len; 441 sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU; 442 break; 443 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU: 444 chunk_len = effective_mps; 445 if (chunk_len >= len){ 446 sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU; 447 chunk_len = len; 448 } 449 l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len); 450 len -= chunk_len; 451 break; 452 default: 453 break; 454 } 455 } 456 457 } else { 458 l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len); 459 } 460 461 // try to send 462 l2cap_notify_channel_can_send(); 463 return 0; 464 } 465 466 static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){ 467 int pos = 0; 468 config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL; 469 config_options[pos++] = 9; // length 470 config_options[pos++] = (uint8_t) channel->mode; 471 config_options[pos++] = channel->num_rx_buffers; // == TxWindows size 472 config_options[pos++] = channel->local_max_transmit; 473 little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms); 474 pos += 2; 475 little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms); 476 pos += 2; 477 little_endian_store_16( config_options, pos, channel->local_mps); 478 pos += 2; 479 // 480 config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; 481 config_options[pos++] = 2; // length 482 little_endian_store_16(config_options, pos, channel->local_mtu); 483 pos += 2; 484 485 // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default 486 // Workaround: try to actively negotiate FCS option 487 config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE; 488 config_options[pos++] = 1; // length 489 config_options[pos++] = channel->fcs_option; 490 return pos; // 11+4+3=18 491 } 492 493 static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){ 494 int pos = 0; 495 config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL; 496 config_options[pos++] = 9; // length 497 config_options[pos++] = (uint8_t) channel->mode; 498 // less or equal to remote tx window size 499 config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size); 500 // max transmit in response shall be ignored -> use sender values 501 config_options[pos++] = channel->remote_max_transmit; 502 // A value for the Retransmission time-out shall be sent in a positive Configuration Response 503 // and indicates the value that will be used by the sender of the Configuration Response -> use our value 504 little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms); 505 pos += 2; 506 // A value for the Monitor time-out shall be sent in a positive Configuration Response 507 // and indicates the value that will be used by the sender of the Configuration Response -> use our value 508 little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms); 509 pos += 2; 510 // less or equal to remote mps 511 uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps); 512 little_endian_store_16( config_options, pos, effective_mps); 513 pos += 2; 514 // 515 config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU 516 config_options[pos++] = 2; // length 517 little_endian_store_16(config_options, pos, channel->remote_mtu); 518 pos += 2; 519 #if 0 520 // 521 config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE; 522 config_options[pos++] = 1; // length 523 config_options[pos++] = channel->fcs_option; 524 #endif 525 return pos; // 11+4=15 526 } 527 528 static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){ 529 hci_reserve_packet_buffer(); 530 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 531 log_info("S-Frame: control 0x%04x", control); 532 little_endian_store_16(acl_buffer, 8, control); 533 return l2cap_send_prepared(channel->local_cid, 2); 534 } 535 536 static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){ 537 538 uint8_t result = ERROR_CODE_SUCCESS; 539 if (ertm_config->max_transmit < 1){ 540 log_error("max_transmit must be >= 1"); 541 result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 542 } 543 if (ertm_config->retransmission_timeout_ms < 2000){ 544 log_error("retransmission_timeout_ms must be >= 2000 ms"); 545 result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 546 } 547 if (ertm_config->monitor_timeout_ms < 12000){ 548 log_error("monitor_timeout_ms must be >= 12000 ms"); 549 result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 550 } 551 if (ertm_config->local_mtu < 48){ 552 log_error("local_mtu must be >= 48"); 553 result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 554 } 555 if (ertm_config->num_rx_buffers < 1){ 556 log_error("num_rx_buffers must be >= 1"); 557 result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 558 } 559 if (ertm_config->num_tx_buffers < 1){ 560 log_error("num_rx_buffers must be >= 1"); 561 result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 562 } 563 return result; 564 } 565 566 static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){ 567 568 channel->mode = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION; 569 channel->ertm_mandatory = ertm_config->ertm_mandatory; 570 channel->local_max_transmit = ertm_config->max_transmit; 571 channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms; 572 channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms; 573 channel->local_mtu = ertm_config->local_mtu; 574 channel->num_rx_buffers = ertm_config->num_rx_buffers; 575 channel->num_tx_buffers = ertm_config->num_tx_buffers; 576 577 // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned 578 int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f); 579 buffer += bytes_till_alignment; 580 size -= bytes_till_alignment; 581 582 // setup state buffers - use void cast to avoid -Wcast-align warning 583 uint32_t pos = 0; 584 channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos]; 585 pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t); 586 channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos]; 587 pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t); 588 589 // setup reassembly buffer 590 channel->reassembly_buffer = &buffer[pos]; 591 pos += ertm_config->local_mtu; 592 593 // divide rest of data equally 594 channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers); 595 log_info("Local MPS: %u", channel->local_mps); 596 channel->rx_packets_data = &buffer[pos]; 597 pos += ertm_config->num_rx_buffers * channel->local_mps; 598 channel->tx_packets_data = &buffer[pos]; 599 600 channel->fcs_option = ertm_config->fcs_option; 601 } 602 603 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm, 604 l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){ 605 606 log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu); 607 608 // validate local config 609 uint8_t result = l2cap_ertm_validate_local_config(ertm_config); 610 if (result) return result; 611 612 l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0); 613 if (!channel) { 614 return BTSTACK_MEMORY_ALLOC_FAILED; 615 } 616 617 // configure ERTM 618 l2cap_ertm_configure_channel(channel, ertm_config, buffer, size); 619 620 // add to connections list 621 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel); 622 623 // store local_cid 624 if (out_local_cid){ 625 *out_local_cid = channel->local_cid; 626 } 627 628 // check if hci connection is already usable 629 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL); 630 if (conn){ 631 log_info("l2cap_create_channel, hci connection already exists"); 632 l2cap_handle_connection_complete(conn->con_handle, channel); 633 // check if remote supported fearures are already received 634 if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) { 635 l2cap_handle_remote_supported_features_received(channel); 636 } 637 } 638 639 l2cap_run(); 640 641 return 0; 642 } 643 644 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){ 645 if (l2cap_ertm_can_store_packet_now(channel)){ 646 channel->waiting_for_can_send_now = 0; 647 l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid); 648 } 649 } 650 651 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){ 652 653 log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid); 654 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 655 if (!channel) { 656 log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid); 657 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 658 } 659 660 // validate local config 661 uint8_t result = l2cap_ertm_validate_local_config(ertm_config); 662 if (result) return result; 663 664 // configure L2CAP ERTM 665 l2cap_ertm_configure_channel(channel, ertm_config, buffer, size); 666 667 // default: continue 668 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 669 670 // verify remote ERTM support 671 hci_connection_t * connection = hci_connection_for_handle(channel->con_handle); 672 if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 673 674 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){ 675 // ERTM not possible, select basic mode and release buffer 676 channel->mode = L2CAP_CHANNEL_MODE_BASIC; 677 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED); 678 679 // bail if ERTM is mandatory 680 if (channel->ertm_mandatory){ 681 // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists" 682 log_info("ERTM mandatory -> reject connection"); 683 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 684 channel->reason = 0x04; // no resources available 685 } else { 686 log_info("ERTM not supported by remote -> use Basic mode"); 687 } 688 } 689 690 // process 691 l2cap_run(); 692 693 return ERROR_CODE_SUCCESS; 694 } 695 696 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){ 697 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 698 if (!channel) { 699 log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid); 700 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 701 } 702 if (!channel->local_busy){ 703 channel->local_busy = 1; 704 channel->send_supervisor_frame_receiver_not_ready = 1; 705 l2cap_run(); 706 } 707 return ERROR_CODE_SUCCESS; 708 } 709 710 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){ 711 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 712 if (!channel) { 713 log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid); 714 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 715 } 716 if (channel->local_busy){ 717 channel->local_busy = 0; 718 channel->send_supervisor_frame_receiver_ready_poll = 1; 719 l2cap_run(); 720 } 721 return ERROR_CODE_SUCCESS; 722 } 723 724 // Process-ReqSeq 725 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){ 726 int num_buffers_acked = 0; 727 l2cap_ertm_tx_packet_state_t * tx_state; 728 log_info("l2cap_ertm_process_req_seq: tx_read_index %u, tx_write_index %u, req_seq %u", l2cap_channel->tx_read_index, l2cap_channel->tx_write_index, req_seq); 729 while (true){ 730 731 // no unack packets left 732 if (l2cap_channel->unacked_frames == 0) { 733 // stop retransmission timer 734 l2cap_ertm_stop_retransmission_timer(l2cap_channel); 735 break; 736 } 737 738 tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index]; 739 // calc delta 740 int delta = (req_seq - tx_state->tx_seq) & 0x03f; 741 if (delta == 0) break; // all packets acknowledged 742 if (delta > l2cap_channel->remote_tx_window_size) break; 743 744 num_buffers_acked++; 745 l2cap_channel->num_stored_tx_frames--; 746 l2cap_channel->unacked_frames--; 747 log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq); 748 749 l2cap_channel->tx_read_index++; 750 if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){ 751 l2cap_channel->tx_read_index = 0; 752 } 753 } 754 if (num_buffers_acked){ 755 log_info("num_buffers_acked %u", num_buffers_acked); 756 l2cap_ertm_notify_channel_can_send(l2cap_channel); 757 } 758 } 759 760 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){ 761 int i; 762 for (i=0;i<l2cap_channel->num_tx_buffers;i++){ 763 l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i]; 764 if (tx_state->tx_seq == tx_seq) return tx_state; 765 } 766 return NULL; 767 } 768 769 // @param delta number of frames in the future, >= 1 770 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler) 771 static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, const uint8_t * payload, uint16_t size){ 772 log_info("Store SDU with delta %u", delta); 773 // get rx state for packet to store 774 int index = l2cap_channel->rx_store_index + delta - 1; 775 if (index > l2cap_channel->num_rx_buffers){ 776 index -= l2cap_channel->num_rx_buffers; 777 } 778 log_info("Index of packet to store %u", index); 779 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index]; 780 // check if buffer is free 781 if (rx_state->valid){ 782 log_error("Packet buffer already used"); 783 return; 784 } 785 rx_state->valid = 1; 786 rx_state->sar = sar; 787 rx_state->len = size; 788 uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index]; 789 (void)memcpy(rx_buffer, payload, size); 790 } 791 792 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler) 793 static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, const uint8_t * payload, uint16_t size){ 794 uint16_t reassembly_sdu_length; 795 switch (sar){ 796 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU: 797 // assert total packet size <= our mtu 798 if (size > l2cap_channel->local_mtu) break; 799 // packet complete -> disapatch 800 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size); 801 break; 802 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU: 803 // read SDU len 804 reassembly_sdu_length = little_endian_read_16(payload, 0); 805 payload += 2; 806 size -= 2; 807 // assert reassembled size <= our mtu 808 if (reassembly_sdu_length > l2cap_channel->local_mtu) break; 809 // store start segment 810 l2cap_channel->reassembly_sdu_length = reassembly_sdu_length; 811 (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size); 812 l2cap_channel->reassembly_pos = size; 813 break; 814 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU: 815 // assert size of reassembled data <= our mtu 816 if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break; 817 // store continuation segment 818 (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], 819 payload, size); 820 l2cap_channel->reassembly_pos += size; 821 break; 822 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU: 823 // assert size of reassembled data <= our mtu 824 if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break; 825 // store continuation segment 826 (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], 827 payload, size); 828 l2cap_channel->reassembly_pos += size; 829 // assert size of reassembled data matches announced sdu length 830 if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break; 831 // packet complete -> disapatch 832 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos); 833 l2cap_channel->reassembly_pos = 0; 834 break; 835 default: 836 btstack_assert(false); 837 break; 838 } 839 } 840 841 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){ 842 channel->unacked_frames++; 843 int index = channel->tx_send_index; 844 channel->tx_send_index++; 845 if (channel->tx_send_index >= channel->num_tx_buffers){ 846 channel->tx_send_index = 0; 847 } 848 l2cap_ertm_send_information_frame(channel, index, 0); // final = 0 849 } 850 851 #endif 852 853 #ifdef L2CAP_USES_CHANNELS 854 static uint16_t l2cap_next_local_cid(void){ 855 do { 856 if (local_source_cid == 0xffffu) { 857 local_source_cid = 0x40; 858 } else { 859 local_source_cid++; 860 } 861 } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL); 862 return local_source_cid; 863 } 864 #endif 865 866 static uint8_t l2cap_next_sig_id(void){ 867 if (sig_seq_nr == 0xffu) { 868 sig_seq_nr = 1; 869 } else { 870 sig_seq_nr++; 871 } 872 return sig_seq_nr; 873 } 874 875 void l2cap_init(void){ 876 signaling_responses_pending = 0; 877 878 l2cap_channels = NULL; 879 880 #ifdef ENABLE_CLASSIC 881 l2cap_services = NULL; 882 require_security_level2_for_outgoing_sdp = 0; 883 884 // Setup Connectionless Channel 885 l2cap_fixed_channel_connectionless.local_cid = L2CAP_CID_CONNECTIONLESS_CHANNEL; 886 l2cap_fixed_channel_connectionless.channel_type = L2CAP_CHANNEL_TYPE_CONNECTIONLESS; 887 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless); 888 #endif 889 890 #ifdef ENABLE_LE_DATA_CHANNELS 891 l2cap_le_services = NULL; 892 #endif 893 894 #ifdef ENABLE_BLE 895 l2cap_event_packet_handler = NULL; 896 l2cap_le_custom_max_mtu = 0; 897 898 // Setup fixed ATT Channel 899 l2cap_fixed_channel_att.local_cid = L2CAP_CID_ATTRIBUTE_PROTOCOL; 900 l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED; 901 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att); 902 903 // Setup fixed SM Channel 904 l2cap_fixed_channel_sm.local_cid = L2CAP_CID_SECURITY_MANAGER_PROTOCOL; 905 l2cap_fixed_channel_sm.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED; 906 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm); 907 #endif 908 909 // 910 // register callback with HCI 911 // 912 hci_event_callback_registration.callback = &l2cap_hci_event_handler; 913 hci_add_event_handler(&hci_event_callback_registration); 914 915 hci_register_acl_packet_handler(&l2cap_acl_handler); 916 917 #ifdef ENABLE_CLASSIC 918 gap_connectable_control(0); // no services yet 919 #endif 920 } 921 922 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){ 923 #ifdef ENABLE_BLE 924 l2cap_event_packet_handler = handler; 925 #else 926 UNUSED(handler); // ok: no code 927 #endif 928 } 929 930 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){ 931 UNUSED(con_handle); // ok: there is no con handle 932 933 l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id); 934 if (!channel) return; 935 channel->waiting_for_can_send_now = 1; 936 l2cap_notify_channel_can_send(); 937 } 938 939 int l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){ 940 UNUSED(channel_id); // ok: only depends on Controller LE buffers 941 942 return hci_can_send_acl_packet_now(con_handle); 943 } 944 945 uint8_t *l2cap_get_outgoing_buffer(void){ 946 return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes 947 } 948 949 // only for L2CAP Basic Channels 950 int l2cap_reserve_packet_buffer(void){ 951 return hci_reserve_packet_buffer(); 952 } 953 954 // only for L2CAP Basic Channels 955 void l2cap_release_packet_buffer(void){ 956 hci_release_packet_buffer(); 957 } 958 959 static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){ 960 // 0 - Connection handle : PB=pb : BC=00 961 little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u)); 962 // 2 - ACL length 963 little_endian_store_16(acl_buffer, 2u, len + 4u); 964 // 4 - L2CAP packet length 965 little_endian_store_16(acl_buffer, 4u, len + 0u); 966 // 6 - L2CAP channel DEST 967 little_endian_store_16(acl_buffer, 6, remote_cid); 968 } 969 970 // assumption - only on LE connections 971 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){ 972 973 if (!hci_is_packet_buffer_reserved()){ 974 log_error("l2cap_send_prepared_connectionless called without reserving packet first"); 975 return BTSTACK_ACL_BUFFERS_FULL; 976 } 977 978 if (!hci_can_send_prepared_acl_packet_now(con_handle)){ 979 log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid); 980 return BTSTACK_ACL_BUFFERS_FULL; 981 } 982 983 log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid); 984 985 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 986 l2cap_setup_header(acl_buffer, con_handle, 0, cid, len); 987 // send 988 return hci_send_acl_packet_buffer(len+8u); 989 } 990 991 // assumption - only on LE connections 992 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){ 993 994 if (!hci_can_send_acl_packet_now(con_handle)){ 995 log_info("l2cap_send cid 0x%02x, cannot send", cid); 996 return BTSTACK_ACL_BUFFERS_FULL; 997 } 998 999 hci_reserve_packet_buffer(); 1000 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1001 1002 (void)memcpy(&acl_buffer[8], data, len); 1003 1004 return l2cap_send_prepared_connectionless(con_handle, cid, len); 1005 } 1006 1007 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) { 1008 log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel); 1009 uint8_t event[4]; 1010 event[0] = L2CAP_EVENT_CAN_SEND_NOW; 1011 event[1] = sizeof(event) - 2u; 1012 little_endian_store_16(event, 2, channel); 1013 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1014 packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event)); 1015 } 1016 1017 #ifdef L2CAP_USES_CHANNELS 1018 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){ 1019 (* (channel->packet_handler))(type, channel->local_cid, data, size); 1020 } 1021 1022 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){ 1023 uint8_t event[4]; 1024 event[0] = event_code; 1025 event[1] = sizeof(event) - 2u; 1026 little_endian_store_16(event, 2, channel->local_cid); 1027 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1028 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 1029 } 1030 #endif 1031 1032 #ifdef ENABLE_CLASSIC 1033 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) { 1034 log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u", 1035 status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, 1036 channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout); 1037 uint8_t event[26]; 1038 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 1039 event[1] = sizeof(event) - 2; 1040 event[2] = status; 1041 reverse_bd_addr(channel->address, &event[3]); 1042 little_endian_store_16(event, 9, channel->con_handle); 1043 little_endian_store_16(event, 11, channel->psm); 1044 little_endian_store_16(event, 13, channel->local_cid); 1045 little_endian_store_16(event, 15, channel->remote_cid); 1046 little_endian_store_16(event, 17, channel->local_mtu); 1047 little_endian_store_16(event, 19, channel->remote_mtu); 1048 little_endian_store_16(event, 21, channel->flush_timeout); 1049 event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0; 1050 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1051 log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option); 1052 event[24] = channel->mode; 1053 event[25] = channel->fcs_option; 1054 1055 #else 1056 event[24] = L2CAP_CHANNEL_MODE_BASIC; 1057 event[25] = 0; 1058 #endif 1059 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1060 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 1061 } 1062 1063 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) { 1064 log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid); 1065 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED); 1066 } 1067 1068 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) { 1069 log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x", 1070 bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid); 1071 uint8_t event[16]; 1072 event[0] = L2CAP_EVENT_INCOMING_CONNECTION; 1073 event[1] = sizeof(event) - 2; 1074 reverse_bd_addr(channel->address, &event[2]); 1075 little_endian_store_16(event, 8, channel->con_handle); 1076 little_endian_store_16(event, 10, channel->psm); 1077 little_endian_store_16(event, 12, channel->local_cid); 1078 little_endian_store_16(event, 14, channel->remote_cid); 1079 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1080 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 1081 } 1082 1083 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){ 1084 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1085 // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released 1086 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1087 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED); 1088 } 1089 #endif 1090 l2cap_emit_channel_opened(channel, status); 1091 } 1092 1093 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){ 1094 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1095 // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released 1096 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1097 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED); 1098 } 1099 #endif 1100 l2cap_emit_channel_closed(channel); 1101 } 1102 #endif 1103 1104 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){ 1105 btstack_linked_list_iterator_t it; 1106 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1107 while (btstack_linked_list_iterator_has_next(&it)){ 1108 l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it); 1109 if (channel->local_cid == cid) { 1110 return channel; 1111 } 1112 } 1113 return NULL; 1114 } 1115 1116 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04 1117 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){ 1118 if (local_cid >= 0x40u) return NULL; 1119 return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid); 1120 } 1121 1122 // used for Classic Channels + LE Data Channels. local_cid >= 0x40 1123 #ifdef L2CAP_USES_CHANNELS 1124 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){ 1125 if (local_cid < 0x40u) return NULL; 1126 return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid); 1127 } 1128 1129 void l2cap_request_can_send_now_event(uint16_t local_cid){ 1130 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 1131 if (!channel) return; 1132 channel->waiting_for_can_send_now = 1; 1133 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1134 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1135 l2cap_ertm_notify_channel_can_send(channel); 1136 return; 1137 } 1138 #endif 1139 l2cap_notify_channel_can_send(); 1140 } 1141 1142 int l2cap_can_send_packet_now(uint16_t local_cid){ 1143 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 1144 if (!channel) return 0; 1145 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1146 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1147 return l2cap_ertm_can_store_packet_now(channel); 1148 } 1149 #endif 1150 return hci_can_send_acl_packet_now(channel->con_handle); 1151 } 1152 1153 int l2cap_can_send_prepared_packet_now(uint16_t local_cid){ 1154 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 1155 if (!channel) return 0; 1156 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1157 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1158 return 0; 1159 } 1160 #endif 1161 return hci_can_send_prepared_acl_packet_now(channel->con_handle); 1162 } 1163 1164 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){ 1165 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1166 if (channel) { 1167 return channel->remote_mtu; 1168 } 1169 return 0; 1170 } 1171 #endif 1172 1173 #ifdef L2CAP_USES_CHANNELS 1174 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){ 1175 switch (channel_type){ 1176 case L2CAP_CHANNEL_TYPE_CLASSIC: 1177 case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL: 1178 return 1; 1179 default: 1180 return 0; 1181 } 1182 } 1183 #endif 1184 1185 #ifdef ENABLE_CLASSIC 1186 // RTX Timer only exist for dynamic channels 1187 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){ 1188 btstack_linked_list_iterator_t it; 1189 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1190 while (btstack_linked_list_iterator_has_next(&it)){ 1191 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1192 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 1193 if (&channel->rtx == ts) { 1194 return channel; 1195 } 1196 } 1197 return NULL; 1198 } 1199 1200 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){ 1201 l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts); 1202 if (!channel) return; 1203 1204 log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid); 1205 1206 // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq 1207 // and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state." 1208 // notify client 1209 l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT); 1210 1211 // discard channel 1212 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 1213 l2cap_free_channel_entry(channel); 1214 } 1215 1216 #endif 1217 1218 #ifdef L2CAP_USES_CHANNELS 1219 static void l2cap_stop_rtx(l2cap_channel_t * channel){ 1220 log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid); 1221 btstack_run_loop_remove_timer(&channel->rtx); 1222 } 1223 #endif 1224 1225 #ifdef ENABLE_CLASSIC 1226 1227 static void l2cap_start_rtx(l2cap_channel_t * channel){ 1228 l2cap_stop_rtx(channel); 1229 log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid); 1230 btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout); 1231 btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS); 1232 btstack_run_loop_add_timer(&channel->rtx); 1233 } 1234 1235 static void l2cap_start_ertx(l2cap_channel_t * channel){ 1236 log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid); 1237 l2cap_stop_rtx(channel); 1238 btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout); 1239 btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS); 1240 btstack_run_loop_add_timer(&channel->rtx); 1241 } 1242 1243 void l2cap_require_security_level_2_for_outgoing_sdp(void){ 1244 require_security_level2_for_outgoing_sdp = 1; 1245 } 1246 1247 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){ 1248 return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp); 1249 } 1250 1251 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){ 1252 if (!hci_can_send_acl_packet_now(handle)){ 1253 log_info("l2cap_send_signaling_packet, cannot send"); 1254 return BTSTACK_ACL_BUFFERS_FULL; 1255 } 1256 1257 // log_info("l2cap_send_signaling_packet type %u", cmd); 1258 hci_reserve_packet_buffer(); 1259 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1260 va_list argptr; 1261 va_start(argptr, identifier); 1262 uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr); 1263 va_end(argptr); 1264 // log_info("l2cap_send_signaling_packet con %u!", handle); 1265 return hci_send_acl_packet_buffer(len); 1266 } 1267 1268 // assumption - only on Classic connections 1269 // cannot be used for L2CAP ERTM 1270 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){ 1271 1272 if (!hci_is_packet_buffer_reserved()){ 1273 log_error("l2cap_send_prepared called without reserving packet first"); 1274 return BTSTACK_ACL_BUFFERS_FULL; 1275 } 1276 1277 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1278 if (!channel) { 1279 log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid); 1280 return -1; // TODO: define error 1281 } 1282 1283 if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){ 1284 log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid); 1285 return BTSTACK_ACL_BUFFERS_FULL; 1286 } 1287 1288 log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle); 1289 1290 int fcs_size = 0; 1291 1292 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1293 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){ 1294 fcs_size = 2; 1295 } 1296 #endif 1297 1298 // set non-flushable packet boundary flag if supported on Controller 1299 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1300 uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02; 1301 l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size); 1302 1303 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1304 if (fcs_size){ 1305 // calculate FCS over l2cap data 1306 uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len); 1307 log_info("I-Frame: fcs 0x%04x", fcs); 1308 little_endian_store_16(acl_buffer, 8 + len, fcs); 1309 } 1310 #endif 1311 1312 // send 1313 return hci_send_acl_packet_buffer(len+8+fcs_size); 1314 } 1315 1316 // assumption - only on Classic connections 1317 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){ 1318 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1319 if (!channel) { 1320 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 1321 return -1; // TODO: define error 1322 } 1323 1324 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1325 // send in ERTM 1326 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1327 return l2cap_ertm_send(channel, data, len); 1328 } 1329 #endif 1330 1331 if (len > channel->remote_mtu){ 1332 log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid); 1333 return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU; 1334 } 1335 1336 if (!hci_can_send_acl_packet_now(channel->con_handle)){ 1337 log_info("l2cap_send cid 0x%02x, cannot send", local_cid); 1338 return BTSTACK_ACL_BUFFERS_FULL; 1339 } 1340 1341 hci_reserve_packet_buffer(); 1342 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1343 (void)memcpy(&acl_buffer[8], data, len); 1344 return l2cap_send_prepared(local_cid, len); 1345 } 1346 1347 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){ 1348 return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data); 1349 } 1350 1351 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 1352 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag); 1353 } 1354 1355 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 1356 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag); 1357 } 1358 #endif 1359 1360 1361 #ifdef ENABLE_BLE 1362 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){ 1363 1364 if (!hci_can_send_acl_packet_now(handle)){ 1365 log_info("l2cap_send_le_signaling_packet, cannot send"); 1366 return BTSTACK_ACL_BUFFERS_FULL; 1367 } 1368 1369 // log_info("l2cap_send_le_signaling_packet type %u", cmd); 1370 hci_reserve_packet_buffer(); 1371 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1372 va_list argptr; 1373 va_start(argptr, identifier); 1374 uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr); 1375 va_end(argptr); 1376 // log_info("l2cap_send_le_signaling_packet con %u!", handle); 1377 return hci_send_acl_packet_buffer(len); 1378 } 1379 #endif 1380 1381 uint16_t l2cap_max_mtu(void){ 1382 return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE; 1383 } 1384 1385 #ifdef ENABLE_BLE 1386 uint16_t l2cap_max_le_mtu(void){ 1387 if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu; 1388 return l2cap_max_mtu(); 1389 } 1390 1391 void l2cap_set_max_le_mtu(uint16_t max_mtu){ 1392 if (max_mtu < l2cap_max_mtu()){ 1393 l2cap_le_custom_max_mtu = max_mtu; 1394 } 1395 } 1396 #endif 1397 1398 #ifdef ENABLE_CLASSIC 1399 1400 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){ 1401 config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU 1402 config_options[1] = 2; // len param 1403 little_endian_store_16(config_options, 2, mtu); 1404 return 4; 1405 } 1406 1407 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1408 static int l2cap_ertm_mode(l2cap_channel_t * channel){ 1409 hci_connection_t * connection = hci_connection_for_handle(channel->con_handle); 1410 return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) 1411 && (connection->l2cap_state.extended_feature_mask & 0x08)); 1412 } 1413 #endif 1414 1415 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){ 1416 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1417 // use ERTM options if supported by remote and channel ready to use it 1418 if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1419 return l2cap_setup_options_ertm_request(channel, config_options); 1420 } 1421 #endif 1422 uint16_t mtu = channel->local_mtu; 1423 return l2cap_setup_options_mtu(config_options, mtu); 1424 } 1425 1426 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){ 1427 uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu); 1428 return l2cap_setup_options_mtu(config_options, mtu); 1429 } 1430 1431 static uint32_t l2cap_extended_features_mask(void){ 1432 // extended features request supported, features: fixed channels, unicast connectionless data reception 1433 uint32_t features = 0x280; 1434 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1435 features |= 0x0028; 1436 #endif 1437 return features; 1438 } 1439 #endif 1440 1441 // 1442 #ifdef ENABLE_CLASSIC 1443 1444 // returns true if channel was finalized 1445 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){ 1446 1447 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1448 uint8_t config_options[18]; 1449 #else 1450 uint8_t config_options[10]; 1451 #endif 1452 1453 switch (channel->state){ 1454 1455 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 1456 case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT: 1457 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1458 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) { 1459 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND); 1460 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0); 1461 } 1462 break; 1463 1464 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 1465 if (!hci_can_send_command_packet_now()) break; 1466 // send connection request - set state first 1467 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE; 1468 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch 1469 (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6); 1470 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch()); 1471 break; 1472 1473 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE: 1474 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1475 channel->state = L2CAP_STATE_INVALID; 1476 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0); 1477 // discard channel - l2cap_finialize_channel_close without sending l2cap close event 1478 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 1479 l2cap_free_channel_entry(channel); 1480 channel = NULL; 1481 break; 1482 1483 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT: 1484 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1485 channel->state = L2CAP_STATE_CONFIG; 1486 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1487 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0); 1488 break; 1489 1490 case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST: 1491 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1492 // success, start l2cap handshake 1493 channel->local_sig_id = l2cap_next_sig_id(); 1494 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP; 1495 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid); 1496 l2cap_start_rtx(channel); 1497 break; 1498 1499 case L2CAP_STATE_CONFIG: 1500 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1501 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1502 // fallback to basic mode if ERTM requested but not not supported by remote 1503 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 1504 if (!l2cap_ertm_mode(channel)){ 1505 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED); 1506 channel->mode = L2CAP_CHANNEL_MODE_BASIC; 1507 } 1508 } 1509 #endif 1510 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){ 1511 uint16_t flags = 0; 1512 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 1513 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) { 1514 flags = 1; 1515 } else { 1516 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP); 1517 } 1518 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){ 1519 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP); 1520 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL); 1521 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1522 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){ 1523 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED); 1524 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP); 1525 uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options); 1526 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size, &config_options); 1527 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){ 1528 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM); 1529 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 1530 uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options); 1531 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options); 1532 #endif 1533 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){ 1534 channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 1535 uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options); 1536 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options); 1537 } else { 1538 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL); 1539 } 1540 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 1541 } 1542 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){ 1543 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1544 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ); 1545 channel->local_sig_id = l2cap_next_sig_id(); 1546 uint16_t options_size = l2cap_setup_options_request(channel, config_options); 1547 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options); 1548 l2cap_start_rtx(channel); 1549 } 1550 if (l2cap_channel_ready_for_open(channel)){ 1551 channel->state = L2CAP_STATE_OPEN; 1552 l2cap_emit_channel_opened(channel, 0); // success 1553 } 1554 break; 1555 1556 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 1557 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1558 channel->state = L2CAP_STATE_INVALID; 1559 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid); 1560 // we don't start an RTX timer for a disconnect - there's no point in closing the channel if the other side doesn't respond :) 1561 l2cap_finialize_channel_close(channel); // -- remove from list 1562 channel = NULL; 1563 break; 1564 1565 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 1566 if (!hci_can_send_acl_packet_now(channel->con_handle)) return false; 1567 channel->local_sig_id = l2cap_next_sig_id(); 1568 channel->state = L2CAP_STATE_WAIT_DISCONNECT; 1569 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid); 1570 break; 1571 default: 1572 break; 1573 } 1574 1575 // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE 1576 return channel == NULL; 1577 } 1578 1579 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1580 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){ 1581 1582 // ERTM mode 1583 if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return; 1584 1585 // check if we can still send 1586 if (channel->con_handle == HCI_CON_HANDLE_INVALID) return; 1587 if (!hci_can_send_acl_packet_now(channel->con_handle)) return; 1588 1589 if (channel->send_supervisor_frame_receiver_ready){ 1590 channel->send_supervisor_frame_receiver_ready = 0; 1591 log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set); 1592 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->req_seq); 1593 channel->set_final_bit_after_packet_with_poll_bit_set = 0; 1594 l2cap_ertm_send_supervisor_frame(channel, control); 1595 return; 1596 } 1597 if (channel->send_supervisor_frame_receiver_ready_poll){ 1598 channel->send_supervisor_frame_receiver_ready_poll = 0; 1599 log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq); 1600 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq); 1601 l2cap_ertm_send_supervisor_frame(channel, control); 1602 return; 1603 } 1604 if (channel->send_supervisor_frame_receiver_not_ready){ 1605 channel->send_supervisor_frame_receiver_not_ready = 0; 1606 log_info("Send S-Frame: RNR %u", channel->req_seq); 1607 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq); 1608 l2cap_ertm_send_supervisor_frame(channel, control); 1609 return; 1610 } 1611 if (channel->send_supervisor_frame_reject){ 1612 channel->send_supervisor_frame_reject = 0; 1613 log_info("Send S-Frame: REJ %u", channel->req_seq); 1614 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq); 1615 l2cap_ertm_send_supervisor_frame(channel, control); 1616 return; 1617 } 1618 if (channel->send_supervisor_frame_selective_reject){ 1619 channel->send_supervisor_frame_selective_reject = 0; 1620 log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq); 1621 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->expected_tx_seq); 1622 channel->set_final_bit_after_packet_with_poll_bit_set = 0; 1623 l2cap_ertm_send_supervisor_frame(channel, control); 1624 return; 1625 } 1626 1627 if (channel->srej_active){ 1628 int i; 1629 for (i=0;i<channel->num_tx_buffers;i++){ 1630 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i]; 1631 if (tx_state->retransmission_requested) { 1632 tx_state->retransmission_requested = 0; 1633 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set; 1634 channel->set_final_bit_after_packet_with_poll_bit_set = 0; 1635 l2cap_ertm_send_information_frame(channel, i, final); 1636 break; 1637 } 1638 } 1639 if (i == channel->num_tx_buffers){ 1640 // no retransmission request found 1641 channel->srej_active = 0; 1642 } else { 1643 // packet was sent 1644 return; 1645 } 1646 } 1647 } 1648 #endif /* ERTM */ 1649 #endif /* Classic */ 1650 1651 static void l2cap_run_signaling_response(void) { 1652 1653 // check pending signaling responses 1654 while (signaling_responses_pending){ 1655 1656 hci_con_handle_t handle = signaling_responses[0].handle; 1657 1658 if (!hci_can_send_acl_packet_now(handle)) break; 1659 1660 uint8_t sig_id = signaling_responses[0].sig_id; 1661 uint8_t response_code = signaling_responses[0].code; 1662 uint16_t result = signaling_responses[0].data; // CONNECTION_REQUEST, COMMAND_REJECT 1663 #ifdef ENABLE_CLASSIC 1664 uint16_t info_type = signaling_responses[0].data; // INFORMATION_REQUEST 1665 uint16_t source_cid = signaling_responses[0].cid; // CONNECTION_REQUEST 1666 #endif 1667 1668 // remove first item before sending (to avoid sending response mutliple times) 1669 signaling_responses_pending--; 1670 int i; 1671 for (i=0; i < signaling_responses_pending; i++){ 1672 (void)memcpy(&signaling_responses[i], 1673 &signaling_responses[i + 1], 1674 sizeof(l2cap_signaling_response_t)); 1675 } 1676 1677 switch (response_code){ 1678 #ifdef ENABLE_CLASSIC 1679 case CONNECTION_REQUEST: 1680 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0); 1681 // also disconnect if result is 0x0003 - security blocked 1682 if (result == 0x0003){ 1683 hci_disconnect_security_block(handle); 1684 } 1685 break; 1686 case ECHO_REQUEST: 1687 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL); 1688 break; 1689 case INFORMATION_REQUEST: 1690 switch (info_type){ 1691 case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: { 1692 uint16_t connectionless_mtu = hci_max_acl_data_packet_length(); 1693 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu); 1694 } 1695 break; 1696 case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: { 1697 uint32_t features = l2cap_extended_features_mask(); 1698 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features); 1699 } 1700 break; 1701 case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: { 1702 uint8_t map[8]; 1703 memset(map, 0, 8); 1704 map[0] = 0x06; // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04) 1705 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map); 1706 } 1707 break; 1708 default: 1709 // all other types are not supported 1710 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL); 1711 break; 1712 } 1713 break; 1714 case COMMAND_REJECT: 1715 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL); 1716 break; 1717 #endif 1718 #ifdef ENABLE_BLE 1719 case LE_CREDIT_BASED_CONNECTION_REQUEST: 1720 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result); 1721 break; 1722 case COMMAND_REJECT_LE: 1723 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL); 1724 break; 1725 #endif 1726 default: 1727 // should not happen 1728 break; 1729 } 1730 } 1731 } 1732 1733 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1734 static bool l2ap_run_ertm(void){ 1735 // send l2cap information request if neccessary 1736 btstack_linked_list_iterator_t it; 1737 hci_connections_get_iterator(&it); 1738 while(btstack_linked_list_iterator_has_next(&it)){ 1739 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 1740 if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){ 1741 if (!hci_can_send_acl_packet_now(connection->con_handle)) break; 1742 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE; 1743 uint8_t sig_id = l2cap_next_sig_id(); 1744 uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED; 1745 l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type); 1746 return true; 1747 } 1748 } 1749 return false; 1750 } 1751 #endif 1752 1753 #ifdef ENABLE_LE_DATA_CHANNELS 1754 static void l2cap_run_le_data_channels(void){ 1755 btstack_linked_list_iterator_t it; 1756 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1757 while (btstack_linked_list_iterator_has_next(&it)){ 1758 uint16_t mps; 1759 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1760 1761 if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue; 1762 1763 // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var); 1764 switch (channel->state){ 1765 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST: 1766 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 1767 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE; 1768 // le psm, source cid, mtu, mps, initial credits 1769 channel->local_sig_id = l2cap_next_sig_id(); 1770 channel->credits_incoming = channel->new_credits_incoming; 1771 channel->new_credits_incoming = 0; 1772 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu); 1773 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming); 1774 break; 1775 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT: 1776 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 1777 // TODO: support larger MPS 1778 channel->state = L2CAP_STATE_OPEN; 1779 channel->credits_incoming = channel->new_credits_incoming; 1780 channel->new_credits_incoming = 0; 1781 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu); 1782 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming, 0); 1783 // notify client 1784 l2cap_emit_le_channel_opened(channel, 0); 1785 break; 1786 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE: 1787 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 1788 channel->state = L2CAP_STATE_INVALID; 1789 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason); 1790 // discard channel - l2cap_finialize_channel_close without sending l2cap close event 1791 btstack_linked_list_iterator_remove(&it); 1792 l2cap_free_channel_entry(channel); 1793 break; 1794 case L2CAP_STATE_OPEN: 1795 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 1796 1797 // send credits 1798 if (channel->new_credits_incoming){ 1799 log_info("l2cap: sending %u credits", channel->new_credits_incoming); 1800 channel->local_sig_id = l2cap_next_sig_id(); 1801 uint16_t new_credits = channel->new_credits_incoming; 1802 channel->new_credits_incoming = 0; 1803 channel->credits_incoming += new_credits; 1804 l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits); 1805 } 1806 break; 1807 1808 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 1809 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 1810 channel->local_sig_id = l2cap_next_sig_id(); 1811 channel->state = L2CAP_STATE_WAIT_DISCONNECT; 1812 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid); 1813 break; 1814 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 1815 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 1816 channel->state = L2CAP_STATE_INVALID; 1817 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid); 1818 l2cap_le_finialize_channel_close(channel); // -- remove from list 1819 break; 1820 default: 1821 break; 1822 } 1823 } 1824 } 1825 #endif 1826 1827 // MARK: L2CAP_RUN 1828 // process outstanding signaling tasks 1829 static void l2cap_run(void){ 1830 1831 // log_info("l2cap_run: entered"); 1832 l2cap_run_signaling_response(); 1833 1834 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1835 bool done = l2ap_run_ertm(); 1836 if (done) return; 1837 #endif 1838 1839 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE) 1840 btstack_linked_list_iterator_t it; 1841 #endif 1842 1843 #ifdef ENABLE_CLASSIC 1844 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1845 while (btstack_linked_list_iterator_has_next(&it)){ 1846 1847 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1848 1849 if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue; 1850 1851 // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var); 1852 bool finalized = l2cap_run_for_classic_channel(channel); 1853 1854 if (!finalized) { 1855 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1856 l2cap_run_for_classic_channel_ertm(channel); 1857 #endif 1858 } 1859 } 1860 #endif 1861 1862 #ifdef ENABLE_LE_DATA_CHANNELS 1863 l2cap_run_le_data_channels(); 1864 #endif 1865 1866 #ifdef ENABLE_BLE 1867 // send l2cap con paramter update if necessary 1868 hci_connections_get_iterator(&it); 1869 while(btstack_linked_list_iterator_has_next(&it)){ 1870 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 1871 if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue; 1872 if (!hci_can_send_acl_packet_now(connection->con_handle)) continue; 1873 switch (connection->le_con_parameter_update_state){ 1874 case CON_PARAMETER_UPDATE_SEND_REQUEST: 1875 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 1876 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(), 1877 connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout); 1878 break; 1879 case CON_PARAMETER_UPDATE_SEND_RESPONSE: 1880 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 1881 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0); 1882 break; 1883 case CON_PARAMETER_UPDATE_DENY: 1884 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 1885 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1); 1886 break; 1887 default: 1888 break; 1889 } 1890 } 1891 #endif 1892 1893 // log_info("l2cap_run: exit"); 1894 } 1895 1896 #ifdef ENABLE_CLASSIC 1897 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){ 1898 if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) { 1899 log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid); 1900 // success, start l2cap handshake 1901 channel->con_handle = con_handle; 1902 // check remote SSP feature first 1903 channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES; 1904 } 1905 } 1906 1907 static void l2cap_ready_to_connect(l2cap_channel_t * channel){ 1908 1909 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1910 // assumption: outgoing connection 1911 hci_connection_t * connection = hci_connection_for_handle(channel->con_handle); 1912 if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){ 1913 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST; 1914 channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES; 1915 return; 1916 } 1917 #endif 1918 1919 // fine, go ahead 1920 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 1921 } 1922 1923 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){ 1924 if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return; 1925 1926 // we have been waiting for remote supported features 1927 if (channel->required_security_level > LEVEL_0){ 1928 // request security level 1929 channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE; 1930 gap_request_security_level(channel->con_handle, channel->required_security_level); 1931 return; 1932 } 1933 1934 l2cap_ready_to_connect(channel); 1935 } 1936 #endif 1937 1938 #ifdef L2CAP_USES_CHANNELS 1939 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type, 1940 uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){ 1941 1942 l2cap_channel_t * channel = btstack_memory_l2cap_channel_get(); 1943 if (!channel) { 1944 return NULL; 1945 } 1946 1947 // fill in 1948 channel->packet_handler = packet_handler; 1949 channel->channel_type = channel_type; 1950 bd_addr_copy(channel->address, address); 1951 channel->address_type = address_type; 1952 channel->psm = psm; 1953 channel->local_mtu = local_mtu; 1954 channel->remote_mtu = L2CAP_DEFAULT_MTU; 1955 channel->required_security_level = security_level; 1956 1957 // 1958 channel->local_cid = l2cap_next_local_cid(); 1959 channel->con_handle = HCI_CON_HANDLE_INVALID; 1960 1961 // set initial state 1962 channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION; 1963 channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE; 1964 channel->remote_sig_id = L2CAP_SIG_ID_INVALID; 1965 channel->local_sig_id = L2CAP_SIG_ID_INVALID; 1966 1967 log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid); 1968 1969 return channel; 1970 } 1971 1972 static void l2cap_free_channel_entry(l2cap_channel_t * channel){ 1973 log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid); 1974 // assert all timers are stopped 1975 l2cap_stop_rtx(channel); 1976 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 1977 l2cap_ertm_stop_retransmission_timer(channel); 1978 l2cap_ertm_stop_monitor_timer(channel); 1979 #endif 1980 // free memory 1981 btstack_memory_l2cap_channel_free(channel); 1982 } 1983 #endif 1984 1985 #ifdef ENABLE_CLASSIC 1986 1987 /** 1988 * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary. 1989 * @param packet_handler 1990 * @param address 1991 * @param psm 1992 * @param mtu 1993 * @param local_cid 1994 */ 1995 1996 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t mtu, uint16_t * out_local_cid){ 1997 // limit MTU to the size of our outgoing HCI buffer 1998 uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu()); 1999 2000 // determine security level based on psm 2001 const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level(); 2002 log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u, sec level %u", bd_addr_to_str(address), psm, mtu, local_mtu, (int) security_level); 2003 2004 l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, security_level); 2005 if (!channel) { 2006 return BTSTACK_MEMORY_ALLOC_FAILED; 2007 } 2008 2009 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2010 channel->mode = L2CAP_CHANNEL_MODE_BASIC; 2011 #endif 2012 2013 // add to connections list 2014 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel); 2015 2016 // store local_cid 2017 if (out_local_cid){ 2018 *out_local_cid = channel->local_cid; 2019 } 2020 2021 // state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION 2022 2023 // check if hci connection is already usable, 2024 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL); 2025 if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){ 2026 // simulate connection complete 2027 l2cap_handle_connection_complete(conn->con_handle, channel); 2028 2029 // state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES 2030 2031 // check if remote supported features are already received 2032 if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) { 2033 // simulate remote features received 2034 l2cap_handle_remote_supported_features_received(channel); 2035 } 2036 } 2037 2038 l2cap_run(); 2039 2040 return ERROR_CODE_SUCCESS; 2041 } 2042 2043 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){ 2044 log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason); 2045 // find channel for local_cid 2046 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 2047 if (channel) { 2048 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2049 } 2050 // process 2051 l2cap_run(); 2052 } 2053 2054 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){ 2055 // mark all channels before emitting open events as these could trigger new connetion requests to the same device 2056 btstack_linked_list_iterator_t it; 2057 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2058 while (btstack_linked_list_iterator_has_next(&it)){ 2059 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2060 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2061 if (bd_addr_cmp( channel->address, address) != 0) continue; 2062 // channel for this address found 2063 switch (channel->state){ 2064 case L2CAP_STATE_WAIT_CONNECTION_COMPLETE: 2065 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 2066 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD; 2067 break; 2068 default: 2069 break; 2070 } 2071 } 2072 // emit and free marked entries. restart loop to deal with list changes 2073 int done = 0; 2074 while (!done) { 2075 done = 1; 2076 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2077 while (btstack_linked_list_iterator_has_next(&it)){ 2078 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2079 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2080 if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){ 2081 done = 0; 2082 // failure, forward error code 2083 l2cap_handle_channel_open_failed(channel, status); 2084 // discard channel 2085 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 2086 l2cap_free_channel_entry(channel); 2087 break; 2088 } 2089 } 2090 } 2091 2092 } 2093 2094 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){ 2095 btstack_linked_list_iterator_t it; 2096 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2097 while (btstack_linked_list_iterator_has_next(&it)){ 2098 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2099 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2100 if ( ! bd_addr_cmp( channel->address, address) ){ 2101 l2cap_handle_connection_complete(handle, channel); 2102 } 2103 } 2104 // process 2105 l2cap_run(); 2106 } 2107 #endif 2108 2109 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){ 2110 switch (channel->channel_type){ 2111 #ifdef ENABLE_CLASSIC 2112 case L2CAP_CHANNEL_TYPE_CLASSIC: 2113 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2114 // send if we have more data and remote windows isn't full yet 2115 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) { 2116 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false; 2117 return hci_can_send_acl_classic_packet_now() != 0; 2118 } 2119 #endif 2120 if (!channel->waiting_for_can_send_now) return false; 2121 return (hci_can_send_acl_classic_packet_now() != 0); 2122 case L2CAP_CHANNEL_TYPE_CONNECTIONLESS: 2123 if (!channel->waiting_for_can_send_now) return false; 2124 return hci_can_send_acl_classic_packet_now() != 0; 2125 #endif 2126 #ifdef ENABLE_BLE 2127 case L2CAP_CHANNEL_TYPE_LE_FIXED: 2128 if (!channel->waiting_for_can_send_now) return false; 2129 return hci_can_send_acl_le_packet_now() != 0; 2130 #ifdef ENABLE_LE_DATA_CHANNELS 2131 case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL: 2132 if (channel->send_sdu_buffer == NULL) return false; 2133 if (channel->credits_outgoing == 0u) return false; 2134 return hci_can_send_acl_le_packet_now() != 0; 2135 #endif 2136 #endif 2137 default: 2138 return false; 2139 } 2140 } 2141 2142 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){ 2143 switch (channel->channel_type){ 2144 #ifdef ENABLE_CLASSIC 2145 case L2CAP_CHANNEL_TYPE_CLASSIC: 2146 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2147 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) { 2148 l2cap_ertm_channel_send_information_frame(channel); 2149 return; 2150 } 2151 #endif 2152 channel->waiting_for_can_send_now = 0; 2153 l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid); 2154 break; 2155 case L2CAP_CHANNEL_TYPE_CONNECTIONLESS: 2156 channel->waiting_for_can_send_now = 0; 2157 l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid); 2158 break; 2159 #endif 2160 #ifdef ENABLE_BLE 2161 case L2CAP_CHANNEL_TYPE_LE_FIXED: 2162 channel->waiting_for_can_send_now = 0; 2163 l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid); 2164 break; 2165 #ifdef ENABLE_LE_DATA_CHANNELS 2166 case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL: 2167 l2cap_le_send_pdu(channel); 2168 break; 2169 #endif 2170 #endif 2171 default: 2172 break; 2173 } 2174 } 2175 2176 static void l2cap_notify_channel_can_send(void){ 2177 bool done = false; 2178 while (!done){ 2179 done = true; 2180 btstack_linked_list_iterator_t it; 2181 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2182 while (btstack_linked_list_iterator_has_next(&it)){ 2183 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2184 bool ready = l2cap_channel_ready_to_send(channel); 2185 if (!ready) continue; 2186 2187 // requeue channel for fairness 2188 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 2189 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel); 2190 2191 // trigger sending 2192 l2cap_channel_trigger_send(channel); 2193 2194 // exit inner loop as we just broke the iterator, but try again 2195 done = false; 2196 break; 2197 } 2198 } 2199 } 2200 2201 #ifdef L2CAP_USES_CHANNELS 2202 2203 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){ 2204 // open cannot fail for for incoming connections 2205 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0; 2206 2207 // check state 2208 switch (channel->state){ 2209 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 2210 case L2CAP_STATE_WAIT_CONNECTION_COMPLETE: 2211 case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES: 2212 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE: 2213 case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT: 2214 case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES: 2215 case L2CAP_STATE_WAIT_CONNECT_RSP: 2216 case L2CAP_STATE_CONFIG: 2217 case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST: 2218 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST: 2219 case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE: 2220 case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD: 2221 return 1; 2222 2223 case L2CAP_STATE_OPEN: 2224 case L2CAP_STATE_CLOSED: 2225 case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES: 2226 case L2CAP_STATE_WAIT_DISCONNECT: 2227 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY: 2228 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE: 2229 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT: 2230 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 2231 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 2232 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE: 2233 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT: 2234 case L2CAP_STATE_INVALID: 2235 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 2236 return 0; 2237 2238 default: 2239 // get a "warning" about new states 2240 btstack_assert(false); 2241 return 0; 2242 } 2243 } 2244 #endif 2245 2246 #ifdef ENABLE_CLASSIC 2247 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){ 2248 if (l2cap_send_open_failed_on_hci_disconnect(channel)){ 2249 l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT); 2250 } else { 2251 l2cap_handle_channel_closed(channel); 2252 } 2253 l2cap_free_channel_entry(channel); 2254 } 2255 #endif 2256 2257 #ifdef ENABLE_LE_DATA_CHANNELS 2258 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){ 2259 if (l2cap_send_open_failed_on_hci_disconnect(channel)){ 2260 l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT); 2261 } else { 2262 l2cap_emit_le_channel_closed(channel); 2263 } 2264 l2cap_free_channel_entry(channel); 2265 } 2266 #endif 2267 2268 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){ 2269 2270 UNUSED(packet_type); // ok: registered with hci_event_callback_registration 2271 UNUSED(cid); // ok: there is no channel 2272 UNUSED(size); // ok: fixed format events read from HCI buffer 2273 2274 #ifdef ENABLE_CLASSIC 2275 bd_addr_t address; 2276 hci_connection_t * hci_connection; 2277 int hci_con_used; 2278 #endif 2279 #ifdef L2CAP_USES_CHANNELS 2280 hci_con_handle_t handle; 2281 btstack_linked_list_iterator_t it; 2282 #endif 2283 2284 switch(hci_event_packet_get_type(packet)){ 2285 2286 // Notify channel packet handler if they can send now 2287 case HCI_EVENT_TRANSPORT_PACKET_SENT: 2288 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 2289 case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED: 2290 l2cap_run(); // try sending signaling packets first 2291 l2cap_notify_channel_can_send(); 2292 break; 2293 2294 case HCI_EVENT_COMMAND_STATUS: 2295 #ifdef ENABLE_CLASSIC 2296 // check command status for create connection for errors 2297 if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){ 2298 // cache outgoing address and reset 2299 (void)memcpy(address, l2cap_outgoing_classic_addr, 6); 2300 memset(l2cap_outgoing_classic_addr, 0, 6); 2301 // error => outgoing connection failed 2302 uint8_t status = hci_event_command_status_get_status(packet); 2303 if (status){ 2304 l2cap_handle_connection_failed_for_addr(address, status); 2305 } 2306 } 2307 #endif 2308 l2cap_run(); // try sending signaling packets first 2309 break; 2310 2311 #ifdef ENABLE_CLASSIC 2312 // handle connection complete events 2313 case HCI_EVENT_CONNECTION_COMPLETE: 2314 reverse_bd_addr(&packet[5], address); 2315 if (packet[2] == 0){ 2316 handle = little_endian_read_16(packet, 3); 2317 l2cap_handle_connection_success_for_addr(address, handle); 2318 } else { 2319 l2cap_handle_connection_failed_for_addr(address, packet[2]); 2320 } 2321 break; 2322 2323 // handle successful create connection cancel command 2324 case HCI_EVENT_COMMAND_COMPLETE: 2325 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) { 2326 if (packet[5] == 0){ 2327 reverse_bd_addr(&packet[6], address); 2328 // CONNECTION TERMINATED BY LOCAL HOST (0X16) 2329 l2cap_handle_connection_failed_for_addr(address, 0x16); 2330 } 2331 } 2332 l2cap_run(); // try sending signaling packets first 2333 break; 2334 #endif 2335 2336 #ifdef L2CAP_USES_CHANNELS 2337 // handle disconnection complete events 2338 case HCI_EVENT_DISCONNECTION_COMPLETE: 2339 handle = little_endian_read_16(packet, 3); 2340 // send l2cap open failed or closed events for all channels on this handle and free them 2341 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2342 while (btstack_linked_list_iterator_has_next(&it)){ 2343 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2344 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2345 if (channel->con_handle != handle) continue; 2346 btstack_linked_list_iterator_remove(&it); 2347 switch(channel->channel_type){ 2348 #ifdef ENABLE_CLASSIC 2349 case L2CAP_CHANNEL_TYPE_CLASSIC: 2350 l2cap_handle_hci_disconnect_event(channel); 2351 break; 2352 #endif 2353 #ifdef ENABLE_LE_DATA_CHANNELS 2354 case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL: 2355 l2cap_handle_hci_le_disconnect_event(channel); 2356 break; 2357 #endif 2358 default: 2359 break; 2360 } 2361 } 2362 break; 2363 #endif 2364 2365 2366 // HCI Connection Timeouts 2367 #ifdef ENABLE_CLASSIC 2368 case L2CAP_EVENT_TIMEOUT_CHECK: 2369 handle = little_endian_read_16(packet, 2); 2370 if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break; 2371 if (hci_authentication_active_for_handle(handle)) break; 2372 hci_con_used = 0; 2373 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2374 while (btstack_linked_list_iterator_has_next(&it)){ 2375 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2376 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2377 if (channel->con_handle != handle) continue; 2378 hci_con_used = 1; 2379 break; 2380 } 2381 if (hci_con_used) break; 2382 if (!hci_can_send_command_packet_now()) break; 2383 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection 2384 break; 2385 2386 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 2387 case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE: 2388 handle = little_endian_read_16(packet, 3); 2389 hci_connection = hci_connection_for_handle(handle); 2390 if (hci_connection == NULL) break; 2391 if ((hci_connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) == 0) break; 2392 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2393 while (btstack_linked_list_iterator_has_next(&it)){ 2394 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2395 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2396 if (channel->con_handle != handle) continue; 2397 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state); 2398 l2cap_handle_remote_supported_features_received(channel); 2399 } 2400 break; 2401 2402 case GAP_EVENT_SECURITY_LEVEL: 2403 handle = little_endian_read_16(packet, 2); 2404 log_info("l2cap - security level update for handle 0x%04x", handle); 2405 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2406 while (btstack_linked_list_iterator_has_next(&it)){ 2407 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2408 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2409 if (channel->con_handle != handle) continue; 2410 2411 gap_security_level_t actual_level = (gap_security_level_t) packet[4]; 2412 gap_security_level_t required_level = channel->required_security_level; 2413 2414 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level); 2415 2416 switch (channel->state){ 2417 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 2418 if (actual_level >= required_level){ 2419 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2420 // we need to know if ERTM is supported before sending a config response 2421 hci_connection_t * connection = hci_connection_for_handle(channel->con_handle); 2422 if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_DONE){ 2423 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST; 2424 channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES; 2425 break; 2426 } 2427 #endif 2428 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 2429 l2cap_emit_incoming_connection(channel); 2430 } else { 2431 channel->reason = 0x0003; // security block 2432 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 2433 } 2434 break; 2435 2436 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE: 2437 if (actual_level >= required_level){ 2438 l2cap_ready_to_connect(channel); 2439 } else { 2440 // disconnnect, authentication not good enough 2441 hci_disconnect_security_block(handle); 2442 } 2443 break; 2444 2445 default: 2446 break; 2447 } 2448 } 2449 break; 2450 #endif 2451 2452 default: 2453 break; 2454 } 2455 2456 l2cap_run(); 2457 } 2458 2459 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){ 2460 // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused." 2461 if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) { 2462 signaling_responses[signaling_responses_pending].handle = handle; 2463 signaling_responses[signaling_responses_pending].code = code; 2464 signaling_responses[signaling_responses_pending].sig_id = sig_id; 2465 signaling_responses[signaling_responses_pending].cid = cid; 2466 signaling_responses[signaling_responses_pending].data = data; 2467 signaling_responses_pending++; 2468 l2cap_run(); 2469 } 2470 } 2471 2472 #ifdef ENABLE_CLASSIC 2473 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){ 2474 channel->remote_sig_id = identifier; 2475 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 2476 l2cap_run(); 2477 } 2478 2479 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){ 2480 2481 // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid); 2482 l2cap_service_t *service = l2cap_get_service(psm); 2483 if (!service) { 2484 // 0x0002 PSM not supported 2485 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002); 2486 return; 2487 } 2488 2489 hci_connection_t * hci_connection = hci_connection_for_handle( handle ); 2490 if (!hci_connection) { 2491 // 2492 log_error("no hci_connection for handle %u", handle); 2493 return; 2494 } 2495 2496 // alloc structure 2497 // log_info("l2cap_handle_connection_request register channel"); 2498 l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL, 2499 psm, service->mtu, service->required_security_level); 2500 if (!channel){ 2501 // 0x0004 No resources available 2502 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004); 2503 return; 2504 } 2505 2506 channel->con_handle = handle; 2507 channel->remote_cid = source_cid; 2508 channel->remote_sig_id = sig_id; 2509 2510 // limit local mtu to max acl packet length - l2cap header 2511 if (channel->local_mtu > l2cap_max_mtu()) { 2512 channel->local_mtu = l2cap_max_mtu(); 2513 } 2514 2515 // set initial state 2516 channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE; 2517 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING); 2518 2519 // add to connections list 2520 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel); 2521 2522 // assert security requirements 2523 gap_request_security_level(handle, channel->required_security_level); 2524 } 2525 2526 void l2cap_accept_connection(uint16_t local_cid){ 2527 log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid); 2528 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 2529 if (!channel) { 2530 log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid); 2531 return; 2532 } 2533 2534 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2535 // configure L2CAP Basic mode 2536 channel->mode = L2CAP_CHANNEL_MODE_BASIC; 2537 #endif 2538 2539 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 2540 2541 // process 2542 l2cap_run(); 2543 } 2544 2545 void l2cap_decline_connection(uint16_t local_cid){ 2546 log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid); 2547 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 2548 if (!channel) { 2549 log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid); 2550 return; 2551 } 2552 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 2553 channel->reason = 0x04; // no resources available 2554 l2cap_run(); 2555 } 2556 2557 // @pre command len is valid, see check in l2cap_signaling_handler_channel 2558 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){ 2559 2560 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2561 uint8_t use_fcs = 1; 2562 #endif 2563 2564 channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 2565 2566 uint16_t flags = little_endian_read_16(command, 6); 2567 if (flags & 1) { 2568 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 2569 } 2570 2571 // accept the other's configuration options 2572 uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 2573 uint16_t pos = 8; 2574 while (pos < end_pos){ 2575 uint8_t option_hint = command[pos] >> 7; 2576 uint8_t option_type = command[pos] & 0x7f; 2577 // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type); 2578 pos++; 2579 uint8_t length = command[pos++]; 2580 // MTU { type(8): 1, len(8):2, MTU(16) } 2581 if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){ 2582 channel->remote_mtu = little_endian_read_16(command, pos); 2583 log_info("Remote MTU %u", channel->remote_mtu); 2584 if (channel->remote_mtu > l2cap_max_mtu()){ 2585 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu()); 2586 channel->remote_mtu = l2cap_max_mtu(); 2587 } 2588 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 2589 } 2590 // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)} 2591 if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){ 2592 channel->flush_timeout = little_endian_read_16(command, pos); 2593 log_info("Flush timeout: %u ms", channel->flush_timeout); 2594 } 2595 2596 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2597 // Retransmission and Flow Control Option 2598 if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){ 2599 l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos]; 2600 switch(channel->mode){ 2601 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION: 2602 // Store remote config 2603 channel->remote_tx_window_size = command[pos+1]; 2604 channel->remote_max_transmit = command[pos+2]; 2605 channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3); 2606 channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5); 2607 channel->remote_mps = little_endian_read_16(command, pos + 7); 2608 log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u", 2609 channel->remote_tx_window_size, 2610 channel->remote_max_transmit, 2611 channel->remote_retransmission_timeout_ms, 2612 channel->remote_monitor_timeout_ms, 2613 channel->remote_mps); 2614 // If ERTM mandatory, but remote doens't offer ERTM -> disconnect 2615 if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 2616 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2617 } else { 2618 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM); 2619 } 2620 break; 2621 case L2CAP_CHANNEL_MODE_BASIC: 2622 switch (mode){ 2623 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION: 2624 // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time 2625 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){ 2626 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2627 } 2628 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED); 2629 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED); 2630 break; 2631 default: // case L2CAP_CHANNEL_MODE_BASIC: 2632 // TODO store and evaluate configuration 2633 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM); 2634 break; 2635 } 2636 break; 2637 default: 2638 break; 2639 } 2640 } 2641 if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){ 2642 use_fcs = command[pos]; 2643 } 2644 #endif 2645 // check for unknown options 2646 if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){ 2647 log_info("l2cap cid %u, unknown options", channel->local_cid); 2648 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID); 2649 } 2650 pos += length; 2651 } 2652 2653 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2654 // "FCS" has precedence over "No FCS" 2655 uint8_t update = channel->fcs_option || use_fcs; 2656 log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update); 2657 channel->fcs_option = update; 2658 // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect 2659 if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){ 2660 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2661 } 2662 #endif 2663 } 2664 2665 // @pre command len is valid, see check in l2cap_signaling_handler_channel 2666 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){ 2667 log_info("l2cap_signaling_handle_configure_response"); 2668 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2669 uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 2670 uint16_t pos = 10; 2671 while (pos < end_pos){ 2672 uint8_t option_hint = command[pos] >> 7; 2673 uint8_t option_type = command[pos] & 0x7f; 2674 // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type); 2675 pos++; 2676 uint8_t length = command[pos++]; 2677 2678 // Retransmission and Flow Control Option 2679 if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){ 2680 switch (channel->mode){ 2681 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION: 2682 if (channel->ertm_mandatory){ 2683 // ?? 2684 } else { 2685 // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode 2686 if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){ 2687 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED); 2688 channel->mode = L2CAP_CHANNEL_MODE_BASIC; 2689 } 2690 } 2691 break; 2692 case L2CAP_CHANNEL_MODE_BASIC: 2693 if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){ 2694 // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect 2695 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2696 } 2697 break; 2698 default: 2699 break; 2700 } 2701 } 2702 2703 // check for unknown options 2704 if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){ 2705 log_info("l2cap cid %u, unknown options", channel->local_cid); 2706 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID); 2707 } 2708 2709 pos += length; 2710 } 2711 #else 2712 UNUSED(channel); // ok: no code 2713 UNUSED(result); // ok: no code 2714 UNUSED(command); // ok: no code 2715 #endif 2716 } 2717 2718 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){ 2719 // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var); 2720 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0; 2721 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0; 2722 // addition check that fixes re-entrance issue causing l2cap event channel opened twice 2723 if (channel->state == L2CAP_STATE_OPEN) return 0; 2724 return 1; 2725 } 2726 2727 2728 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch 2729 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){ 2730 2731 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 2732 uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 2733 uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 2734 uint16_t result = 0; 2735 2736 log_info("L2CAP signaling handler code %u, state %u", code, channel->state); 2737 2738 // handle DISCONNECT REQUESTS seperately 2739 if (code == DISCONNECTION_REQUEST){ 2740 switch (channel->state){ 2741 case L2CAP_STATE_CONFIG: 2742 case L2CAP_STATE_OPEN: 2743 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 2744 case L2CAP_STATE_WAIT_DISCONNECT: 2745 l2cap_handle_disconnect_request(channel, identifier); 2746 break; 2747 2748 default: 2749 // ignore in other states 2750 break; 2751 } 2752 return; 2753 } 2754 2755 // @STATEMACHINE(l2cap) 2756 switch (channel->state) { 2757 2758 case L2CAP_STATE_WAIT_CONNECT_RSP: 2759 switch (code){ 2760 case CONNECTION_RESPONSE: 2761 if (cmd_len < 8){ 2762 // command imcomplete 2763 l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN); 2764 break; 2765 } 2766 l2cap_stop_rtx(channel); 2767 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 2768 switch (result) { 2769 case 0: 2770 // successful connection 2771 channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 2772 channel->state = L2CAP_STATE_CONFIG; 2773 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 2774 break; 2775 case 1: 2776 // connection pending. get some coffee, but start the ERTX 2777 l2cap_start_ertx(channel); 2778 break; 2779 default: 2780 // channel closed 2781 channel->state = L2CAP_STATE_CLOSED; 2782 // map l2cap connection response result to BTstack status enumeration 2783 l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result); 2784 2785 // drop link key if security block 2786 if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){ 2787 gap_drop_link_key_for_bd_addr(channel->address); 2788 } 2789 2790 // discard channel 2791 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 2792 l2cap_free_channel_entry(channel); 2793 break; 2794 } 2795 break; 2796 2797 default: 2798 //@TODO: implement other signaling packets 2799 break; 2800 } 2801 break; 2802 2803 case L2CAP_STATE_CONFIG: 2804 switch (code) { 2805 case CONFIGURE_REQUEST: 2806 if (cmd_len < 4){ 2807 // command incomplete 2808 l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN); 2809 break; 2810 } 2811 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 2812 l2cap_signaling_handle_configure_request(channel, command); 2813 if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){ 2814 // only done if continuation not set 2815 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ); 2816 } 2817 break; 2818 case CONFIGURE_RESPONSE: 2819 if (cmd_len < 6){ 2820 // command incomplete 2821 l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN); 2822 break; 2823 } 2824 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 2825 l2cap_stop_rtx(channel); 2826 l2cap_signaling_handle_configure_response(channel, result, command); 2827 switch (result){ 2828 case 0: // success 2829 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP); 2830 break; 2831 case 4: // pending 2832 l2cap_start_ertx(channel); 2833 break; 2834 default: 2835 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2836 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){ 2837 // remote does not offer ertm but it's required 2838 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2839 break; 2840 } 2841 #endif 2842 // retry on negative result 2843 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 2844 break; 2845 } 2846 break; 2847 default: 2848 break; 2849 } 2850 if (l2cap_channel_ready_for_open(channel)){ 2851 2852 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2853 // assert that packet can be stored in fragment buffers in ertm 2854 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 2855 uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps); 2856 uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2; 2857 if (usable_mtu < channel->remote_mtu){ 2858 log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu); 2859 channel->remote_mtu = usable_mtu; 2860 } 2861 } 2862 #endif 2863 // for open: 2864 channel->state = L2CAP_STATE_OPEN; 2865 l2cap_emit_channel_opened(channel, 0); 2866 } 2867 break; 2868 2869 case L2CAP_STATE_WAIT_DISCONNECT: 2870 switch (code) { 2871 case DISCONNECTION_RESPONSE: 2872 l2cap_finialize_channel_close(channel); 2873 break; 2874 default: 2875 //@TODO: implement other signaling packets 2876 break; 2877 } 2878 break; 2879 2880 case L2CAP_STATE_CLOSED: 2881 // @TODO handle incoming requests 2882 break; 2883 2884 case L2CAP_STATE_OPEN: 2885 //@TODO: implement other signaling packets, e.g. re-configure 2886 break; 2887 default: 2888 break; 2889 } 2890 // log_info("new state %u", channel->state); 2891 } 2892 2893 2894 // @pre command len is valid, see check in l2cap_acl_classic_handler 2895 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){ 2896 2897 btstack_linked_list_iterator_t it; 2898 2899 // get code, signalind identifier and command len 2900 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 2901 uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 2902 uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 2903 2904 // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE 2905 if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){ 2906 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN); 2907 return; 2908 } 2909 2910 // general commands without an assigned channel 2911 switch(code) { 2912 2913 case CONNECTION_REQUEST: 2914 if (cmd_len == 4){ 2915 uint16_t psm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 2916 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 2917 l2cap_handle_connection_request(handle, sig_id, psm, source_cid); 2918 } else { 2919 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN); 2920 } 2921 return; 2922 2923 case ECHO_REQUEST: 2924 l2cap_register_signaling_response(handle, code, sig_id, 0, 0); 2925 return; 2926 2927 case INFORMATION_REQUEST: 2928 if (cmd_len == 2) { 2929 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 2930 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type); 2931 } else { 2932 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN); 2933 } 2934 return; 2935 2936 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 2937 case INFORMATION_RESPONSE: { 2938 hci_connection_t * connection = hci_connection_for_handle(handle); 2939 if (!connection) return; 2940 if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return; 2941 2942 // get extended features from response if valid 2943 connection->l2cap_state.extended_feature_mask = 0; 2944 if (cmd_len >= 6) { 2945 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 2946 uint16_t result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 2947 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) { 2948 connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 2949 } 2950 } 2951 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE; 2952 log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask); 2953 2954 // trigger connection request 2955 btstack_linked_list_iterator_init(&it, &l2cap_channels); 2956 while (btstack_linked_list_iterator_has_next(&it)){ 2957 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2958 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 2959 if (channel->con_handle != handle) continue; 2960 2961 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory 2962 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){ 2963 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 2964 l2cap_emit_incoming_connection(channel); 2965 continue; 2966 } 2967 2968 // outgoing connection 2969 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){ 2970 2971 // if ERTM was requested, but is not listed in extended feature mask: 2972 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){ 2973 2974 if (channel->ertm_mandatory){ 2975 // bail if ERTM is mandatory 2976 channel->state = L2CAP_STATE_CLOSED; 2977 // map l2cap connection response result to BTstack status enumeration 2978 l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED); 2979 // discard channel 2980 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 2981 l2cap_free_channel_entry(channel); 2982 continue; 2983 2984 } else { 2985 // fallback to Basic mode 2986 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED); 2987 channel->mode = L2CAP_CHANNEL_MODE_BASIC; 2988 } 2989 } 2990 2991 // respond to connection request 2992 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 2993 continue; 2994 } 2995 } 2996 return; 2997 } 2998 #endif 2999 3000 default: 3001 break; 3002 } 3003 3004 // Get potential destination CID 3005 uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 3006 3007 // Find channel for this sig_id and connection handle 3008 btstack_linked_list_iterator_init(&it, &l2cap_channels); 3009 while (btstack_linked_list_iterator_has_next(&it)){ 3010 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 3011 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 3012 if (channel->con_handle != handle) continue; 3013 if (code & 1) { 3014 // match odd commands (responses) by previous signaling identifier 3015 if (channel->local_sig_id == sig_id) { 3016 l2cap_signaling_handler_channel(channel, command); 3017 break; 3018 } 3019 } else { 3020 // match even commands (requests) by local channel id 3021 if (channel->local_cid == dest_cid) { 3022 l2cap_signaling_handler_channel(channel, command); 3023 break; 3024 } 3025 } 3026 } 3027 } 3028 #endif 3029 3030 #ifdef ENABLE_BLE 3031 3032 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){ 3033 uint8_t event[6]; 3034 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE; 3035 event[1] = 4; 3036 little_endian_store_16(event, 2, con_handle); 3037 little_endian_store_16(event, 4, result); 3038 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 3039 if (!l2cap_event_packet_handler) return; 3040 (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event)); 3041 } 3042 3043 // @returns valid 3044 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){ 3045 hci_connection_t * connection; 3046 uint16_t result; 3047 uint8_t event[12]; 3048 3049 #ifdef ENABLE_LE_DATA_CHANNELS 3050 btstack_linked_list_iterator_t it; 3051 l2cap_channel_t * channel; 3052 uint16_t local_cid; 3053 uint16_t le_psm; 3054 uint16_t new_credits; 3055 uint16_t credits_before; 3056 l2cap_service_t * service; 3057 uint16_t source_cid; 3058 #endif 3059 3060 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 3061 uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 3062 log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len); 3063 3064 switch (code){ 3065 3066 case CONNECTION_PARAMETER_UPDATE_REQUEST: 3067 // check size 3068 if (len < 8u) return 0u; 3069 connection = hci_connection_for_handle(handle); 3070 if (connection){ 3071 if (connection->role != HCI_ROLE_MASTER){ 3072 // reject command without notifying upper layer when not in master role 3073 return 0; 3074 } 3075 le_connection_parameter_range_t existing_range; 3076 gap_get_connection_parameter_range(&existing_range); 3077 uint16_t le_conn_interval_min = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 3078 uint16_t le_conn_interval_max = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 3079 uint16_t le_conn_latency = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 3080 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6); 3081 3082 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout); 3083 if (update_parameter){ 3084 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE; 3085 connection->le_conn_interval_min = le_conn_interval_min; 3086 connection->le_conn_interval_max = le_conn_interval_max; 3087 connection->le_conn_latency = le_conn_latency; 3088 connection->le_supervision_timeout = le_supervision_timeout; 3089 } else { 3090 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY; 3091 } 3092 connection->le_con_param_update_identifier = sig_id; 3093 } 3094 3095 if (!l2cap_event_packet_handler) break; 3096 3097 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST; 3098 event[1] = 8; 3099 little_endian_store_16(event, 2, handle); 3100 (void)memcpy(&event[4], &command[4], 8); 3101 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 3102 (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event)); 3103 break; 3104 3105 case CONNECTION_PARAMETER_UPDATE_RESPONSE: 3106 // check size 3107 if (len < 2u) return 0u; 3108 result = little_endian_read_16(command, 4); 3109 l2cap_emit_connection_parameter_update_response(handle, result); 3110 break; 3111 3112 #ifdef ENABLE_LE_DATA_CHANNELS 3113 3114 case COMMAND_REJECT: 3115 // Find channel for this sig_id and connection handle 3116 channel = NULL; 3117 btstack_linked_list_iterator_init(&it, &l2cap_channels); 3118 while (btstack_linked_list_iterator_has_next(&it)){ 3119 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 3120 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue; 3121 if (a_channel->con_handle != handle) continue; 3122 if (a_channel->local_sig_id != sig_id) continue; 3123 channel = a_channel; 3124 break; 3125 } 3126 if (!channel) break; 3127 3128 // if received while waiting for le connection response, assume legacy device 3129 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){ 3130 channel->state = L2CAP_STATE_CLOSED; 3131 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002 3132 l2cap_emit_le_channel_opened(channel, 0x0002); 3133 3134 // discard channel 3135 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 3136 l2cap_free_channel_entry(channel); 3137 break; 3138 } 3139 break; 3140 3141 case LE_CREDIT_BASED_CONNECTION_REQUEST: 3142 // check size 3143 if (len < 10u) return 0u; 3144 3145 // get hci connection, bail if not found (must not happen) 3146 connection = hci_connection_for_handle(handle); 3147 if (!connection) return 0; 3148 3149 // check if service registered 3150 le_psm = little_endian_read_16(command, 4); 3151 service = l2cap_le_get_service(le_psm); 3152 source_cid = little_endian_read_16(command, 6); 3153 3154 if (service){ 3155 if (source_cid < 0x40u){ 3156 // 0x0009 Connection refused - Invalid Source CID 3157 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009); 3158 return 1; 3159 } 3160 3161 // go through list of channels for this ACL connection and check if we get a match 3162 btstack_linked_list_iterator_init(&it, &l2cap_channels); 3163 while (btstack_linked_list_iterator_has_next(&it)){ 3164 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 3165 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue; 3166 if (a_channel->con_handle != handle) continue; 3167 if (a_channel->remote_cid != source_cid) continue; 3168 // 0x000a Connection refused - Source CID already allocated 3169 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a); 3170 return 1; 3171 } 3172 3173 // security: check encryption 3174 if (service->required_security_level >= LEVEL_2){ 3175 if (gap_encryption_key_size(handle) == 0){ 3176 // 0x0008 Connection refused - insufficient encryption 3177 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008); 3178 return 1; 3179 } 3180 // anything less than 16 byte key size is insufficient 3181 if (gap_encryption_key_size(handle) < 16){ 3182 // 0x0007 Connection refused – insufficient encryption key size 3183 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007); 3184 return 1; 3185 } 3186 } 3187 3188 // security: check authencation 3189 if (service->required_security_level >= LEVEL_3){ 3190 if (!gap_authenticated(handle)){ 3191 // 0x0005 Connection refused – insufficient authentication 3192 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005); 3193 return 1; 3194 } 3195 } 3196 3197 // security: check authorization 3198 if (service->required_security_level >= LEVEL_4){ 3199 if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){ 3200 // 0x0006 Connection refused – insufficient authorization 3201 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006); 3202 return 1; 3203 } 3204 } 3205 3206 // allocate channel 3207 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, 3208 BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level); 3209 if (!channel){ 3210 // 0x0004 Connection refused – no resources available 3211 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004); 3212 return 1; 3213 } 3214 3215 channel->con_handle = handle; 3216 channel->remote_cid = source_cid; 3217 channel->remote_sig_id = sig_id; 3218 channel->remote_mtu = little_endian_read_16(command, 8); 3219 channel->remote_mps = little_endian_read_16(command, 10); 3220 channel->credits_outgoing = little_endian_read_16(command, 12); 3221 3222 // set initial state 3223 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 3224 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING; 3225 3226 // add to connections list 3227 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel); 3228 3229 // post connection request event 3230 l2cap_emit_le_incoming_connection(channel); 3231 3232 } else { 3233 // Connection refused – LE_PSM not supported 3234 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002); 3235 } 3236 break; 3237 3238 case LE_CREDIT_BASED_CONNECTION_RESPONSE: 3239 // check size 3240 if (len < 10u) return 0u; 3241 3242 // Find channel for this sig_id and connection handle 3243 channel = NULL; 3244 btstack_linked_list_iterator_init(&it, &l2cap_channels); 3245 while (btstack_linked_list_iterator_has_next(&it)){ 3246 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 3247 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue; 3248 if (a_channel->con_handle != handle) continue; 3249 if (a_channel->local_sig_id != sig_id) continue; 3250 channel = a_channel; 3251 break; 3252 } 3253 if (!channel) break; 3254 3255 // cid + 0 3256 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8); 3257 if (result){ 3258 channel->state = L2CAP_STATE_CLOSED; 3259 // map l2cap connection response result to BTstack status enumeration 3260 l2cap_emit_le_channel_opened(channel, result); 3261 3262 // discard channel 3263 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 3264 l2cap_free_channel_entry(channel); 3265 break; 3266 } 3267 3268 // success 3269 channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 3270 channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2); 3271 channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4); 3272 channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6); 3273 channel->state = L2CAP_STATE_OPEN; 3274 l2cap_emit_le_channel_opened(channel, result); 3275 break; 3276 3277 case LE_FLOW_CONTROL_CREDIT: 3278 // check size 3279 if (len < 4u) return 0u; 3280 3281 // find channel 3282 local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 3283 channel = l2cap_get_channel_for_local_cid(local_cid); 3284 if (!channel) { 3285 log_error("l2cap: no channel for cid 0x%02x", local_cid); 3286 break; 3287 } 3288 new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2); 3289 credits_before = channel->credits_outgoing; 3290 channel->credits_outgoing += new_credits; 3291 // check for credit overrun 3292 if (credits_before > channel->credits_outgoing){ 3293 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid); 3294 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 3295 break; 3296 } 3297 log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing); 3298 break; 3299 3300 case DISCONNECTION_REQUEST: 3301 3302 // check size 3303 if (len < 4u) return 0u; 3304 3305 // find channel 3306 local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 3307 channel = l2cap_get_channel_for_local_cid(local_cid); 3308 if (!channel) { 3309 log_error("l2cap: no channel for cid 0x%02x", local_cid); 3310 break; 3311 } 3312 channel->remote_sig_id = sig_id; 3313 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 3314 break; 3315 3316 #endif 3317 3318 case DISCONNECTION_RESPONSE: 3319 break; 3320 3321 default: 3322 // command unknown -> reject command 3323 return 0; 3324 } 3325 return 1; 3326 } 3327 #endif 3328 3329 #ifdef ENABLE_CLASSIC 3330 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){ 3331 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE 3332 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){ 3333 3334 int fcs_size = l2cap_channel->fcs_option ? 2 : 0; 3335 3336 // assert control + FCS fields are inside 3337 if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return; 3338 3339 if (l2cap_channel->fcs_option){ 3340 // verify FCS (required if one side requested it) 3341 uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2)); 3342 uint16_t fcs_packet = little_endian_read_16(packet, size-2); 3343 3344 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 3345 // simulate fcs error 3346 static int counter = 0; 3347 if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) { 3348 log_info("Simulate fcs error"); 3349 fcs_calculated++; 3350 counter = 0; 3351 } 3352 #endif 3353 3354 if (fcs_calculated == fcs_packet){ 3355 log_info("Packet FCS 0x%04x verified", fcs_packet); 3356 } else { 3357 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated); 3358 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS' 3359 return; 3360 } 3361 } 3362 3363 // switch on packet type 3364 uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER); 3365 uint8_t req_seq = (control >> 8) & 0x3f; 3366 int final = (control >> 7) & 0x01; 3367 if (control & 1){ 3368 // S-Frame 3369 int poll = (control >> 4) & 0x01; 3370 l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03); 3371 log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq); 3372 l2cap_ertm_tx_packet_state_t * tx_state; 3373 switch (s){ 3374 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY: 3375 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY"); 3376 l2cap_ertm_process_req_seq(l2cap_channel, req_seq); 3377 if (poll && final){ 3378 // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time. 3379 log_error("P=F=1 in S-Frame"); 3380 break; 3381 } 3382 if (poll){ 3383 // check if we did request selective retransmission before <==> we have stored SDU segments 3384 int i; 3385 int num_stored_out_of_order_packets = 0; 3386 for (i=0;i<l2cap_channel->num_rx_buffers;i++){ 3387 int index = l2cap_channel->rx_store_index + i; 3388 if (index >= l2cap_channel->num_rx_buffers){ 3389 index -= l2cap_channel->num_rx_buffers; 3390 } 3391 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index]; 3392 if (!rx_state->valid) continue; 3393 num_stored_out_of_order_packets++; 3394 } 3395 if (num_stored_out_of_order_packets){ 3396 l2cap_channel->send_supervisor_frame_selective_reject = 1; 3397 } else { 3398 l2cap_channel->send_supervisor_frame_receiver_ready = 1; 3399 } 3400 l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1; 3401 } 3402 if (final){ 3403 // Stop-MonitorTimer 3404 l2cap_ertm_stop_monitor_timer(l2cap_channel); 3405 // If UnackedFrames > 0 then Start-RetransTimer 3406 if (l2cap_channel->unacked_frames){ 3407 l2cap_ertm_start_retransmission_timer(l2cap_channel); 3408 } 3409 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted 3410 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel); 3411 } 3412 break; 3413 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT: 3414 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT"); 3415 l2cap_ertm_process_req_seq(l2cap_channel, req_seq); 3416 // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq) 3417 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel); 3418 break; 3419 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY: 3420 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY"); 3421 break; 3422 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT: 3423 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT"); 3424 if (poll){ 3425 l2cap_ertm_process_req_seq(l2cap_channel, req_seq); 3426 } 3427 // find requested i-frame 3428 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq); 3429 if (tx_state){ 3430 log_info("Retransmission for tx_seq %u requested", req_seq); 3431 l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll; 3432 tx_state->retransmission_requested = 1; 3433 l2cap_channel->srej_active = 1; 3434 } 3435 break; 3436 default: 3437 break; 3438 } 3439 } else { 3440 // I-Frame 3441 // get control 3442 l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14); 3443 uint8_t tx_seq = (control >> 1) & 0x3f; 3444 log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq); 3445 log_info("SAR: pos %u", l2cap_channel->reassembly_pos); 3446 log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq); 3447 l2cap_ertm_process_req_seq(l2cap_channel, req_seq); 3448 if (final){ 3449 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted 3450 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel); 3451 } 3452 3453 // get SDU 3454 const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2]; 3455 uint16_t payload_len = size-(COMPLETE_L2CAP_HEADER+2+fcs_size); 3456 3457 // assert SDU size is smaller or equal to our buffers 3458 uint16_t max_payload_size = 0; 3459 switch (sar){ 3460 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU: 3461 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU: 3462 // SDU Length + MPS 3463 max_payload_size = l2cap_channel->local_mps + 2; 3464 break; 3465 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU: 3466 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU: 3467 max_payload_size = l2cap_channel->local_mps; 3468 break; 3469 default: 3470 btstack_assert(false); 3471 break; 3472 } 3473 if (payload_len > max_payload_size){ 3474 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size); 3475 return; 3476 } 3477 3478 // check ordering 3479 if (l2cap_channel->expected_tx_seq == tx_seq){ 3480 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq); 3481 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq); 3482 l2cap_channel->req_seq = l2cap_channel->expected_tx_seq; 3483 3484 // process SDU 3485 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len); 3486 3487 // process stored segments 3488 while (true){ 3489 int index = l2cap_channel->rx_store_index; 3490 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index]; 3491 if (!rx_state->valid) break; 3492 3493 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq); 3494 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq); 3495 l2cap_channel->req_seq = l2cap_channel->expected_tx_seq; 3496 3497 rx_state->valid = 0; 3498 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len); 3499 3500 // update rx store index 3501 index++; 3502 if (index >= l2cap_channel->num_rx_buffers){ 3503 index = 0; 3504 } 3505 l2cap_channel->rx_store_index = index; 3506 } 3507 3508 // 3509 l2cap_channel->send_supervisor_frame_receiver_ready = 1; 3510 3511 } else { 3512 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f; 3513 if (delta < 2){ 3514 // store segment 3515 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len); 3516 3517 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq); 3518 l2cap_channel->send_supervisor_frame_selective_reject = 1; 3519 } else { 3520 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq); 3521 l2cap_channel->send_supervisor_frame_reject = 1; 3522 } 3523 } 3524 } 3525 return; 3526 } 3527 #endif 3528 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 3529 3530 } 3531 #endif 3532 3533 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){ 3534 #ifdef ENABLE_CLASSIC 3535 l2cap_channel_t * l2cap_channel; 3536 l2cap_fixed_channel_t * l2cap_fixed_channel; 3537 3538 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 3539 switch (channel_id) { 3540 3541 case L2CAP_CID_SIGNALING: { 3542 uint32_t command_offset = 8; 3543 while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) { 3544 // assert signaling command is fully inside packet 3545 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 3546 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len; 3547 if (next_command_offset > size){ 3548 log_error("l2cap signaling command len invalid -> drop"); 3549 break; 3550 } 3551 // handle signaling command 3552 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]); 3553 // go to next command 3554 command_offset = next_command_offset; 3555 } 3556 break; 3557 } 3558 case L2CAP_CID_CONNECTIONLESS_CHANNEL: 3559 l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL); 3560 if (!l2cap_fixed_channel) break; 3561 if (!l2cap_fixed_channel->packet_handler) break; 3562 (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 3563 break; 3564 3565 default: 3566 // Find channel for this channel_id and connection handle 3567 l2cap_channel = l2cap_get_channel_for_local_cid(channel_id); 3568 if (l2cap_channel) { 3569 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size); 3570 } 3571 break; 3572 } 3573 #else 3574 UNUSED(handle); // ok: no code 3575 UNUSED(packet); // ok: no code 3576 UNUSED(size); // ok: no code 3577 #endif 3578 } 3579 3580 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){ 3581 #ifdef ENABLE_BLE 3582 3583 l2cap_fixed_channel_t * l2cap_fixed_channel; 3584 3585 #ifdef ENABLE_LE_DATA_CHANNELS 3586 l2cap_channel_t * l2cap_channel; 3587 #endif 3588 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 3589 switch (channel_id) { 3590 3591 case L2CAP_CID_SIGNALING_LE: { 3592 uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1]; 3593 uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2); 3594 if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break; 3595 int valid = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id); 3596 if (!valid){ 3597 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN); 3598 } 3599 break; 3600 } 3601 3602 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 3603 l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL); 3604 if (!l2cap_fixed_channel) break; 3605 if (!l2cap_fixed_channel->packet_handler) break; 3606 (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 3607 break; 3608 3609 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 3610 l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL); 3611 if (!l2cap_fixed_channel) break; 3612 if (!l2cap_fixed_channel->packet_handler) break; 3613 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 3614 break; 3615 3616 default: 3617 3618 #ifdef ENABLE_LE_DATA_CHANNELS 3619 l2cap_channel = l2cap_get_channel_for_local_cid(channel_id); 3620 if (l2cap_channel) { 3621 // credit counting 3622 if (l2cap_channel->credits_incoming == 0u){ 3623 log_error("LE Data Channel packet received but no incoming credits"); 3624 l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 3625 break; 3626 } 3627 l2cap_channel->credits_incoming--; 3628 3629 // automatic credits 3630 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){ 3631 l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT; 3632 } 3633 3634 // first fragment 3635 uint16_t pos = 0; 3636 if (!l2cap_channel->receive_sdu_len){ 3637 uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER); 3638 if(sdu_len > l2cap_channel->local_mtu) break; // SDU would be larger than our buffer 3639 l2cap_channel->receive_sdu_len = sdu_len; 3640 l2cap_channel->receive_sdu_pos = 0; 3641 pos += 2u; 3642 size -= 2u; 3643 } 3644 uint16_t fragment_size = size-COMPLETE_L2CAP_HEADER; 3645 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos; 3646 if (fragment_size > remaining_space) break; // SDU would cause buffer overrun 3647 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], 3648 &packet[COMPLETE_L2CAP_HEADER + pos], 3649 fragment_size); 3650 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER; 3651 // done? 3652 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len); 3653 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){ 3654 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len); 3655 l2cap_channel->receive_sdu_len = 0; 3656 } 3657 } else { 3658 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id); 3659 } 3660 #endif 3661 break; 3662 } 3663 #else 3664 UNUSED(handle); // ok: no code 3665 UNUSED(packet); // ok: no code 3666 UNUSED(size); // ok: no code 3667 #endif 3668 } 3669 3670 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 3671 UNUSED(packet_type); // ok: registered with hci_register_acl_packet_handler 3672 UNUSED(channel); // ok: there is no channel 3673 3674 // Assert full L2CAP header present 3675 if (size < COMPLETE_L2CAP_HEADER) return; 3676 3677 // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP) 3678 hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet); 3679 hci_connection_t *conn = hci_connection_for_handle(handle); 3680 if (!conn) return; 3681 if (conn->address_type == BD_ADDR_TYPE_ACL){ 3682 l2cap_acl_classic_handler(handle, packet, size); 3683 } else { 3684 l2cap_acl_le_handler(handle, packet, size); 3685 } 3686 3687 l2cap_run(); 3688 } 3689 3690 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol 3691 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) { 3692 l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id); 3693 if (!channel) return; 3694 channel->packet_handler = the_packet_handler; 3695 } 3696 3697 #ifdef ENABLE_CLASSIC 3698 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 3699 void l2cap_finialize_channel_close(l2cap_channel_t * channel){ 3700 channel->state = L2CAP_STATE_CLOSED; 3701 l2cap_handle_channel_closed(channel); 3702 // discard channel 3703 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 3704 l2cap_free_channel_entry(channel); 3705 } 3706 #endif 3707 3708 #ifdef L2CAP_USES_CHANNELS 3709 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){ 3710 btstack_linked_list_iterator_t it; 3711 btstack_linked_list_iterator_init(&it, services); 3712 while (btstack_linked_list_iterator_has_next(&it)){ 3713 l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it); 3714 if ( service->psm == psm){ 3715 return service; 3716 }; 3717 } 3718 return NULL; 3719 } 3720 #endif 3721 3722 #ifdef ENABLE_CLASSIC 3723 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){ 3724 return l2cap_get_service_internal(&l2cap_services, psm); 3725 } 3726 3727 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){ 3728 3729 log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu); 3730 3731 // check for alread registered psm 3732 l2cap_service_t *service = l2cap_get_service(psm); 3733 if (service) { 3734 log_error("l2cap_register_service: PSM %u already registered", psm); 3735 return L2CAP_SERVICE_ALREADY_REGISTERED; 3736 } 3737 3738 // alloc structure 3739 service = btstack_memory_l2cap_service_get(); 3740 if (!service) { 3741 log_error("l2cap_register_service: no memory for l2cap_service_t"); 3742 return BTSTACK_MEMORY_ALLOC_FAILED; 3743 } 3744 3745 // fill in 3746 service->psm = psm; 3747 service->mtu = mtu; 3748 service->packet_handler = service_packet_handler; 3749 service->required_security_level = security_level; 3750 3751 // add to services list 3752 btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service); 3753 3754 // enable page scan 3755 gap_connectable_control(1); 3756 3757 return ERROR_CODE_SUCCESS; 3758 } 3759 3760 uint8_t l2cap_unregister_service(uint16_t psm){ 3761 3762 log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm); 3763 3764 l2cap_service_t *service = l2cap_get_service(psm); 3765 if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST; 3766 btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service); 3767 btstack_memory_l2cap_service_free(service); 3768 3769 // disable page scan when no services registered 3770 if (btstack_linked_list_empty(&l2cap_services)) { 3771 gap_connectable_control(0); 3772 } 3773 return ERROR_CODE_SUCCESS; 3774 } 3775 #endif 3776 3777 3778 #ifdef ENABLE_LE_DATA_CHANNELS 3779 3780 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){ 3781 if (!channel->waiting_for_can_send_now) return; 3782 if (channel->send_sdu_buffer) return; 3783 channel->waiting_for_can_send_now = 0; 3784 log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid); 3785 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW); 3786 } 3787 3788 // 1BH2222 3789 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) { 3790 log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u", 3791 channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu); 3792 uint8_t event[19]; 3793 event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION; 3794 event[1] = sizeof(event) - 2u; 3795 event[2] = channel->address_type; 3796 reverse_bd_addr(channel->address, &event[3]); 3797 little_endian_store_16(event, 9, channel->con_handle); 3798 little_endian_store_16(event, 11, channel->psm); 3799 little_endian_store_16(event, 13, channel->local_cid); 3800 little_endian_store_16(event, 15, channel->remote_cid); 3801 little_endian_store_16(event, 17, channel->remote_mtu); 3802 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 3803 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 3804 } 3805 // 11BH22222 3806 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) { 3807 log_info("L2CAP_EVENT_LE_CHANNEL_OPENED status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u", 3808 status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, 3809 channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu); 3810 uint8_t event[23]; 3811 event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED; 3812 event[1] = sizeof(event) - 2u; 3813 event[2] = status; 3814 event[3] = channel->address_type; 3815 reverse_bd_addr(channel->address, &event[4]); 3816 little_endian_store_16(event, 10, channel->con_handle); 3817 event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0; 3818 little_endian_store_16(event, 13, channel->psm); 3819 little_endian_store_16(event, 15, channel->local_cid); 3820 little_endian_store_16(event, 17, channel->remote_cid); 3821 little_endian_store_16(event, 19, channel->local_mtu); 3822 little_endian_store_16(event, 21, channel->remote_mtu); 3823 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 3824 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 3825 } 3826 // 2 3827 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){ 3828 log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid); 3829 uint8_t event[4]; 3830 event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED; 3831 event[1] = sizeof(event) - 2u; 3832 little_endian_store_16(event, 2, channel->local_cid); 3833 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 3834 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 3835 } 3836 3837 static void l2cap_le_send_pdu(l2cap_channel_t *channel){ 3838 btstack_assert(channel != NULL); 3839 btstack_assert(channel->send_sdu_buffer != NULL); 3840 btstack_assert(channel->credits_outgoing > 0); 3841 3842 // send part of SDU 3843 hci_reserve_packet_buffer(); 3844 uint8_t * acl_buffer = hci_get_outgoing_packet_buffer(); 3845 uint8_t * l2cap_payload = acl_buffer + 8; 3846 uint16_t pos = 0; 3847 if (!channel->send_sdu_pos){ 3848 // store SDU len 3849 channel->send_sdu_pos += 2u; 3850 little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len); 3851 pos += 2u; 3852 } 3853 uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos); 3854 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing); 3855 (void)memcpy(&l2cap_payload[pos], 3856 &channel->send_sdu_buffer[channel->send_sdu_pos - 2u], 3857 payload_size); // -2 for virtual SDU len 3858 pos += payload_size; 3859 channel->send_sdu_pos += payload_size; 3860 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos); 3861 3862 channel->credits_outgoing--; 3863 3864 hci_send_acl_packet_buffer(8u + pos); 3865 3866 if (channel->send_sdu_pos >= (channel->send_sdu_len + 2u)){ 3867 channel->send_sdu_buffer = NULL; 3868 // send done event 3869 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT); 3870 // inform about can send now 3871 l2cap_le_notify_channel_can_send(channel); 3872 } 3873 } 3874 3875 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 3876 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){ 3877 channel->state = L2CAP_STATE_CLOSED; 3878 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED); 3879 // discard channel 3880 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 3881 l2cap_free_channel_entry(channel); 3882 } 3883 3884 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){ 3885 return l2cap_get_service_internal(&l2cap_le_services, le_psm); 3886 } 3887 3888 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){ 3889 3890 log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm); 3891 3892 // check for alread registered psm 3893 l2cap_service_t *service = l2cap_le_get_service(psm); 3894 if (service) { 3895 return L2CAP_SERVICE_ALREADY_REGISTERED; 3896 } 3897 3898 // alloc structure 3899 service = btstack_memory_l2cap_service_get(); 3900 if (!service) { 3901 log_error("l2cap_register_service_internal: no memory for l2cap_service_t"); 3902 return BTSTACK_MEMORY_ALLOC_FAILED; 3903 } 3904 3905 // fill in 3906 service->psm = psm; 3907 service->mtu = 0; 3908 service->packet_handler = packet_handler; 3909 service->required_security_level = security_level; 3910 3911 // add to services list 3912 btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service); 3913 3914 // done 3915 return ERROR_CODE_SUCCESS; 3916 } 3917 3918 uint8_t l2cap_le_unregister_service(uint16_t psm) { 3919 log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm); 3920 l2cap_service_t *service = l2cap_le_get_service(psm); 3921 if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST; 3922 3923 btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service); 3924 btstack_memory_l2cap_service_free(service); 3925 return ERROR_CODE_SUCCESS; 3926 } 3927 3928 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){ 3929 // get channel 3930 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 3931 if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 3932 3933 // validate state 3934 if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){ 3935 return ERROR_CODE_COMMAND_DISALLOWED; 3936 } 3937 3938 // set state accept connection 3939 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT; 3940 channel->receive_sdu_buffer = receive_sdu_buffer; 3941 channel->local_mtu = mtu; 3942 channel->new_credits_incoming = initial_credits; 3943 channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS; 3944 3945 // test 3946 // channel->new_credits_incoming = 1; 3947 3948 // go 3949 l2cap_run(); 3950 return ERROR_CODE_SUCCESS; 3951 } 3952 3953 /** 3954 * @brief Deny incoming LE Data Channel connection due to resource constraints 3955 * @param local_cid L2CAP LE Data Channel Identifier 3956 */ 3957 3958 uint8_t l2cap_le_decline_connection(uint16_t local_cid){ 3959 // get channel 3960 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 3961 if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 3962 3963 // validate state 3964 if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){ 3965 return ERROR_CODE_COMMAND_DISALLOWED; 3966 } 3967 3968 // set state decline connection 3969 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE; 3970 channel->reason = 0x04; // no resources available 3971 l2cap_run(); 3972 return ERROR_CODE_SUCCESS; 3973 } 3974 3975 static gap_security_level_t l2cap_le_security_level_for_connection(hci_con_handle_t con_handle){ 3976 uint8_t encryption_key_size = gap_encryption_key_size(con_handle); 3977 if (encryption_key_size == 0) return LEVEL_0; 3978 3979 uint8_t authenticated = gap_authenticated(con_handle); 3980 if (!authenticated) return LEVEL_2; 3981 3982 return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3; 3983 } 3984 3985 // used to handle pairing complete after triggering to increase 3986 static void l2cap_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) { 3987 UNUSED(channel_nr); 3988 UNUSED(size); 3989 UNUSED(packet_type); 3990 btstack_assert(packet_type = HCI_EVENT_PACKET); 3991 if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return; 3992 hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet); 3993 btstack_linked_list_iterator_t it; 3994 btstack_linked_list_iterator_init(&it, &l2cap_channels); 3995 while (btstack_linked_list_iterator_has_next(&it)) { 3996 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 3997 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue; 3998 if (channel->con_handle != con_handle) continue; 3999 if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue; 4000 4001 // found channel, check security level 4002 if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){ 4003 // pairing failed or wasn't good enough, inform user 4004 l2cap_emit_le_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY); 4005 // discard channel 4006 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 4007 l2cap_free_channel_entry(channel); 4008 } else { 4009 // send conn request now 4010 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST; 4011 l2cap_run(); 4012 } 4013 } 4014 } 4015 4016 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle, 4017 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level, 4018 uint16_t * out_local_cid) { 4019 4020 static btstack_packet_callback_registration_t sm_event_callback_registration; 4021 static bool sm_callback_registered = false; 4022 4023 log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu); 4024 4025 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4026 if (!connection) { 4027 log_error("no hci_connection for handle 0x%04x", con_handle); 4028 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 4029 } 4030 4031 l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, connection->address_type, psm, mtu, security_level); 4032 if (!channel) { 4033 return BTSTACK_MEMORY_ALLOC_FAILED; 4034 } 4035 log_info("l2cap_le_create_channel %p", channel); 4036 4037 // store local_cid 4038 if (out_local_cid){ 4039 *out_local_cid = channel->local_cid; 4040 } 4041 4042 // setup channel entry 4043 channel->con_handle = con_handle; 4044 channel->receive_sdu_buffer = receive_sdu_buffer; 4045 channel->new_credits_incoming = initial_credits; 4046 channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS; 4047 4048 // add to connections list 4049 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel); 4050 4051 // check security level 4052 if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){ 4053 if (!sm_callback_registered){ 4054 sm_callback_registered = true; 4055 // lazy registration for SM events 4056 sm_event_callback_registration.callback = &l2cap_sm_packet_handler; 4057 sm_add_event_handler(&sm_event_callback_registration); 4058 } 4059 4060 // start pairing 4061 channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE; 4062 sm_request_pairing(con_handle); 4063 } else { 4064 // send conn request right away 4065 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST; 4066 l2cap_run(); 4067 } 4068 4069 return ERROR_CODE_SUCCESS; 4070 } 4071 4072 /** 4073 * @brief Provide credtis for LE Data Channel 4074 * @param local_cid L2CAP LE Data Channel Identifier 4075 * @param credits Number additional credits for peer 4076 */ 4077 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){ 4078 4079 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 4080 if (!channel) { 4081 log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid); 4082 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 4083 } 4084 4085 // check state 4086 if (channel->state != L2CAP_STATE_OPEN){ 4087 log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid); 4088 } 4089 4090 // assert incoming credits + credits <= 0xffff 4091 uint32_t total_credits = channel->credits_incoming; 4092 total_credits += channel->new_credits_incoming; 4093 total_credits += credits; 4094 if (total_credits > 0xffffu){ 4095 log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming, 4096 channel->new_credits_incoming, credits); 4097 } 4098 4099 // set credits_granted 4100 channel->new_credits_incoming += credits; 4101 4102 // go 4103 l2cap_run(); 4104 return ERROR_CODE_SUCCESS; 4105 } 4106 4107 /** 4108 * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module 4109 * @param local_cid L2CAP LE Data Channel Identifier 4110 */ 4111 int l2cap_le_can_send_now(uint16_t local_cid){ 4112 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 4113 if (!channel) { 4114 log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid); 4115 return 0; 4116 } 4117 4118 // check state 4119 if (channel->state != L2CAP_STATE_OPEN) return 0; 4120 4121 // check queue 4122 if (channel->send_sdu_buffer) return 0; 4123 4124 // fine, go ahead 4125 return 1; 4126 } 4127 4128 /** 4129 * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible 4130 * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function 4131 * so packet handler should be ready to handle it 4132 * @param local_cid L2CAP LE Data Channel Identifier 4133 */ 4134 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){ 4135 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 4136 if (!channel) { 4137 log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid); 4138 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 4139 } 4140 channel->waiting_for_can_send_now = 1; 4141 l2cap_le_notify_channel_can_send(channel); 4142 return ERROR_CODE_SUCCESS; 4143 } 4144 4145 /** 4146 * @brief Send data via LE Data Channel 4147 * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event 4148 * @param local_cid L2CAP LE Data Channel Identifier 4149 * @param data data to send 4150 * @param size data size 4151 */ 4152 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){ 4153 4154 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 4155 if (!channel) { 4156 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 4157 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 4158 } 4159 4160 if (len > channel->remote_mtu){ 4161 log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid); 4162 return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU; 4163 } 4164 4165 if (channel->send_sdu_buffer){ 4166 log_info("l2cap_send cid 0x%02x, cannot send", local_cid); 4167 return BTSTACK_ACL_BUFFERS_FULL; 4168 } 4169 4170 channel->send_sdu_buffer = data; 4171 channel->send_sdu_len = len; 4172 channel->send_sdu_pos = 0; 4173 4174 l2cap_notify_channel_can_send(); 4175 return ERROR_CODE_SUCCESS; 4176 } 4177 4178 /** 4179 * @brief Disconnect from LE Data Channel 4180 * @param local_cid L2CAP LE Data Channel Identifier 4181 */ 4182 uint8_t l2cap_le_disconnect(uint16_t local_cid) 4183 { 4184 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 4185 if (!channel) { 4186 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 4187 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 4188 } 4189 4190 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 4191 l2cap_run(); 4192 return ERROR_CODE_SUCCESS; 4193 } 4194 4195 #endif 4196