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