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