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