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 /* 39 * l2cap.c 40 * 41 * Logical Link Control and Adaption Protocl (L2CAP) 42 * 43 * Created by Matthias Ringwald on 5/16/09. 44 */ 45 46 #include "l2cap.h" 47 #include "hci.h" 48 #include "hci_dump.h" 49 #include "btstack_debug.h" 50 #include "btstack_event.h" 51 #include "btstack_memory.h" 52 53 #ifdef ENABLE_LE_DATA_CHANNELS 54 #include "ble/sm.h" 55 #endif 56 57 #include <stdarg.h> 58 #include <string.h> 59 60 #include <stdio.h> 61 62 // nr of buffered acl packets in outgoing queue to get max performance 63 #define NR_BUFFERED_ACL_PACKETS 3 64 65 // used to cache l2cap rejects, echo, and informational requests 66 #define NR_PENDING_SIGNALING_RESPONSES 3 67 68 // nr of credits provided to remote if credits fall below watermark 69 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5 70 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5 71 72 // offsets for L2CAP SIGNALING COMMANDS 73 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET 0 74 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET 1 75 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2 76 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET 4 77 78 // internal table 79 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0 80 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL 1 81 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2 82 #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1) 83 84 // prototypes 85 static void l2cap_finialize_channel_close(l2cap_channel_t *channel); 86 static inline l2cap_service_t * l2cap_get_service(uint16_t psm); 87 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status); 88 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel); 89 static void l2cap_emit_channel_closed(l2cap_channel_t *channel); 90 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel); 91 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel); 92 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 93 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ); 94 static void l2cap_notify_channel_can_send(void); 95 #ifdef ENABLE_LE_DATA_CHANNELS 96 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel); 97 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel); 98 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm); 99 #endif 100 101 typedef struct l2cap_fixed_channel { 102 btstack_packet_handler_t callback; 103 uint8_t waiting_for_can_send_now; 104 } l2cap_fixed_channel_t; 105 106 static btstack_linked_list_t l2cap_channels; 107 static btstack_linked_list_t l2cap_services; 108 static btstack_linked_list_t l2cap_le_channels; 109 static btstack_linked_list_t l2cap_le_services; 110 111 // used to cache l2cap rejects, echo, and informational requests 112 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES]; 113 static int signaling_responses_pending; 114 115 static uint8_t require_security_level2_for_outgoing_sdp; 116 117 static btstack_packet_callback_registration_t hci_event_callback_registration; 118 119 static btstack_packet_handler_t l2cap_event_packet_handler; 120 static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE]; 121 122 static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){ 123 switch (index){ 124 case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL: 125 return L2CAP_CID_ATTRIBUTE_PROTOCOL; 126 case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL: 127 return L2CAP_CID_SECURITY_MANAGER_PROTOCOL; 128 case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL: 129 return L2CAP_CID_CONNECTIONLESS_CHANNEL; 130 default: 131 return 0; 132 } 133 } 134 static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){ 135 switch (channel_id){ 136 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 137 return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL; 138 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 139 return L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL; 140 case L2CAP_CID_CONNECTIONLESS_CHANNEL: 141 return L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL; 142 default: 143 return -1; 144 } 145 } 146 147 static int l2cap_fixed_channel_table_index_is_le(int index){ 148 if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0; 149 return 1; 150 } 151 152 void l2cap_init(void){ 153 signaling_responses_pending = 0; 154 155 l2cap_channels = NULL; 156 l2cap_services = NULL; 157 l2cap_le_services = NULL; 158 l2cap_le_channels = NULL; 159 160 l2cap_event_packet_handler = NULL; 161 memset(fixed_channels, 0, sizeof(fixed_channels)); 162 163 require_security_level2_for_outgoing_sdp = 0; 164 165 // 166 // register callback with HCI 167 // 168 hci_event_callback_registration.callback = &l2cap_hci_event_handler; 169 hci_add_event_handler(&hci_event_callback_registration); 170 171 hci_register_acl_packet_handler(&l2cap_acl_handler); 172 173 gap_connectable_control(0); // no services yet 174 } 175 176 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){ 177 l2cap_event_packet_handler = handler; 178 } 179 180 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){ 181 (* (channel->packet_handler))(type, channel->local_cid, data, size); 182 } 183 184 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){ 185 uint8_t event[4]; 186 event[0] = event_code; 187 event[1] = sizeof(event) - 2; 188 little_endian_store_16(event, 2, channel->local_cid); 189 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 190 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 191 } 192 193 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) { 194 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", 195 status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, 196 channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout); 197 uint8_t event[23]; 198 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 199 event[1] = sizeof(event) - 2; 200 event[2] = status; 201 reverse_bd_addr(channel->address, &event[3]); 202 little_endian_store_16(event, 9, channel->con_handle); 203 little_endian_store_16(event, 11, channel->psm); 204 little_endian_store_16(event, 13, channel->local_cid); 205 little_endian_store_16(event, 15, channel->remote_cid); 206 little_endian_store_16(event, 17, channel->local_mtu); 207 little_endian_store_16(event, 19, channel->remote_mtu); 208 little_endian_store_16(event, 21, channel->flush_timeout); 209 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 210 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 211 } 212 213 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) { 214 log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid); 215 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED); 216 } 217 218 219 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) { 220 log_info("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel); 221 uint8_t event[4]; 222 event[0] = L2CAP_EVENT_CAN_SEND_NOW; 223 event[1] = sizeof(event) - 2; 224 little_endian_store_16(event, 2, channel); 225 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 226 packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event)); 227 } 228 229 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) { 230 log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x", 231 bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid); 232 uint8_t event[16]; 233 event[0] = L2CAP_EVENT_INCOMING_CONNECTION; 234 event[1] = sizeof(event) - 2; 235 reverse_bd_addr(channel->address, &event[2]); 236 little_endian_store_16(event, 8, channel->con_handle); 237 little_endian_store_16(event, 10, channel->psm); 238 little_endian_store_16(event, 12, channel->local_cid); 239 little_endian_store_16(event, 14, channel->remote_cid); 240 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 241 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 242 } 243 244 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){ 245 uint8_t event[6]; 246 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE; 247 event[1] = 4; 248 little_endian_store_16(event, 2, con_handle); 249 little_endian_store_16(event, 4, result); 250 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 251 if (!l2cap_event_packet_handler) return; 252 (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event)); 253 } 254 255 #ifdef ENABLE_LE_DATA_CHANNELS 256 // 1BH2222 257 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) { 258 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", 259 channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu); 260 uint8_t event[19]; 261 event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION; 262 event[1] = sizeof(event) - 2; 263 event[2] = channel->address_type; 264 reverse_bd_addr(channel->address, &event[3]); 265 little_endian_store_16(event, 9, channel->con_handle); 266 little_endian_store_16(event, 11, channel->psm); 267 little_endian_store_16(event, 13, channel->local_cid); 268 little_endian_store_16(event, 15, channel->remote_cid); 269 little_endian_store_16(event, 17, channel->remote_mtu); 270 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 271 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 272 } 273 // 11BH22222 274 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) { 275 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", 276 status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, 277 channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu); 278 uint8_t event[22]; 279 event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED; 280 event[1] = sizeof(event) - 2; 281 event[2] = status; 282 event[3] = channel->address_type; 283 reverse_bd_addr(channel->address, &event[4]); 284 little_endian_store_16(event, 10, channel->con_handle); 285 little_endian_store_16(event, 12, channel->psm); 286 little_endian_store_16(event, 14, channel->local_cid); 287 little_endian_store_16(event, 16, channel->remote_cid); 288 little_endian_store_16(event, 18, channel->local_mtu); 289 little_endian_store_16(event, 20, channel->remote_mtu); 290 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 291 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 292 } 293 #endif 294 295 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){ 296 btstack_linked_list_iterator_t it; 297 btstack_linked_list_iterator_init(&it, &l2cap_channels); 298 while (btstack_linked_list_iterator_has_next(&it)){ 299 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 300 if ( channel->local_cid == local_cid) { 301 return channel; 302 } 303 } 304 return NULL; 305 } 306 307 #ifdef ENABLE_BLE 308 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){ 309 btstack_linked_list_iterator_t it; 310 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 311 while (btstack_linked_list_iterator_has_next(&it)){ 312 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 313 if ( channel->local_cid == local_cid) { 314 return channel; 315 } 316 } 317 return NULL; 318 } 319 #endif 320 321 /// 322 323 void l2cap_request_can_send_now_event(uint16_t local_cid){ 324 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 325 if (!channel) return; 326 channel->waiting_for_can_send_now = 1; 327 l2cap_notify_channel_can_send(); 328 } 329 330 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){ 331 int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id); 332 if (index < 0) return; 333 fixed_channels[index].waiting_for_can_send_now = 1; 334 l2cap_notify_channel_can_send(); 335 } 336 337 /// 338 339 int l2cap_can_send_packet_now(uint16_t local_cid){ 340 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 341 if (!channel) return 0; 342 return hci_can_send_acl_packet_now(channel->con_handle); 343 } 344 345 int l2cap_can_send_prepared_packet_now(uint16_t local_cid){ 346 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 347 if (!channel) return 0; 348 return hci_can_send_prepared_acl_packet_now(channel->con_handle); 349 } 350 351 int l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){ 352 return hci_can_send_acl_packet_now(con_handle); 353 } 354 355 /// 356 357 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){ 358 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 359 if (channel) { 360 return channel->remote_mtu; 361 } 362 return 0; 363 } 364 365 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){ 366 btstack_linked_list_iterator_t it; 367 btstack_linked_list_iterator_init(&it, &l2cap_channels); 368 while (btstack_linked_list_iterator_has_next(&it)){ 369 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 370 if ( &channel->rtx == ts) { 371 return channel; 372 } 373 } 374 return NULL; 375 } 376 377 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){ 378 l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts); 379 if (!channel) return; 380 381 log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid); 382 383 // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq 384 // and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state." 385 // notify client 386 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT); 387 388 // discard channel 389 // no need to stop timer here, it is removed from list during timer callback 390 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 391 btstack_memory_l2cap_channel_free(channel); 392 } 393 394 static void l2cap_stop_rtx(l2cap_channel_t * channel){ 395 log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid); 396 btstack_run_loop_remove_timer(&channel->rtx); 397 } 398 399 static void l2cap_start_rtx(l2cap_channel_t * channel){ 400 l2cap_stop_rtx(channel); 401 log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid); 402 btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout); 403 btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS); 404 btstack_run_loop_add_timer(&channel->rtx); 405 } 406 407 static void l2cap_start_ertx(l2cap_channel_t * channel){ 408 log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid); 409 l2cap_stop_rtx(channel); 410 btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout); 411 btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS); 412 btstack_run_loop_add_timer(&channel->rtx); 413 } 414 415 void l2cap_require_security_level_2_for_outgoing_sdp(void){ 416 require_security_level2_for_outgoing_sdp = 1; 417 } 418 419 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){ 420 return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp); 421 } 422 423 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){ 424 425 if (!hci_can_send_acl_packet_now(handle)){ 426 log_info("l2cap_send_signaling_packet, cannot send"); 427 return BTSTACK_ACL_BUFFERS_FULL; 428 } 429 430 // log_info("l2cap_send_signaling_packet type %u", cmd); 431 hci_reserve_packet_buffer(); 432 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 433 va_list argptr; 434 va_start(argptr, identifier); 435 uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr); 436 va_end(argptr); 437 // log_info("l2cap_send_signaling_packet con %u!", handle); 438 return hci_send_acl_packet_buffer(len); 439 } 440 441 #ifdef ENABLE_BLE 442 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){ 443 444 if (!hci_can_send_acl_packet_now(handle)){ 445 log_info("l2cap_send_signaling_packet, cannot send"); 446 return BTSTACK_ACL_BUFFERS_FULL; 447 } 448 449 // log_info("l2cap_send_signaling_packet type %u", cmd); 450 hci_reserve_packet_buffer(); 451 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 452 va_list argptr; 453 va_start(argptr, identifier); 454 uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr); 455 va_end(argptr); 456 // log_info("l2cap_send_signaling_packet con %u!", handle); 457 return hci_send_acl_packet_buffer(len); 458 } 459 #endif 460 461 uint8_t *l2cap_get_outgoing_buffer(void){ 462 return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes 463 } 464 465 int l2cap_reserve_packet_buffer(void){ 466 return hci_reserve_packet_buffer(); 467 } 468 469 void l2cap_release_packet_buffer(void){ 470 hci_release_packet_buffer(); 471 } 472 473 static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint16_t remote_cid, uint16_t len){ 474 475 int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02; 476 477 // 0 - Connection handle : PB=pb : BC=00 478 little_endian_store_16(acl_buffer, 0, con_handle | (pb << 12) | (0 << 14)); 479 // 2 - ACL length 480 little_endian_store_16(acl_buffer, 2, len + 4); 481 // 4 - L2CAP packet length 482 little_endian_store_16(acl_buffer, 4, len + 0); 483 // 6 - L2CAP channel DEST 484 little_endian_store_16(acl_buffer, 6, remote_cid); 485 } 486 487 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){ 488 489 if (!hci_is_packet_buffer_reserved()){ 490 log_error("l2cap_send_prepared called without reserving packet first"); 491 return BTSTACK_ACL_BUFFERS_FULL; 492 } 493 494 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 495 if (!channel) { 496 log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid); 497 return -1; // TODO: define error 498 } 499 500 if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){ 501 log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid); 502 return BTSTACK_ACL_BUFFERS_FULL; 503 } 504 505 log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle); 506 507 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 508 l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, len); 509 // send 510 return hci_send_acl_packet_buffer(len+8); 511 } 512 513 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){ 514 515 if (!hci_is_packet_buffer_reserved()){ 516 log_error("l2cap_send_prepared_connectionless called without reserving packet first"); 517 return BTSTACK_ACL_BUFFERS_FULL; 518 } 519 520 if (!hci_can_send_prepared_acl_packet_now(con_handle)){ 521 log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid); 522 return BTSTACK_ACL_BUFFERS_FULL; 523 } 524 525 log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid); 526 527 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 528 l2cap_setup_header(acl_buffer, con_handle, cid, len); 529 // send 530 return hci_send_acl_packet_buffer(len+8); 531 } 532 533 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){ 534 535 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 536 if (!channel) { 537 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 538 return -1; // TODO: define error 539 } 540 541 if (len > channel->remote_mtu){ 542 log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid); 543 return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU; 544 } 545 546 if (!hci_can_send_acl_packet_now(channel->con_handle)){ 547 log_info("l2cap_send cid 0x%02x, cannot send", local_cid); 548 return BTSTACK_ACL_BUFFERS_FULL; 549 } 550 551 hci_reserve_packet_buffer(); 552 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 553 554 memcpy(&acl_buffer[8], data, len); 555 556 return l2cap_send_prepared(local_cid, len); 557 } 558 559 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){ 560 561 if (!hci_can_send_acl_packet_now(con_handle)){ 562 log_info("l2cap_send cid 0x%02x, cannot send", cid); 563 return BTSTACK_ACL_BUFFERS_FULL; 564 } 565 566 hci_reserve_packet_buffer(); 567 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 568 569 memcpy(&acl_buffer[8], data, len); 570 571 return l2cap_send_prepared_connectionless(con_handle, cid, len); 572 } 573 574 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){ 575 return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data); 576 } 577 578 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 579 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag); 580 } 581 582 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 583 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag); 584 } 585 586 587 588 // MARK: L2CAP_RUN 589 // process outstanding signaling tasks 590 static void l2cap_run(void){ 591 592 // log_info("l2cap_run: entered"); 593 594 // check pending signaling responses 595 while (signaling_responses_pending){ 596 597 hci_con_handle_t handle = signaling_responses[0].handle; 598 599 if (!hci_can_send_acl_packet_now(handle)) break; 600 601 uint8_t sig_id = signaling_responses[0].sig_id; 602 uint16_t infoType = signaling_responses[0].data; // INFORMATION_REQUEST 603 uint16_t result = signaling_responses[0].data; // CONNECTION_REQUEST, COMMAND_REJECT 604 uint8_t response_code = signaling_responses[0].code; 605 606 // remove first item before sending (to avoid sending response mutliple times) 607 signaling_responses_pending--; 608 int i; 609 for (i=0; i < signaling_responses_pending; i++){ 610 memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t)); 611 } 612 613 switch (response_code){ 614 case CONNECTION_REQUEST: 615 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0); 616 // also disconnect if result is 0x0003 - security blocked 617 if (result == 0x0003){ 618 hci_disconnect_security_block(handle); 619 } 620 break; 621 case ECHO_REQUEST: 622 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL); 623 break; 624 case INFORMATION_REQUEST: 625 switch (infoType){ 626 case 1: { // Connectionless MTU 627 uint16_t connectionless_mtu = hci_max_acl_data_packet_length(); 628 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu); 629 break; 630 } 631 case 2: { // Extended Features Supported 632 // extended features request supported, features: fixed channels, unicast connectionless data reception 633 uint32_t features = 0x280; 634 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features); 635 break; 636 } 637 case 3: { // Fixed Channels Supported 638 uint8_t map[8]; 639 memset(map, 0, 8); 640 map[0] = 0x06; // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04) 641 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map); 642 break; 643 } 644 default: 645 // all other types are not supported 646 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL); 647 break; 648 } 649 break; 650 case COMMAND_REJECT: 651 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL); 652 break; 653 #ifdef ENABLE_BLE 654 case LE_CREDIT_BASED_CONNECTION_REQUEST: 655 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result); 656 break; 657 case COMMAND_REJECT_LE: 658 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL); 659 break; 660 #endif 661 default: 662 // should not happen 663 break; 664 } 665 } 666 667 uint8_t config_options[4]; 668 btstack_linked_list_iterator_t it; 669 btstack_linked_list_iterator_init(&it, &l2cap_channels); 670 while (btstack_linked_list_iterator_has_next(&it)){ 671 672 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 673 // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var); 674 switch (channel->state){ 675 676 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 677 case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT: 678 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 679 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) { 680 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND); 681 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0); 682 } 683 break; 684 685 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 686 if (!hci_can_send_command_packet_now()) break; 687 // send connection request - set state first 688 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE; 689 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch 690 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 691 break; 692 693 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE: 694 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 695 channel->state = L2CAP_STATE_INVALID; 696 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0); 697 // discard channel - l2cap_finialize_channel_close without sending l2cap close event 698 l2cap_stop_rtx(channel); 699 btstack_linked_list_iterator_remove(&it); 700 btstack_memory_l2cap_channel_free(channel); 701 break; 702 703 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT: 704 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 705 channel->state = L2CAP_STATE_CONFIG; 706 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 707 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0); 708 break; 709 710 case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST: 711 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 712 // success, start l2cap handshake 713 channel->local_sig_id = l2cap_next_sig_id(); 714 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP; 715 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid); 716 l2cap_start_rtx(channel); 717 break; 718 719 case L2CAP_STATE_CONFIG: 720 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 721 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){ 722 uint16_t flags = 0; 723 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 724 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) { 725 flags = 1; 726 } else { 727 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP); 728 } 729 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){ 730 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL); 731 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){ 732 config_options[0] = 1; // MTU 733 config_options[1] = 2; // len param 734 little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu); 735 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options); 736 channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 737 } else { 738 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL); 739 } 740 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 741 } 742 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){ 743 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 744 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ); 745 channel->local_sig_id = l2cap_next_sig_id(); 746 config_options[0] = 1; // MTU 747 config_options[1] = 2; // len param 748 little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu); 749 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options); 750 l2cap_start_rtx(channel); 751 } 752 if (l2cap_channel_ready_for_open(channel)){ 753 channel->state = L2CAP_STATE_OPEN; 754 l2cap_emit_channel_opened(channel, 0); // success 755 } 756 break; 757 758 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 759 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 760 channel->state = L2CAP_STATE_INVALID; 761 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid); 762 // 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 :) 763 l2cap_finialize_channel_close(channel); // -- remove from list 764 break; 765 766 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 767 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 768 channel->local_sig_id = l2cap_next_sig_id(); 769 channel->state = L2CAP_STATE_WAIT_DISCONNECT; 770 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid); 771 break; 772 default: 773 break; 774 } 775 } 776 777 #ifdef ENABLE_BLE 778 #ifdef ENABLE_LE_DATA_CHANNELS 779 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 780 while (btstack_linked_list_iterator_has_next(&it)){ 781 uint8_t * acl_buffer; 782 uint8_t * l2cap_payload; 783 uint16_t pos; 784 uint16_t payload_size; 785 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 786 // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var); 787 switch (channel->state){ 788 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST: 789 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 790 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE; 791 // le psm, source cid, mtu, mps, initial credits 792 channel->local_sig_id = l2cap_next_sig_id(); 793 channel->credits_incoming = channel->new_credits_incoming; 794 channel->new_credits_incoming = 0; 795 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, 23, channel->credits_incoming); 796 break; 797 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT: 798 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 799 // TODO: support larger MPS 800 channel->state = L2CAP_STATE_OPEN; 801 channel->credits_incoming = channel->new_credits_incoming; 802 channel->new_credits_incoming = 0; 803 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming, 0); 804 // notify client 805 l2cap_emit_le_channel_opened(channel, 0); 806 break; 807 case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE: 808 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 809 channel->state = L2CAP_STATE_INVALID; 810 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason); 811 // discard channel - l2cap_finialize_channel_close without sending l2cap close event 812 l2cap_stop_rtx(channel); 813 btstack_linked_list_iterator_remove(&it); 814 btstack_memory_l2cap_channel_free(channel); 815 break; 816 case L2CAP_STATE_OPEN: 817 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 818 819 // send credits 820 if (channel->new_credits_incoming){ 821 log_info("l2cap: sending %u credits", channel->new_credits_incoming); 822 channel->local_sig_id = l2cap_next_sig_id(); 823 uint16_t new_credits = channel->new_credits_incoming; 824 channel->new_credits_incoming = 0; 825 channel->credits_incoming += new_credits; 826 l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits); 827 break; 828 } 829 830 // send data 831 if (!channel->send_sdu_buffer) break; 832 if (!channel->credits_outgoing) break; 833 834 // send part of SDU 835 hci_reserve_packet_buffer(); 836 acl_buffer = hci_get_outgoing_packet_buffer(); 837 l2cap_payload = acl_buffer + 8; 838 pos = 0; 839 if (!channel->send_sdu_pos){ 840 // store SDU len 841 channel->send_sdu_pos += 2; 842 little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len); 843 pos += 2; 844 } 845 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos); 846 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing); 847 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len 848 pos += payload_size; 849 channel->send_sdu_pos += payload_size; 850 l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, pos); 851 // done 852 853 channel->credits_outgoing--; 854 855 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){ 856 channel->send_sdu_buffer = NULL; 857 // send done event 858 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT); 859 // inform about can send now 860 l2cap_le_notify_channel_can_send(channel); 861 } 862 hci_send_acl_packet_buffer(8 + pos); 863 break; 864 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 865 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 866 channel->local_sig_id = l2cap_next_sig_id(); 867 channel->state = L2CAP_STATE_WAIT_DISCONNECT; 868 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid); 869 break; 870 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 871 if (!hci_can_send_acl_packet_now(channel->con_handle)) break; 872 channel->state = L2CAP_STATE_INVALID; 873 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid); 874 l2cap_le_finialize_channel_close(channel); // -- remove from list 875 break; 876 default: 877 break; 878 } 879 } 880 881 // send l2cap con paramter update if necessary 882 hci_connections_get_iterator(&it); 883 while(btstack_linked_list_iterator_has_next(&it)){ 884 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 885 if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue; 886 if (!hci_can_send_acl_packet_now(connection->con_handle)) continue; 887 switch (connection->le_con_parameter_update_state){ 888 case CON_PARAMETER_UPDATE_SEND_REQUEST: 889 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 890 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier, 891 connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout); 892 break; 893 case CON_PARAMETER_UPDATE_SEND_RESPONSE: 894 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 895 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0); 896 break; 897 case CON_PARAMETER_UPDATE_DENY: 898 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 899 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1); 900 break; 901 default: 902 break; 903 } 904 } 905 #endif 906 #endif 907 908 // log_info("l2cap_run: exit"); 909 } 910 911 uint16_t l2cap_max_mtu(void){ 912 return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE; 913 } 914 915 uint16_t l2cap_max_le_mtu(void){ 916 return l2cap_max_mtu(); 917 } 918 919 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){ 920 if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) { 921 log_info("l2cap_handle_connection_complete expected state"); 922 // success, start l2cap handshake 923 channel->con_handle = con_handle; 924 // check remote SSP feature first 925 channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES; 926 } 927 } 928 929 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){ 930 if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return; 931 932 // we have been waiting for remote supported features, if both support SSP, 933 log_info("l2cap received remote supported features, sec_level_0_allowed for psm %u = %u", channel->psm, l2cap_security_level_0_allowed_for_PSM(channel->psm)); 934 if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){ 935 // request security level 2 936 channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE; 937 gap_request_security_level(channel->con_handle, LEVEL_2); 938 return; 939 } 940 // fine, go ahead 941 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 942 } 943 944 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type, 945 uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){ 946 947 l2cap_channel_t * channel = btstack_memory_l2cap_channel_get(); 948 if (!channel) { 949 return NULL; 950 } 951 952 // Init memory (make valgrind happy) 953 memset(channel, 0, sizeof(l2cap_channel_t)); 954 955 // fill in 956 channel->packet_handler = packet_handler; 957 bd_addr_copy(channel->address, address); 958 channel->address_type = address_type; 959 channel->psm = psm; 960 channel->local_mtu = local_mtu; 961 channel->remote_mtu = L2CAP_MINIMAL_MTU; 962 channel->required_security_level = security_level; 963 964 // 965 channel->local_cid = l2cap_next_local_cid(); 966 channel->con_handle = 0; 967 968 // set initial state 969 channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION; 970 channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE; 971 channel->remote_sig_id = L2CAP_SIG_ID_INVALID; 972 channel->local_sig_id = L2CAP_SIG_ID_INVALID; 973 return channel; 974 } 975 976 /** 977 * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary. 978 * @param packet_handler 979 * @param address 980 * @param psm 981 * @param mtu 982 * @param local_cid 983 */ 984 985 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t local_mtu, uint16_t * out_local_cid){ 986 log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, local_mtu); 987 988 if (local_mtu > l2cap_max_mtu()) { 989 local_mtu = l2cap_max_mtu(); 990 } 991 992 l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0); 993 if (!channel) { 994 return BTSTACK_MEMORY_ALLOC_FAILED; 995 } 996 997 // add to connections list 998 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel); 999 1000 // store local_cid 1001 if (out_local_cid){ 1002 *out_local_cid = channel->local_cid; 1003 } 1004 1005 // check if hci connection is already usable 1006 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC); 1007 if (conn){ 1008 log_info("l2cap_create_channel, hci connection already exists"); 1009 l2cap_handle_connection_complete(conn->con_handle, channel); 1010 // check if remote supported fearures are already received 1011 if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) { 1012 l2cap_handle_remote_supported_features_received(channel); 1013 } 1014 } 1015 1016 l2cap_run(); 1017 1018 return 0; 1019 } 1020 1021 void 1022 l2cap_disconnect(uint16_t local_cid, uint8_t reason){ 1023 log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason); 1024 // find channel for local_cid 1025 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1026 if (channel) { 1027 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 1028 } 1029 // process 1030 l2cap_run(); 1031 } 1032 1033 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){ 1034 btstack_linked_list_iterator_t it; 1035 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1036 while (btstack_linked_list_iterator_has_next(&it)){ 1037 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1038 if ( bd_addr_cmp( channel->address, address) != 0) continue; 1039 // channel for this address found 1040 switch (channel->state){ 1041 case L2CAP_STATE_WAIT_CONNECTION_COMPLETE: 1042 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 1043 // failure, forward error code 1044 l2cap_emit_channel_opened(channel, status); 1045 // discard channel 1046 l2cap_stop_rtx(channel); 1047 btstack_linked_list_iterator_remove(&it); 1048 btstack_memory_l2cap_channel_free(channel); 1049 break; 1050 default: 1051 break; 1052 } 1053 } 1054 } 1055 1056 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){ 1057 btstack_linked_list_iterator_t it; 1058 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1059 while (btstack_linked_list_iterator_has_next(&it)){ 1060 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1061 if ( ! bd_addr_cmp( channel->address, address) ){ 1062 l2cap_handle_connection_complete(handle, channel); 1063 } 1064 } 1065 // process 1066 l2cap_run(); 1067 } 1068 1069 1070 #ifdef ENABLE_LE_DATA_CHANNELS 1071 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){ 1072 if (!channel->waiting_for_can_send_now) return; 1073 if (channel->send_sdu_buffer) return; 1074 channel->waiting_for_can_send_now = 0; 1075 log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid); 1076 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW); 1077 } 1078 #endif 1079 1080 static void l2cap_notify_channel_can_send(void){ 1081 btstack_linked_list_iterator_t it; 1082 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1083 while (btstack_linked_list_iterator_has_next(&it)){ 1084 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1085 if (!channel->waiting_for_can_send_now) continue; 1086 if (!hci_can_send_acl_packet_now(channel->con_handle)) continue; 1087 channel->waiting_for_can_send_now = 0; 1088 l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid); 1089 } 1090 1091 1092 int i; 1093 for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){ 1094 if (!fixed_channels[i].callback) continue; 1095 if (!fixed_channels[i].waiting_for_can_send_now) continue; 1096 int can_send; 1097 if (l2cap_fixed_channel_table_index_is_le(i)){ 1098 can_send = hci_can_send_acl_le_packet_now(); 1099 } else { 1100 can_send = hci_can_send_acl_classic_packet_now(); 1101 } 1102 if (!can_send) continue; 1103 fixed_channels[i].waiting_for_can_send_now = 0; 1104 l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i)); 1105 } 1106 } 1107 1108 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){ 1109 1110 bd_addr_t address; 1111 hci_con_handle_t handle; 1112 btstack_linked_list_iterator_t it; 1113 int hci_con_used; 1114 1115 switch(hci_event_packet_get_type(packet)){ 1116 1117 // handle connection complete events 1118 case HCI_EVENT_CONNECTION_COMPLETE: 1119 reverse_bd_addr(&packet[5], address); 1120 if (packet[2] == 0){ 1121 handle = little_endian_read_16(packet, 3); 1122 l2cap_handle_connection_success_for_addr(address, handle); 1123 } else { 1124 l2cap_handle_connection_failed_for_addr(address, packet[2]); 1125 } 1126 break; 1127 1128 // handle successful create connection cancel command 1129 case HCI_EVENT_COMMAND_COMPLETE: 1130 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) { 1131 if (packet[5] == 0){ 1132 reverse_bd_addr(&packet[6], address); 1133 // CONNECTION TERMINATED BY LOCAL HOST (0X16) 1134 l2cap_handle_connection_failed_for_addr(address, 0x16); 1135 } 1136 } 1137 l2cap_run(); // try sending signaling packets first 1138 break; 1139 1140 case HCI_EVENT_COMMAND_STATUS: 1141 l2cap_run(); // try sending signaling packets first 1142 break; 1143 1144 // handle disconnection complete events 1145 case HCI_EVENT_DISCONNECTION_COMPLETE: 1146 // send l2cap disconnect events for all channels on this handle and free them 1147 handle = little_endian_read_16(packet, 3); 1148 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1149 while (btstack_linked_list_iterator_has_next(&it)){ 1150 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1151 if (channel->con_handle != handle) continue; 1152 l2cap_emit_channel_closed(channel); 1153 l2cap_stop_rtx(channel); 1154 btstack_linked_list_iterator_remove(&it); 1155 btstack_memory_l2cap_channel_free(channel); 1156 } 1157 #ifdef ENABLE_BLE 1158 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1159 while (btstack_linked_list_iterator_has_next(&it)){ 1160 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1161 if (channel->con_handle != handle) continue; 1162 l2cap_emit_channel_closed(channel); 1163 btstack_linked_list_iterator_remove(&it); 1164 btstack_memory_l2cap_channel_free(channel); 1165 } 1166 #endif 1167 break; 1168 1169 // Notify channel packet handler if they can send now 1170 case HCI_EVENT_TRANSPORT_PACKET_SENT: 1171 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 1172 l2cap_run(); // try sending signaling packets first 1173 l2cap_notify_channel_can_send(); 1174 break; 1175 1176 // HCI Connection Timeouts 1177 case L2CAP_EVENT_TIMEOUT_CHECK: 1178 handle = little_endian_read_16(packet, 2); 1179 if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break; 1180 if (hci_authentication_active_for_handle(handle)) break; 1181 hci_con_used = 0; 1182 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1183 while (btstack_linked_list_iterator_has_next(&it)){ 1184 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1185 if (channel->con_handle != handle) continue; 1186 hci_con_used = 1; 1187 break; 1188 } 1189 if (hci_con_used) break; 1190 if (!hci_can_send_command_packet_now()) break; 1191 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection 1192 break; 1193 1194 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 1195 handle = little_endian_read_16(packet, 3); 1196 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1197 while (btstack_linked_list_iterator_has_next(&it)){ 1198 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1199 if (channel->con_handle != handle) continue; 1200 l2cap_handle_remote_supported_features_received(channel); 1201 break; 1202 } 1203 break; 1204 1205 case GAP_EVENT_SECURITY_LEVEL: 1206 handle = little_endian_read_16(packet, 2); 1207 log_info("l2cap - security level update"); 1208 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1209 while (btstack_linked_list_iterator_has_next(&it)){ 1210 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1211 if (channel->con_handle != handle) continue; 1212 1213 log_info("l2cap - state %u", channel->state); 1214 1215 gap_security_level_t actual_level = (gap_security_level_t) packet[4]; 1216 gap_security_level_t required_level = channel->required_security_level; 1217 1218 switch (channel->state){ 1219 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 1220 if (actual_level >= required_level){ 1221 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 1222 l2cap_emit_incoming_connection(channel); 1223 } else { 1224 channel->reason = 0x0003; // security block 1225 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 1226 } 1227 break; 1228 1229 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE: 1230 if (actual_level >= required_level){ 1231 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 1232 } else { 1233 // disconnnect, authentication not good enough 1234 hci_disconnect_security_block(handle); 1235 } 1236 break; 1237 1238 default: 1239 break; 1240 } 1241 } 1242 break; 1243 1244 default: 1245 break; 1246 } 1247 1248 l2cap_run(); 1249 } 1250 1251 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){ 1252 channel->remote_sig_id = identifier; 1253 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 1254 l2cap_run(); 1255 } 1256 1257 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){ 1258 // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused." 1259 if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) { 1260 signaling_responses[signaling_responses_pending].handle = handle; 1261 signaling_responses[signaling_responses_pending].code = code; 1262 signaling_responses[signaling_responses_pending].sig_id = sig_id; 1263 signaling_responses[signaling_responses_pending].data = data; 1264 signaling_responses_pending++; 1265 l2cap_run(); 1266 } 1267 } 1268 1269 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){ 1270 1271 // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid); 1272 l2cap_service_t *service = l2cap_get_service(psm); 1273 if (!service) { 1274 // 0x0002 PSM not supported 1275 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002); 1276 return; 1277 } 1278 1279 hci_connection_t * hci_connection = hci_connection_for_handle( handle ); 1280 if (!hci_connection) { 1281 // 1282 log_error("no hci_connection for handle %u", handle); 1283 return; 1284 } 1285 1286 // alloc structure 1287 // log_info("l2cap_handle_connection_request register channel"); 1288 l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC, 1289 psm, service->mtu, service->required_security_level); 1290 if (!channel){ 1291 // 0x0004 No resources available 1292 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004); 1293 return; 1294 } 1295 1296 channel->con_handle = handle; 1297 channel->remote_cid = source_cid; 1298 channel->remote_sig_id = sig_id; 1299 1300 // limit local mtu to max acl packet length - l2cap header 1301 if (channel->local_mtu > l2cap_max_mtu()) { 1302 channel->local_mtu = l2cap_max_mtu(); 1303 } 1304 1305 // set initial state 1306 channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE; 1307 channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND; 1308 1309 // add to connections list 1310 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel); 1311 1312 // assert security requirements 1313 gap_request_security_level(handle, channel->required_security_level); 1314 } 1315 1316 void l2cap_accept_connection(uint16_t local_cid){ 1317 log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid); 1318 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1319 if (!channel) { 1320 log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid); 1321 return; 1322 } 1323 1324 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 1325 1326 // process 1327 l2cap_run(); 1328 } 1329 1330 void l2cap_decline_connection(uint16_t local_cid){ 1331 log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid); 1332 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 1333 if (!channel) { 1334 log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid); 1335 return; 1336 } 1337 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 1338 channel->reason = 0x04; // no resources available 1339 l2cap_run(); 1340 } 1341 1342 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){ 1343 1344 channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1345 1346 uint16_t flags = little_endian_read_16(command, 6); 1347 if (flags & 1) { 1348 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 1349 } 1350 1351 // accept the other's configuration options 1352 uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1353 uint16_t pos = 8; 1354 while (pos < end_pos){ 1355 uint8_t option_hint = command[pos] >> 7; 1356 uint8_t option_type = command[pos] & 0x7f; 1357 log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type); 1358 pos++; 1359 uint8_t length = command[pos++]; 1360 // MTU { type(8): 1, len(8):2, MTU(16) } 1361 if (option_type == 1 && length == 2){ 1362 channel->remote_mtu = little_endian_read_16(command, pos); 1363 // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu); 1364 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 1365 } 1366 // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)} 1367 if (option_type == 2 && length == 2){ 1368 channel->flush_timeout = little_endian_read_16(command, pos); 1369 } 1370 // check for unknown options 1371 if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){ 1372 log_info("l2cap cid %u, unknown options", channel->local_cid); 1373 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID); 1374 } 1375 pos += length; 1376 } 1377 } 1378 1379 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){ 1380 // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var); 1381 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0; 1382 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0; 1383 // addition check that fixes re-entrance issue causing l2cap event channel opened twice 1384 if (channel->state == L2CAP_STATE_OPEN) return 0; 1385 return 1; 1386 } 1387 1388 1389 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){ 1390 1391 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1392 uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1393 uint16_t result = 0; 1394 1395 log_info("L2CAP signaling handler code %u, state %u", code, channel->state); 1396 1397 // handle DISCONNECT REQUESTS seperately 1398 if (code == DISCONNECTION_REQUEST){ 1399 switch (channel->state){ 1400 case L2CAP_STATE_CONFIG: 1401 case L2CAP_STATE_OPEN: 1402 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 1403 case L2CAP_STATE_WAIT_DISCONNECT: 1404 l2cap_handle_disconnect_request(channel, identifier); 1405 break; 1406 1407 default: 1408 // ignore in other states 1409 break; 1410 } 1411 return; 1412 } 1413 1414 // @STATEMACHINE(l2cap) 1415 switch (channel->state) { 1416 1417 case L2CAP_STATE_WAIT_CONNECT_RSP: 1418 switch (code){ 1419 case CONNECTION_RESPONSE: 1420 l2cap_stop_rtx(channel); 1421 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1422 switch (result) { 1423 case 0: 1424 // successful connection 1425 channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1426 channel->state = L2CAP_STATE_CONFIG; 1427 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1428 break; 1429 case 1: 1430 // connection pending. get some coffee, but start the ERTX 1431 l2cap_start_ertx(channel); 1432 break; 1433 default: 1434 // channel closed 1435 channel->state = L2CAP_STATE_CLOSED; 1436 // map l2cap connection response result to BTstack status enumeration 1437 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result); 1438 1439 // drop link key if security block 1440 if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){ 1441 gap_drop_link_key_for_bd_addr(channel->address); 1442 } 1443 1444 // discard channel 1445 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 1446 btstack_memory_l2cap_channel_free(channel); 1447 break; 1448 } 1449 break; 1450 1451 default: 1452 //@TODO: implement other signaling packets 1453 break; 1454 } 1455 break; 1456 1457 case L2CAP_STATE_CONFIG: 1458 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1459 switch (code) { 1460 case CONFIGURE_REQUEST: 1461 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 1462 l2cap_signaling_handle_configure_request(channel, command); 1463 if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){ 1464 // only done if continuation not set 1465 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ); 1466 } 1467 break; 1468 case CONFIGURE_RESPONSE: 1469 l2cap_stop_rtx(channel); 1470 switch (result){ 1471 case 0: // success 1472 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP); 1473 break; 1474 case 4: // pending 1475 l2cap_start_ertx(channel); 1476 break; 1477 default: 1478 // retry on negative result 1479 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1480 break; 1481 } 1482 break; 1483 default: 1484 break; 1485 } 1486 if (l2cap_channel_ready_for_open(channel)){ 1487 // for open: 1488 channel->state = L2CAP_STATE_OPEN; 1489 l2cap_emit_channel_opened(channel, 0); 1490 } 1491 break; 1492 1493 case L2CAP_STATE_WAIT_DISCONNECT: 1494 switch (code) { 1495 case DISCONNECTION_RESPONSE: 1496 l2cap_finialize_channel_close(channel); 1497 break; 1498 default: 1499 //@TODO: implement other signaling packets 1500 break; 1501 } 1502 break; 1503 1504 case L2CAP_STATE_CLOSED: 1505 // @TODO handle incoming requests 1506 break; 1507 1508 case L2CAP_STATE_OPEN: 1509 //@TODO: implement other signaling packets, e.g. re-configure 1510 break; 1511 default: 1512 break; 1513 } 1514 // log_info("new state %u", channel->state); 1515 } 1516 1517 1518 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){ 1519 1520 // get code, signalind identifier and command len 1521 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1522 uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1523 1524 // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST 1525 if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){ 1526 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1527 return; 1528 } 1529 1530 // general commands without an assigned channel 1531 switch(code) { 1532 1533 case CONNECTION_REQUEST: { 1534 uint16_t psm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1535 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 1536 l2cap_handle_connection_request(handle, sig_id, psm, source_cid); 1537 return; 1538 } 1539 1540 case ECHO_REQUEST: 1541 l2cap_register_signaling_response(handle, code, sig_id, 0); 1542 return; 1543 1544 case INFORMATION_REQUEST: { 1545 uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1546 l2cap_register_signaling_response(handle, code, sig_id, infoType); 1547 return; 1548 } 1549 1550 default: 1551 break; 1552 } 1553 1554 1555 // Get potential destination CID 1556 uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1557 1558 // Find channel for this sig_id and connection handle 1559 btstack_linked_list_iterator_t it; 1560 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1561 while (btstack_linked_list_iterator_has_next(&it)){ 1562 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1563 if (channel->con_handle != handle) continue; 1564 if (code & 1) { 1565 // match odd commands (responses) by previous signaling identifier 1566 if (channel->local_sig_id == sig_id) { 1567 l2cap_signaling_handler_channel(channel, command); 1568 break; 1569 } 1570 } else { 1571 // match even commands (requests) by local channel id 1572 if (channel->local_cid == dest_cid) { 1573 l2cap_signaling_handler_channel(channel, command); 1574 break; 1575 } 1576 } 1577 } 1578 } 1579 1580 #ifdef ENABLE_BLE 1581 // @returns valid 1582 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){ 1583 hci_connection_t * connection; 1584 uint16_t result; 1585 uint8_t event[10]; 1586 uint16_t local_cid; 1587 l2cap_channel_t * channel; 1588 btstack_linked_list_iterator_t it; 1589 1590 #ifdef ENABLE_LE_DATA_CHANNELS 1591 uint16_t le_psm; 1592 uint16_t new_credits; 1593 uint16_t credits_before; 1594 l2cap_service_t * service; 1595 #endif 1596 1597 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1598 log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id); 1599 1600 switch (code){ 1601 1602 case CONNECTION_PARAMETER_UPDATE_RESPONSE: 1603 result = little_endian_read_16(command, 4); 1604 l2cap_emit_connection_parameter_update_response(handle, result); 1605 break; 1606 1607 case CONNECTION_PARAMETER_UPDATE_REQUEST: 1608 connection = hci_connection_for_handle(handle); 1609 if (connection){ 1610 if (connection->role != HCI_ROLE_MASTER){ 1611 // reject command without notifying upper layer when not in master role 1612 return 0; 1613 } 1614 int update_parameter = 1; 1615 le_connection_parameter_range_t existing_range; 1616 gap_get_connection_parameter_range(&existing_range); 1617 uint16_t le_conn_interval_min = little_endian_read_16(command,8); 1618 uint16_t le_conn_interval_max = little_endian_read_16(command,10); 1619 uint16_t le_conn_latency = little_endian_read_16(command,12); 1620 uint16_t le_supervision_timeout = little_endian_read_16(command,14); 1621 1622 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0; 1623 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0; 1624 1625 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0; 1626 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0; 1627 1628 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0; 1629 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0; 1630 1631 if (update_parameter){ 1632 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE; 1633 connection->le_conn_interval_min = le_conn_interval_min; 1634 connection->le_conn_interval_max = le_conn_interval_max; 1635 connection->le_conn_latency = le_conn_latency; 1636 connection->le_supervision_timeout = le_supervision_timeout; 1637 } else { 1638 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY; 1639 } 1640 connection->le_con_param_update_identifier = sig_id; 1641 } 1642 1643 if (!l2cap_event_packet_handler) break; 1644 1645 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST; 1646 event[1] = 8; 1647 memcpy(&event[2], &command[4], 8); 1648 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1649 (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1650 break; 1651 1652 case COMMAND_REJECT: 1653 // Find channel for this sig_id and connection handle 1654 channel = NULL; 1655 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1656 while (btstack_linked_list_iterator_has_next(&it)){ 1657 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1658 if (a_channel->con_handle != handle) continue; 1659 if (a_channel->local_sig_id != sig_id) continue; 1660 channel = a_channel; 1661 break; 1662 } 1663 if (!channel) break; 1664 1665 // if received while waiting for le connection response, assume legacy device 1666 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){ 1667 channel->state = L2CAP_STATE_CLOSED; 1668 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002 1669 l2cap_emit_le_channel_opened(channel, 0x0002); 1670 1671 // discard channel 1672 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1673 btstack_memory_l2cap_channel_free(channel); 1674 break; 1675 } 1676 break; 1677 1678 #ifdef ENABLE_LE_DATA_CHANNELS 1679 case LE_CREDIT_BASED_CONNECTION_REQUEST: 1680 1681 // get hci connection, bail if not found (must not happen) 1682 connection = hci_connection_for_handle(handle); 1683 if (!connection) return 0; 1684 1685 // check if service registered 1686 le_psm = little_endian_read_16(command, 4); 1687 service = l2cap_le_get_service(le_psm); 1688 1689 if (service){ 1690 1691 uint16_t source_cid = little_endian_read_16(command, 6); 1692 if (source_cid < 0x40){ 1693 // 0x0009 Connection refused - Invalid Source CID 1694 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0009); 1695 return 1; 1696 } 1697 1698 // go through list of channels for this ACL connection and check if we get a match 1699 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1700 while (btstack_linked_list_iterator_has_next(&it)){ 1701 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1702 if (a_channel->con_handle != handle) continue; 1703 if (a_channel->remote_cid != source_cid) continue; 1704 // 0x000a Connection refused - Source CID already allocated 1705 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x000a); 1706 return 1; 1707 } 1708 1709 // security: check encryption 1710 if (service->required_security_level >= LEVEL_2){ 1711 if (sm_encryption_key_size(handle) == 0){ 1712 // 0x0008 Connection refused - insufficient encryption 1713 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0008); 1714 return 1; 1715 } 1716 // anything less than 16 byte key size is insufficient 1717 if (sm_encryption_key_size(handle) < 16){ 1718 // 0x0007 Connection refused – insufficient encryption key size 1719 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0007); 1720 return 1; 1721 } 1722 } 1723 1724 // security: check authencation 1725 if (service->required_security_level >= LEVEL_3){ 1726 if (!sm_authenticated(handle)){ 1727 // 0x0005 Connection refused – insufficient authentication 1728 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0005); 1729 return 1; 1730 } 1731 } 1732 1733 // security: check authorization 1734 if (service->required_security_level >= LEVEL_4){ 1735 if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){ 1736 // 0x0006 Connection refused – insufficient authorization 1737 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0006); 1738 return 1; 1739 } 1740 } 1741 1742 // allocate channel 1743 channel = l2cap_create_channel_entry(service->packet_handler, connection->address, 1744 BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level); 1745 if (!channel){ 1746 // 0x0004 Connection refused – no resources available 1747 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0004); 1748 return 1; 1749 } 1750 1751 channel->con_handle = handle; 1752 channel->remote_cid = source_cid; 1753 channel->remote_sig_id = sig_id; 1754 channel->remote_mtu = little_endian_read_16(command, 8); 1755 channel->remote_mps = little_endian_read_16(command, 10); 1756 channel->credits_outgoing = little_endian_read_16(command, 12); 1757 1758 // set initial state 1759 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 1760 1761 // add to connections list 1762 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1763 1764 // post connection request event 1765 l2cap_emit_le_incoming_connection(channel); 1766 1767 } else { 1768 // Connection refused – LE_PSM not supported 1769 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0002); 1770 } 1771 break; 1772 1773 case LE_CREDIT_BASED_CONNECTION_RESPONSE: 1774 // Find channel for this sig_id and connection handle 1775 channel = NULL; 1776 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1777 while (btstack_linked_list_iterator_has_next(&it)){ 1778 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1779 if (a_channel->con_handle != handle) continue; 1780 if (a_channel->local_sig_id != sig_id) continue; 1781 channel = a_channel; 1782 break; 1783 } 1784 if (!channel) break; 1785 1786 // cid + 0 1787 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8); 1788 if (result){ 1789 channel->state = L2CAP_STATE_CLOSED; 1790 // map l2cap connection response result to BTstack status enumeration 1791 l2cap_emit_le_channel_opened(channel, result); 1792 1793 // discard channel 1794 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1795 btstack_memory_l2cap_channel_free(channel); 1796 break; 1797 } 1798 1799 // success 1800 channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 1801 channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2); 1802 channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4); 1803 channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6); 1804 channel->state = L2CAP_STATE_OPEN; 1805 l2cap_emit_le_channel_opened(channel, result); 1806 break; 1807 1808 case LE_FLOW_CONTROL_CREDIT: 1809 // find channel 1810 local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 1811 channel = l2cap_le_get_channel_for_local_cid(local_cid); 1812 if (!channel) { 1813 log_error("l2cap: no channel for cid 0x%02x", local_cid); 1814 break; 1815 } 1816 new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2); 1817 credits_before = channel->credits_outgoing; 1818 channel->credits_outgoing += new_credits; 1819 // check for credit overrun 1820 if (credits_before > channel->credits_outgoing){ 1821 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid); 1822 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 1823 break; 1824 } 1825 log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing); 1826 break; 1827 #endif 1828 1829 case DISCONNECTION_REQUEST: 1830 // find channel 1831 local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 1832 channel = l2cap_le_get_channel_for_local_cid(local_cid); 1833 if (!channel) { 1834 log_error("l2cap: no channel for cid 0x%02x", local_cid); 1835 break; 1836 } 1837 channel->remote_sig_id = sig_id; 1838 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 1839 break; 1840 1841 case DISCONNECTION_RESPONSE: 1842 break; 1843 1844 default: 1845 // command unknown -> reject command 1846 return 0; 1847 } 1848 return 1; 1849 } 1850 #endif 1851 1852 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){ 1853 1854 // Get Channel ID 1855 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 1856 hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet); 1857 1858 switch (channel_id) { 1859 1860 case L2CAP_CID_SIGNALING: { 1861 uint16_t command_offset = 8; 1862 while (command_offset < size) { 1863 // handle signaling commands 1864 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]); 1865 1866 // increment command_offset 1867 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1868 } 1869 break; 1870 } 1871 1872 #ifdef ENABLE_BLE 1873 case L2CAP_CID_SIGNALING_LE: { 1874 uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1]; 1875 int valid = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id); 1876 if (!valid){ 1877 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1878 } 1879 break; 1880 } 1881 #endif 1882 1883 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1884 if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) { 1885 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1886 } 1887 break; 1888 1889 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1890 if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) { 1891 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1892 } 1893 break; 1894 1895 case L2CAP_CID_CONNECTIONLESS_CHANNEL: 1896 if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) { 1897 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1898 } 1899 break; 1900 1901 default: { 1902 // Find channel for this channel_id and connection handle 1903 l2cap_channel_t * l2cap_channel; 1904 l2cap_channel = l2cap_get_channel_for_local_cid(channel_id); 1905 if (l2cap_channel) { 1906 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1907 } 1908 #ifdef ENABLE_BLE 1909 l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id); 1910 if (l2cap_channel) { 1911 // credit counting 1912 if (l2cap_channel->credits_incoming == 0){ 1913 log_error("LE Data Channel packet received but no incoming credits"); 1914 l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 1915 break; 1916 } 1917 l2cap_channel->credits_incoming--; 1918 1919 // automatic credits 1920 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){ 1921 l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT; 1922 } 1923 1924 // first fragment 1925 uint16_t pos = 0; 1926 if (!l2cap_channel->receive_sdu_len){ 1927 l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER); 1928 l2cap_channel->receive_sdu_pos = 0; 1929 pos += 2; 1930 size -= 2; 1931 } 1932 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER); 1933 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER; 1934 // done? 1935 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len); 1936 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){ 1937 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len); 1938 l2cap_channel->receive_sdu_len = 0; 1939 } 1940 } else { 1941 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id); 1942 } 1943 #endif 1944 break; 1945 } 1946 } 1947 1948 l2cap_run(); 1949 } 1950 1951 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 1952 void l2cap_finialize_channel_close(l2cap_channel_t * channel){ 1953 channel->state = L2CAP_STATE_CLOSED; 1954 l2cap_emit_channel_closed(channel); 1955 // discard channel 1956 l2cap_stop_rtx(channel); 1957 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 1958 btstack_memory_l2cap_channel_free(channel); 1959 } 1960 1961 #ifdef ENABLE_LE_DATA_CHANNELS 1962 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 1963 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){ 1964 channel->state = L2CAP_STATE_CLOSED; 1965 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED); 1966 // discard channel 1967 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1968 btstack_memory_l2cap_channel_free(channel); 1969 } 1970 #endif 1971 1972 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){ 1973 btstack_linked_list_iterator_t it; 1974 btstack_linked_list_iterator_init(&it, services); 1975 while (btstack_linked_list_iterator_has_next(&it)){ 1976 l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it); 1977 if ( service->psm == psm){ 1978 return service; 1979 }; 1980 } 1981 return NULL; 1982 } 1983 1984 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){ 1985 return l2cap_get_service_internal(&l2cap_services, psm); 1986 } 1987 1988 1989 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){ 1990 1991 log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu); 1992 1993 // check for alread registered psm 1994 l2cap_service_t *service = l2cap_get_service(psm); 1995 if (service) { 1996 log_error("l2cap_register_service: PSM %u already registered", psm); 1997 return L2CAP_SERVICE_ALREADY_REGISTERED; 1998 } 1999 2000 // alloc structure 2001 service = btstack_memory_l2cap_service_get(); 2002 if (!service) { 2003 log_error("l2cap_register_service: no memory for l2cap_service_t"); 2004 return BTSTACK_MEMORY_ALLOC_FAILED; 2005 } 2006 2007 // fill in 2008 service->psm = psm; 2009 service->mtu = mtu; 2010 service->packet_handler = service_packet_handler; 2011 service->required_security_level = security_level; 2012 2013 // add to services list 2014 btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service); 2015 2016 // enable page scan 2017 gap_connectable_control(1); 2018 2019 return 0; 2020 } 2021 2022 uint8_t l2cap_unregister_service(uint16_t psm){ 2023 2024 log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm); 2025 2026 l2cap_service_t *service = l2cap_get_service(psm); 2027 if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST; 2028 btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service); 2029 btstack_memory_l2cap_service_free(service); 2030 2031 // disable page scan when no services registered 2032 if (btstack_linked_list_empty(&l2cap_services)) { 2033 gap_connectable_control(0); 2034 } 2035 return 0; 2036 } 2037 2038 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol 2039 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) { 2040 int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id); 2041 if (index < 0) return; 2042 fixed_channels[index].callback = the_packet_handler; 2043 } 2044 2045 #ifdef ENABLE_BLE 2046 2047 #ifdef ENABLE_LE_DATA_CHANNELS 2048 2049 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){ 2050 return l2cap_get_service_internal(&l2cap_le_services, le_psm); 2051 } 2052 2053 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){ 2054 2055 log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm); 2056 2057 // check for alread registered psm 2058 l2cap_service_t *service = l2cap_le_get_service(psm); 2059 if (service) { 2060 return L2CAP_SERVICE_ALREADY_REGISTERED; 2061 } 2062 2063 // alloc structure 2064 service = btstack_memory_l2cap_service_get(); 2065 if (!service) { 2066 log_error("l2cap_register_service_internal: no memory for l2cap_service_t"); 2067 return BTSTACK_MEMORY_ALLOC_FAILED; 2068 } 2069 2070 // fill in 2071 service->psm = psm; 2072 service->mtu = 0; 2073 service->packet_handler = packet_handler; 2074 service->required_security_level = security_level; 2075 2076 // add to services list 2077 btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service); 2078 2079 // done 2080 return 0; 2081 } 2082 2083 uint8_t l2cap_le_unregister_service(uint16_t psm) { 2084 log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm); 2085 l2cap_service_t *service = l2cap_le_get_service(psm); 2086 if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST; 2087 2088 btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service); 2089 btstack_memory_l2cap_service_free(service); 2090 return 0; 2091 } 2092 2093 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){ 2094 // get channel 2095 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2096 if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2097 2098 // validate state 2099 if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){ 2100 return ERROR_CODE_COMMAND_DISALLOWED; 2101 } 2102 2103 // set state accept connection 2104 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT; 2105 channel->receive_sdu_buffer = receive_sdu_buffer; 2106 channel->local_mtu = mtu; 2107 channel->new_credits_incoming = initial_credits; 2108 channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS; 2109 2110 // test 2111 // channel->new_credits_incoming = 1; 2112 2113 // go 2114 l2cap_run(); 2115 return 0; 2116 } 2117 2118 /** 2119 * @brief Deny incoming LE Data Channel connection due to resource constraints 2120 * @param local_cid L2CAP LE Data Channel Identifier 2121 */ 2122 2123 uint8_t l2cap_le_decline_connection(uint16_t local_cid){ 2124 // get channel 2125 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2126 if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2127 2128 // validate state 2129 if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){ 2130 return ERROR_CODE_COMMAND_DISALLOWED; 2131 } 2132 2133 // set state decline connection 2134 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE; 2135 channel->reason = 0x04; // no resources available 2136 l2cap_run(); 2137 return 0; 2138 } 2139 2140 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle, 2141 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level, 2142 uint16_t * out_local_cid) { 2143 2144 log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu); 2145 2146 2147 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2148 if (!connection) { 2149 log_error("no hci_connection for handle 0x%04x", con_handle); 2150 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 2151 } 2152 2153 l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level); 2154 if (!channel) { 2155 return BTSTACK_MEMORY_ALLOC_FAILED; 2156 } 2157 log_info("l2cap_le_create_channel %p", channel); 2158 2159 // store local_cid 2160 if (out_local_cid){ 2161 *out_local_cid = channel->local_cid; 2162 } 2163 2164 // provide buffer 2165 channel->con_handle = con_handle; 2166 channel->receive_sdu_buffer = receive_sdu_buffer; 2167 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST; 2168 channel->new_credits_incoming = initial_credits; 2169 channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS; 2170 2171 // add to connections list 2172 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel); 2173 2174 // go 2175 l2cap_run(); 2176 return 0; 2177 } 2178 2179 /** 2180 * @brief Provide credtis for LE Data Channel 2181 * @param local_cid L2CAP LE Data Channel Identifier 2182 * @param credits Number additional credits for peer 2183 */ 2184 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){ 2185 2186 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2187 if (!channel) { 2188 log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid); 2189 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2190 } 2191 2192 // check state 2193 if (channel->state != L2CAP_STATE_OPEN){ 2194 log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid); 2195 } 2196 2197 // assert incoming credits + credits <= 0xffff 2198 uint32_t total_credits = channel->credits_incoming; 2199 total_credits += channel->new_credits_incoming; 2200 total_credits += credits; 2201 if (total_credits > 0xffff){ 2202 log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming, 2203 channel->new_credits_incoming, credits); 2204 } 2205 2206 // set credits_granted 2207 channel->new_credits_incoming += credits; 2208 2209 // go 2210 l2cap_run(); 2211 return 0; 2212 } 2213 2214 /** 2215 * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module 2216 * @param local_cid L2CAP LE Data Channel Identifier 2217 */ 2218 int l2cap_le_can_send_now(uint16_t local_cid){ 2219 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2220 if (!channel) { 2221 log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid); 2222 return 0; 2223 } 2224 2225 // check state 2226 if (channel->state != L2CAP_STATE_OPEN) return 0; 2227 2228 // check queue 2229 if (channel->send_sdu_buffer) return 0; 2230 2231 // fine, go ahead 2232 return 1; 2233 } 2234 2235 /** 2236 * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible 2237 * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function 2238 * so packet handler should be ready to handle it 2239 * @param local_cid L2CAP LE Data Channel Identifier 2240 */ 2241 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){ 2242 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2243 if (!channel) { 2244 log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid); 2245 return 0; 2246 } 2247 channel->waiting_for_can_send_now = 1; 2248 l2cap_le_notify_channel_can_send(channel); 2249 return 0; 2250 } 2251 2252 /** 2253 * @brief Send data via LE Data Channel 2254 * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event 2255 * @param local_cid L2CAP LE Data Channel Identifier 2256 * @param data data to send 2257 * @param size data size 2258 */ 2259 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){ 2260 2261 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2262 if (!channel) { 2263 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 2264 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2265 } 2266 2267 if (len > channel->remote_mtu){ 2268 log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid); 2269 return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU; 2270 } 2271 2272 if (channel->send_sdu_buffer){ 2273 log_info("l2cap_send cid 0x%02x, cannot send", local_cid); 2274 return BTSTACK_ACL_BUFFERS_FULL; 2275 } 2276 2277 channel->send_sdu_buffer = data; 2278 channel->send_sdu_len = len; 2279 channel->send_sdu_pos = 0; 2280 2281 l2cap_run(); 2282 return 0; 2283 } 2284 2285 /** 2286 * @brief Disconnect from LE Data Channel 2287 * @param local_cid L2CAP LE Data Channel Identifier 2288 */ 2289 uint8_t l2cap_le_disconnect(uint16_t local_cid) 2290 { 2291 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2292 if (!channel) { 2293 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 2294 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2295 } 2296 2297 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2298 l2cap_run(); 2299 return 0; 2300 } 2301 2302 #endif 2303 2304 #endif 2305