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