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