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 1092 switch(hci_event_packet_get_type(packet)){ 1093 1094 // Notify channel packet handler if they can send now 1095 case HCI_EVENT_TRANSPORT_PACKET_SENT: 1096 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 1097 l2cap_run(); // try sending signaling packets first 1098 l2cap_notify_channel_can_send(); 1099 break; 1100 1101 case HCI_EVENT_COMMAND_STATUS: 1102 l2cap_run(); // try sending signaling packets first 1103 break; 1104 1105 #ifdef ENABLE_CLASSIC 1106 // handle connection complete events 1107 case HCI_EVENT_CONNECTION_COMPLETE: 1108 reverse_bd_addr(&packet[5], address); 1109 if (packet[2] == 0){ 1110 handle = little_endian_read_16(packet, 3); 1111 l2cap_handle_connection_success_for_addr(address, handle); 1112 } else { 1113 l2cap_handle_connection_failed_for_addr(address, packet[2]); 1114 } 1115 break; 1116 1117 // handle successful create connection cancel command 1118 case HCI_EVENT_COMMAND_COMPLETE: 1119 if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) { 1120 if (packet[5] == 0){ 1121 reverse_bd_addr(&packet[6], address); 1122 // CONNECTION TERMINATED BY LOCAL HOST (0X16) 1123 l2cap_handle_connection_failed_for_addr(address, 0x16); 1124 } 1125 } 1126 l2cap_run(); // try sending signaling packets first 1127 break; 1128 #endif 1129 1130 // handle disconnection complete events 1131 case HCI_EVENT_DISCONNECTION_COMPLETE: 1132 // send l2cap disconnect events for all channels on this handle and free them 1133 #ifdef ENABLE_CLASSIC 1134 handle = little_endian_read_16(packet, 3); 1135 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1136 while (btstack_linked_list_iterator_has_next(&it)){ 1137 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1138 if (channel->con_handle != handle) continue; 1139 l2cap_emit_channel_closed(channel); 1140 l2cap_stop_rtx(channel); 1141 btstack_linked_list_iterator_remove(&it); 1142 btstack_memory_l2cap_channel_free(channel); 1143 } 1144 #endif 1145 #ifdef ENABLE_LE_DATA_CHANNELS 1146 handle = little_endian_read_16(packet, 3); 1147 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1148 while (btstack_linked_list_iterator_has_next(&it)){ 1149 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1150 if (channel->con_handle != handle) continue; 1151 l2cap_emit_channel_closed(channel); 1152 btstack_linked_list_iterator_remove(&it); 1153 btstack_memory_l2cap_channel_free(channel); 1154 } 1155 #endif 1156 break; 1157 1158 // HCI Connection Timeouts 1159 #ifdef ENABLE_CLASSIC 1160 case L2CAP_EVENT_TIMEOUT_CHECK: 1161 handle = little_endian_read_16(packet, 2); 1162 if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break; 1163 if (hci_authentication_active_for_handle(handle)) break; 1164 hci_con_used = 0; 1165 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1166 while (btstack_linked_list_iterator_has_next(&it)){ 1167 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1168 if (channel->con_handle != handle) continue; 1169 hci_con_used = 1; 1170 break; 1171 } 1172 if (hci_con_used) break; 1173 if (!hci_can_send_command_packet_now()) break; 1174 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection 1175 break; 1176 1177 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 1178 handle = little_endian_read_16(packet, 3); 1179 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1180 while (btstack_linked_list_iterator_has_next(&it)){ 1181 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1182 if (channel->con_handle != handle) continue; 1183 l2cap_handle_remote_supported_features_received(channel); 1184 break; 1185 } 1186 break; 1187 1188 case GAP_EVENT_SECURITY_LEVEL: 1189 handle = little_endian_read_16(packet, 2); 1190 log_info("l2cap - security level update"); 1191 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1192 while (btstack_linked_list_iterator_has_next(&it)){ 1193 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1194 if (channel->con_handle != handle) continue; 1195 1196 log_info("l2cap - state %u", channel->state); 1197 1198 gap_security_level_t actual_level = (gap_security_level_t) packet[4]; 1199 gap_security_level_t required_level = channel->required_security_level; 1200 1201 switch (channel->state){ 1202 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 1203 if (actual_level >= required_level){ 1204 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 1205 l2cap_emit_incoming_connection(channel); 1206 } else { 1207 channel->reason = 0x0003; // security block 1208 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 1209 } 1210 break; 1211 1212 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE: 1213 if (actual_level >= required_level){ 1214 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 1215 } else { 1216 // disconnnect, authentication not good enough 1217 hci_disconnect_security_block(handle); 1218 } 1219 break; 1220 1221 default: 1222 break; 1223 } 1224 } 1225 break; 1226 #endif 1227 1228 default: 1229 break; 1230 } 1231 1232 l2cap_run(); 1233 } 1234 1235 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){ 1236 // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused." 1237 if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) { 1238 signaling_responses[signaling_responses_pending].handle = handle; 1239 signaling_responses[signaling_responses_pending].code = code; 1240 signaling_responses[signaling_responses_pending].sig_id = sig_id; 1241 signaling_responses[signaling_responses_pending].data = data; 1242 signaling_responses_pending++; 1243 l2cap_run(); 1244 } 1245 } 1246 1247 #ifdef ENABLE_CLASSIC 1248 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){ 1249 channel->remote_sig_id = identifier; 1250 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 1251 l2cap_run(); 1252 } 1253 1254 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){ 1255 1256 // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid); 1257 l2cap_service_t *service = l2cap_get_service(psm); 1258 if (!service) { 1259 // 0x0002 PSM not supported 1260 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002); 1261 return; 1262 } 1263 1264 hci_connection_t * hci_connection = hci_connection_for_handle( handle ); 1265 if (!hci_connection) { 1266 // 1267 log_error("no hci_connection for handle %u", handle); 1268 return; 1269 } 1270 1271 // alloc structure 1272 // log_info("l2cap_handle_connection_request register channel"); 1273 l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC, 1274 psm, service->mtu, service->required_security_level); 1275 if (!channel){ 1276 // 0x0004 No resources available 1277 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004); 1278 return; 1279 } 1280 1281 channel->con_handle = handle; 1282 channel->remote_cid = source_cid; 1283 channel->remote_sig_id = sig_id; 1284 1285 // limit local mtu to max acl packet length - l2cap header 1286 if (channel->local_mtu > l2cap_max_mtu()) { 1287 channel->local_mtu = l2cap_max_mtu(); 1288 } 1289 1290 // set initial state 1291 channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE; 1292 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING); 1293 1294 // add to connections list 1295 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel); 1296 1297 // assert security requirements 1298 gap_request_security_level(handle, channel->required_security_level); 1299 } 1300 1301 void l2cap_accept_connection(uint16_t local_cid){ 1302 log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid); 1303 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1304 if (!channel) { 1305 log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid); 1306 return; 1307 } 1308 1309 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 1310 1311 // process 1312 l2cap_run(); 1313 } 1314 1315 void l2cap_decline_connection(uint16_t local_cid){ 1316 log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid); 1317 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 1318 if (!channel) { 1319 log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid); 1320 return; 1321 } 1322 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 1323 channel->reason = 0x04; // no resources available 1324 l2cap_run(); 1325 } 1326 1327 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){ 1328 1329 channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1330 1331 uint16_t flags = little_endian_read_16(command, 6); 1332 if (flags & 1) { 1333 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 1334 } 1335 1336 // accept the other's configuration options 1337 uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1338 uint16_t pos = 8; 1339 while (pos < end_pos){ 1340 uint8_t option_hint = command[pos] >> 7; 1341 uint8_t option_type = command[pos] & 0x7f; 1342 log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type); 1343 pos++; 1344 uint8_t length = command[pos++]; 1345 // MTU { type(8): 1, len(8):2, MTU(16) } 1346 if (option_type == 1 && length == 2){ 1347 channel->remote_mtu = little_endian_read_16(command, pos); 1348 // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu); 1349 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 1350 } 1351 // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)} 1352 if (option_type == 2 && length == 2){ 1353 channel->flush_timeout = little_endian_read_16(command, pos); 1354 } 1355 // check for unknown options 1356 if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){ 1357 log_info("l2cap cid %u, unknown options", channel->local_cid); 1358 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID); 1359 } 1360 pos += length; 1361 } 1362 } 1363 1364 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){ 1365 // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var); 1366 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0; 1367 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0; 1368 // addition check that fixes re-entrance issue causing l2cap event channel opened twice 1369 if (channel->state == L2CAP_STATE_OPEN) return 0; 1370 return 1; 1371 } 1372 1373 1374 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){ 1375 1376 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1377 uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1378 uint16_t result = 0; 1379 1380 log_info("L2CAP signaling handler code %u, state %u", code, channel->state); 1381 1382 // handle DISCONNECT REQUESTS seperately 1383 if (code == DISCONNECTION_REQUEST){ 1384 switch (channel->state){ 1385 case L2CAP_STATE_CONFIG: 1386 case L2CAP_STATE_OPEN: 1387 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 1388 case L2CAP_STATE_WAIT_DISCONNECT: 1389 l2cap_handle_disconnect_request(channel, identifier); 1390 break; 1391 1392 default: 1393 // ignore in other states 1394 break; 1395 } 1396 return; 1397 } 1398 1399 // @STATEMACHINE(l2cap) 1400 switch (channel->state) { 1401 1402 case L2CAP_STATE_WAIT_CONNECT_RSP: 1403 switch (code){ 1404 case CONNECTION_RESPONSE: 1405 l2cap_stop_rtx(channel); 1406 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1407 switch (result) { 1408 case 0: 1409 // successful connection 1410 channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1411 channel->state = L2CAP_STATE_CONFIG; 1412 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1413 break; 1414 case 1: 1415 // connection pending. get some coffee, but start the ERTX 1416 l2cap_start_ertx(channel); 1417 break; 1418 default: 1419 // channel closed 1420 channel->state = L2CAP_STATE_CLOSED; 1421 // map l2cap connection response result to BTstack status enumeration 1422 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result); 1423 1424 // drop link key if security block 1425 if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){ 1426 gap_drop_link_key_for_bd_addr(channel->address); 1427 } 1428 1429 // discard channel 1430 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 1431 btstack_memory_l2cap_channel_free(channel); 1432 break; 1433 } 1434 break; 1435 1436 default: 1437 //@TODO: implement other signaling packets 1438 break; 1439 } 1440 break; 1441 1442 case L2CAP_STATE_CONFIG: 1443 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1444 switch (code) { 1445 case CONFIGURE_REQUEST: 1446 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 1447 l2cap_signaling_handle_configure_request(channel, command); 1448 if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){ 1449 // only done if continuation not set 1450 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ); 1451 } 1452 break; 1453 case CONFIGURE_RESPONSE: 1454 l2cap_stop_rtx(channel); 1455 switch (result){ 1456 case 0: // success 1457 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP); 1458 break; 1459 case 4: // pending 1460 l2cap_start_ertx(channel); 1461 break; 1462 default: 1463 // retry on negative result 1464 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1465 break; 1466 } 1467 break; 1468 default: 1469 break; 1470 } 1471 if (l2cap_channel_ready_for_open(channel)){ 1472 // for open: 1473 channel->state = L2CAP_STATE_OPEN; 1474 l2cap_emit_channel_opened(channel, 0); 1475 } 1476 break; 1477 1478 case L2CAP_STATE_WAIT_DISCONNECT: 1479 switch (code) { 1480 case DISCONNECTION_RESPONSE: 1481 l2cap_finialize_channel_close(channel); 1482 break; 1483 default: 1484 //@TODO: implement other signaling packets 1485 break; 1486 } 1487 break; 1488 1489 case L2CAP_STATE_CLOSED: 1490 // @TODO handle incoming requests 1491 break; 1492 1493 case L2CAP_STATE_OPEN: 1494 //@TODO: implement other signaling packets, e.g. re-configure 1495 break; 1496 default: 1497 break; 1498 } 1499 // log_info("new state %u", channel->state); 1500 } 1501 1502 1503 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){ 1504 1505 // get code, signalind identifier and command len 1506 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1507 uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1508 1509 // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST 1510 if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){ 1511 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1512 return; 1513 } 1514 1515 // general commands without an assigned channel 1516 switch(code) { 1517 1518 case CONNECTION_REQUEST: { 1519 uint16_t psm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1520 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 1521 l2cap_handle_connection_request(handle, sig_id, psm, source_cid); 1522 return; 1523 } 1524 1525 case ECHO_REQUEST: 1526 l2cap_register_signaling_response(handle, code, sig_id, 0); 1527 return; 1528 1529 case INFORMATION_REQUEST: { 1530 uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1531 l2cap_register_signaling_response(handle, code, sig_id, infoType); 1532 return; 1533 } 1534 1535 default: 1536 break; 1537 } 1538 1539 1540 // Get potential destination CID 1541 uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1542 1543 // Find channel for this sig_id and connection handle 1544 btstack_linked_list_iterator_t it; 1545 btstack_linked_list_iterator_init(&it, &l2cap_channels); 1546 while (btstack_linked_list_iterator_has_next(&it)){ 1547 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1548 if (channel->con_handle != handle) continue; 1549 if (code & 1) { 1550 // match odd commands (responses) by previous signaling identifier 1551 if (channel->local_sig_id == sig_id) { 1552 l2cap_signaling_handler_channel(channel, command); 1553 break; 1554 } 1555 } else { 1556 // match even commands (requests) by local channel id 1557 if (channel->local_cid == dest_cid) { 1558 l2cap_signaling_handler_channel(channel, command); 1559 break; 1560 } 1561 } 1562 } 1563 } 1564 #endif 1565 1566 #ifdef ENABLE_BLE 1567 1568 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){ 1569 uint8_t event[6]; 1570 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE; 1571 event[1] = 4; 1572 little_endian_store_16(event, 2, con_handle); 1573 little_endian_store_16(event, 4, result); 1574 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1575 if (!l2cap_event_packet_handler) return; 1576 (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1577 } 1578 1579 // @returns valid 1580 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){ 1581 hci_connection_t * connection; 1582 uint16_t result; 1583 uint8_t event[10]; 1584 1585 #ifdef ENABLE_LE_DATA_CHANNELS 1586 btstack_linked_list_iterator_t it; 1587 l2cap_channel_t * channel; 1588 uint16_t local_cid; 1589 uint16_t le_psm; 1590 uint16_t new_credits; 1591 uint16_t credits_before; 1592 l2cap_service_t * service; 1593 #endif 1594 1595 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1596 log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id); 1597 1598 switch (code){ 1599 1600 case CONNECTION_PARAMETER_UPDATE_RESPONSE: 1601 result = little_endian_read_16(command, 4); 1602 l2cap_emit_connection_parameter_update_response(handle, result); 1603 break; 1604 1605 case CONNECTION_PARAMETER_UPDATE_REQUEST: 1606 connection = hci_connection_for_handle(handle); 1607 if (connection){ 1608 if (connection->role != HCI_ROLE_MASTER){ 1609 // reject command without notifying upper layer when not in master role 1610 return 0; 1611 } 1612 int update_parameter = 1; 1613 le_connection_parameter_range_t existing_range; 1614 gap_get_connection_parameter_range(&existing_range); 1615 uint16_t le_conn_interval_min = little_endian_read_16(command,8); 1616 uint16_t le_conn_interval_max = little_endian_read_16(command,10); 1617 uint16_t le_conn_latency = little_endian_read_16(command,12); 1618 uint16_t le_supervision_timeout = little_endian_read_16(command,14); 1619 1620 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0; 1621 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0; 1622 1623 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0; 1624 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0; 1625 1626 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0; 1627 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0; 1628 1629 if (update_parameter){ 1630 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE; 1631 connection->le_conn_interval_min = le_conn_interval_min; 1632 connection->le_conn_interval_max = le_conn_interval_max; 1633 connection->le_conn_latency = le_conn_latency; 1634 connection->le_supervision_timeout = le_supervision_timeout; 1635 } else { 1636 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY; 1637 } 1638 connection->le_con_param_update_identifier = sig_id; 1639 } 1640 1641 if (!l2cap_event_packet_handler) break; 1642 1643 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST; 1644 event[1] = 8; 1645 memcpy(&event[2], &command[4], 8); 1646 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1647 (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1648 break; 1649 1650 #ifdef ENABLE_LE_DATA_CHANNELS 1651 1652 case COMMAND_REJECT: 1653 // Find channel for this sig_id and connection handle 1654 channel = NULL; 1655 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1656 while (btstack_linked_list_iterator_has_next(&it)){ 1657 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1658 if (a_channel->con_handle != handle) continue; 1659 if (a_channel->local_sig_id != sig_id) continue; 1660 channel = a_channel; 1661 break; 1662 } 1663 if (!channel) break; 1664 1665 // if received while waiting for le connection response, assume legacy device 1666 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){ 1667 channel->state = L2CAP_STATE_CLOSED; 1668 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002 1669 l2cap_emit_le_channel_opened(channel, 0x0002); 1670 1671 // discard channel 1672 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1673 btstack_memory_l2cap_channel_free(channel); 1674 break; 1675 } 1676 break; 1677 1678 case LE_CREDIT_BASED_CONNECTION_REQUEST: 1679 1680 // get hci connection, bail if not found (must not happen) 1681 connection = hci_connection_for_handle(handle); 1682 if (!connection) return 0; 1683 1684 // check if service registered 1685 le_psm = little_endian_read_16(command, 4); 1686 service = l2cap_le_get_service(le_psm); 1687 1688 if (service){ 1689 1690 uint16_t source_cid = little_endian_read_16(command, 6); 1691 if (source_cid < 0x40){ 1692 // 0x0009 Connection refused - Invalid Source CID 1693 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0009); 1694 return 1; 1695 } 1696 1697 // go through list of channels for this ACL connection and check if we get a match 1698 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1699 while (btstack_linked_list_iterator_has_next(&it)){ 1700 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1701 if (a_channel->con_handle != handle) continue; 1702 if (a_channel->remote_cid != source_cid) continue; 1703 // 0x000a Connection refused - Source CID already allocated 1704 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x000a); 1705 return 1; 1706 } 1707 1708 // security: check encryption 1709 if (service->required_security_level >= LEVEL_2){ 1710 if (sm_encryption_key_size(handle) == 0){ 1711 // 0x0008 Connection refused - insufficient encryption 1712 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0008); 1713 return 1; 1714 } 1715 // anything less than 16 byte key size is insufficient 1716 if (sm_encryption_key_size(handle) < 16){ 1717 // 0x0007 Connection refused – insufficient encryption key size 1718 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0007); 1719 return 1; 1720 } 1721 } 1722 1723 // security: check authencation 1724 if (service->required_security_level >= LEVEL_3){ 1725 if (!sm_authenticated(handle)){ 1726 // 0x0005 Connection refused – insufficient authentication 1727 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0005); 1728 return 1; 1729 } 1730 } 1731 1732 // security: check authorization 1733 if (service->required_security_level >= LEVEL_4){ 1734 if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){ 1735 // 0x0006 Connection refused – insufficient authorization 1736 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0006); 1737 return 1; 1738 } 1739 } 1740 1741 // allocate channel 1742 channel = l2cap_create_channel_entry(service->packet_handler, connection->address, 1743 BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level); 1744 if (!channel){ 1745 // 0x0004 Connection refused – no resources available 1746 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0004); 1747 return 1; 1748 } 1749 1750 channel->con_handle = handle; 1751 channel->remote_cid = source_cid; 1752 channel->remote_sig_id = sig_id; 1753 channel->remote_mtu = little_endian_read_16(command, 8); 1754 channel->remote_mps = little_endian_read_16(command, 10); 1755 channel->credits_outgoing = little_endian_read_16(command, 12); 1756 1757 // set initial state 1758 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 1759 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING; 1760 1761 // add to connections list 1762 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1763 1764 // post connection request event 1765 l2cap_emit_le_incoming_connection(channel); 1766 1767 } else { 1768 // Connection refused – LE_PSM not supported 1769 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0002); 1770 } 1771 break; 1772 1773 case LE_CREDIT_BASED_CONNECTION_RESPONSE: 1774 // Find channel for this sig_id and connection handle 1775 channel = NULL; 1776 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 1777 while (btstack_linked_list_iterator_has_next(&it)){ 1778 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 1779 if (a_channel->con_handle != handle) continue; 1780 if (a_channel->local_sig_id != sig_id) continue; 1781 channel = a_channel; 1782 break; 1783 } 1784 if (!channel) break; 1785 1786 // cid + 0 1787 result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8); 1788 if (result){ 1789 channel->state = L2CAP_STATE_CLOSED; 1790 // map l2cap connection response result to BTstack status enumeration 1791 l2cap_emit_le_channel_opened(channel, result); 1792 1793 // discard channel 1794 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel); 1795 btstack_memory_l2cap_channel_free(channel); 1796 break; 1797 } 1798 1799 // success 1800 channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 1801 channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2); 1802 channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4); 1803 channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6); 1804 channel->state = L2CAP_STATE_OPEN; 1805 l2cap_emit_le_channel_opened(channel, result); 1806 break; 1807 1808 case LE_FLOW_CONTROL_CREDIT: 1809 // find channel 1810 local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 1811 channel = l2cap_le_get_channel_for_local_cid(local_cid); 1812 if (!channel) { 1813 log_error("l2cap: no channel for cid 0x%02x", local_cid); 1814 break; 1815 } 1816 new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2); 1817 credits_before = channel->credits_outgoing; 1818 channel->credits_outgoing += new_credits; 1819 // check for credit overrun 1820 if (credits_before > channel->credits_outgoing){ 1821 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid); 1822 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 1823 break; 1824 } 1825 log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing); 1826 break; 1827 1828 case DISCONNECTION_REQUEST: 1829 // find channel 1830 local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0); 1831 channel = l2cap_le_get_channel_for_local_cid(local_cid); 1832 if (!channel) { 1833 log_error("l2cap: no channel for cid 0x%02x", local_cid); 1834 break; 1835 } 1836 channel->remote_sig_id = sig_id; 1837 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 1838 break; 1839 1840 #endif 1841 1842 case DISCONNECTION_RESPONSE: 1843 break; 1844 1845 default: 1846 // command unknown -> reject command 1847 return 0; 1848 } 1849 return 1; 1850 } 1851 #endif 1852 1853 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){ 1854 UNUSED(packet_type); 1855 UNUSED(channel); 1856 1857 l2cap_channel_t * l2cap_channel; 1858 UNUSED(l2cap_channel); 1859 1860 // Get Channel ID 1861 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 1862 hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet); 1863 1864 switch (channel_id) { 1865 1866 #ifdef ENABLE_CLASSIC 1867 case L2CAP_CID_SIGNALING: { 1868 uint16_t command_offset = 8; 1869 while (command_offset < size) { 1870 // handle signaling commands 1871 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]); 1872 1873 // increment command_offset 1874 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1875 } 1876 break; 1877 } 1878 #endif 1879 1880 #ifdef ENABLE_BLE 1881 case L2CAP_CID_SIGNALING_LE: { 1882 uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1]; 1883 int valid = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id); 1884 if (!valid){ 1885 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1886 } 1887 break; 1888 } 1889 #endif 1890 1891 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1892 if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) { 1893 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1894 } 1895 break; 1896 1897 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1898 if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) { 1899 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1900 } 1901 break; 1902 1903 case L2CAP_CID_CONNECTIONLESS_CHANNEL: 1904 if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) { 1905 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1906 } 1907 break; 1908 1909 default: 1910 #ifdef ENABLE_CLASSIC 1911 // Find channel for this channel_id and connection handle 1912 l2cap_channel = l2cap_get_channel_for_local_cid(channel_id); 1913 if (l2cap_channel) { 1914 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1915 } 1916 #endif 1917 #ifdef ENABLE_LE_DATA_CHANNELS 1918 l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id); 1919 if (l2cap_channel) { 1920 // credit counting 1921 if (l2cap_channel->credits_incoming == 0){ 1922 log_error("LE Data Channel packet received but no incoming credits"); 1923 l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 1924 break; 1925 } 1926 l2cap_channel->credits_incoming--; 1927 1928 // automatic credits 1929 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){ 1930 l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT; 1931 } 1932 1933 // first fragment 1934 uint16_t pos = 0; 1935 if (!l2cap_channel->receive_sdu_len){ 1936 l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER); 1937 l2cap_channel->receive_sdu_pos = 0; 1938 pos += 2; 1939 size -= 2; 1940 } 1941 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER); 1942 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER; 1943 // done? 1944 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len); 1945 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){ 1946 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len); 1947 l2cap_channel->receive_sdu_len = 0; 1948 } 1949 } else { 1950 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id); 1951 } 1952 #endif 1953 break; 1954 } 1955 1956 l2cap_run(); 1957 } 1958 1959 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol 1960 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) { 1961 int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id); 1962 if (index < 0) return; 1963 fixed_channels[index].callback = the_packet_handler; 1964 } 1965 1966 #ifdef ENABLE_CLASSIC 1967 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 1968 void l2cap_finialize_channel_close(l2cap_channel_t * channel){ 1969 channel->state = L2CAP_STATE_CLOSED; 1970 l2cap_emit_channel_closed(channel); 1971 // discard channel 1972 l2cap_stop_rtx(channel); 1973 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel); 1974 btstack_memory_l2cap_channel_free(channel); 1975 } 1976 1977 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){ 1978 btstack_linked_list_iterator_t it; 1979 btstack_linked_list_iterator_init(&it, services); 1980 while (btstack_linked_list_iterator_has_next(&it)){ 1981 l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it); 1982 if ( service->psm == psm){ 1983 return service; 1984 }; 1985 } 1986 return NULL; 1987 } 1988 1989 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){ 1990 return l2cap_get_service_internal(&l2cap_services, psm); 1991 } 1992 1993 1994 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){ 1995 1996 log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu); 1997 1998 // check for alread registered psm 1999 l2cap_service_t *service = l2cap_get_service(psm); 2000 if (service) { 2001 log_error("l2cap_register_service: PSM %u already registered", psm); 2002 return L2CAP_SERVICE_ALREADY_REGISTERED; 2003 } 2004 2005 // alloc structure 2006 service = btstack_memory_l2cap_service_get(); 2007 if (!service) { 2008 log_error("l2cap_register_service: no memory for l2cap_service_t"); 2009 return BTSTACK_MEMORY_ALLOC_FAILED; 2010 } 2011 2012 // fill in 2013 service->psm = psm; 2014 service->mtu = mtu; 2015 service->packet_handler = service_packet_handler; 2016 service->required_security_level = security_level; 2017 2018 // add to services list 2019 btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service); 2020 2021 // enable page scan 2022 gap_connectable_control(1); 2023 2024 return 0; 2025 } 2026 2027 uint8_t l2cap_unregister_service(uint16_t psm){ 2028 2029 log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm); 2030 2031 l2cap_service_t *service = l2cap_get_service(psm); 2032 if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST; 2033 btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service); 2034 btstack_memory_l2cap_service_free(service); 2035 2036 // disable page scan when no services registered 2037 if (btstack_linked_list_empty(&l2cap_services)) { 2038 gap_connectable_control(0); 2039 } 2040 return 0; 2041 } 2042 #endif 2043 2044 2045 #ifdef ENABLE_LE_DATA_CHANNELS 2046 2047 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){ 2048 if (!channel->waiting_for_can_send_now) return; 2049 if (channel->send_sdu_buffer) return; 2050 channel->waiting_for_can_send_now = 0; 2051 log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid); 2052 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW); 2053 } 2054 2055 // 1BH2222 2056 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) { 2057 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", 2058 channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu); 2059 uint8_t event[19]; 2060 event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION; 2061 event[1] = sizeof(event) - 2; 2062 event[2] = channel->address_type; 2063 reverse_bd_addr(channel->address, &event[3]); 2064 little_endian_store_16(event, 9, channel->con_handle); 2065 little_endian_store_16(event, 11, channel->psm); 2066 little_endian_store_16(event, 13, channel->local_cid); 2067 little_endian_store_16(event, 15, channel->remote_cid); 2068 little_endian_store_16(event, 17, channel->remote_mtu); 2069 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2070 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 2071 } 2072 // 11BH22222 2073 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) { 2074 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", 2075 status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm, 2076 channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu); 2077 uint8_t event[23]; 2078 event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED; 2079 event[1] = sizeof(event) - 2; 2080 event[2] = status; 2081 event[3] = channel->address_type; 2082 reverse_bd_addr(channel->address, &event[4]); 2083 little_endian_store_16(event, 10, channel->con_handle); 2084 event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0; 2085 little_endian_store_16(event, 13, channel->psm); 2086 little_endian_store_16(event, 15, channel->local_cid); 2087 little_endian_store_16(event, 17, channel->remote_cid); 2088 little_endian_store_16(event, 19, channel->local_mtu); 2089 little_endian_store_16(event, 21, channel->remote_mtu); 2090 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2091 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event)); 2092 } 2093 2094 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){ 2095 btstack_linked_list_iterator_t it; 2096 btstack_linked_list_iterator_init(&it, &l2cap_le_channels); 2097 while (btstack_linked_list_iterator_has_next(&it)){ 2098 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it); 2099 if ( channel->local_cid == local_cid) { 2100 return channel; 2101 } 2102 } 2103 return NULL; 2104 } 2105 2106 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 2107 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){ 2108 channel->state = L2CAP_STATE_CLOSED; 2109 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED); 2110 // discard channel 2111 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel); 2112 btstack_memory_l2cap_channel_free(channel); 2113 } 2114 2115 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){ 2116 return l2cap_get_service_internal(&l2cap_le_services, le_psm); 2117 } 2118 2119 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){ 2120 2121 log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm); 2122 2123 // check for alread registered psm 2124 l2cap_service_t *service = l2cap_le_get_service(psm); 2125 if (service) { 2126 return L2CAP_SERVICE_ALREADY_REGISTERED; 2127 } 2128 2129 // alloc structure 2130 service = btstack_memory_l2cap_service_get(); 2131 if (!service) { 2132 log_error("l2cap_register_service_internal: no memory for l2cap_service_t"); 2133 return BTSTACK_MEMORY_ALLOC_FAILED; 2134 } 2135 2136 // fill in 2137 service->psm = psm; 2138 service->mtu = 0; 2139 service->packet_handler = packet_handler; 2140 service->required_security_level = security_level; 2141 2142 // add to services list 2143 btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service); 2144 2145 // done 2146 return 0; 2147 } 2148 2149 uint8_t l2cap_le_unregister_service(uint16_t psm) { 2150 log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm); 2151 l2cap_service_t *service = l2cap_le_get_service(psm); 2152 if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST; 2153 2154 btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service); 2155 btstack_memory_l2cap_service_free(service); 2156 return 0; 2157 } 2158 2159 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){ 2160 // get channel 2161 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2162 if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2163 2164 // validate state 2165 if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){ 2166 return ERROR_CODE_COMMAND_DISALLOWED; 2167 } 2168 2169 // set state accept connection 2170 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT; 2171 channel->receive_sdu_buffer = receive_sdu_buffer; 2172 channel->local_mtu = mtu; 2173 channel->new_credits_incoming = initial_credits; 2174 channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS; 2175 2176 // test 2177 // channel->new_credits_incoming = 1; 2178 2179 // go 2180 l2cap_run(); 2181 return 0; 2182 } 2183 2184 /** 2185 * @brief Deny incoming LE Data Channel connection due to resource constraints 2186 * @param local_cid L2CAP LE Data Channel Identifier 2187 */ 2188 2189 uint8_t l2cap_le_decline_connection(uint16_t local_cid){ 2190 // get channel 2191 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2192 if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2193 2194 // validate state 2195 if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){ 2196 return ERROR_CODE_COMMAND_DISALLOWED; 2197 } 2198 2199 // set state decline connection 2200 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE; 2201 channel->reason = 0x04; // no resources available 2202 l2cap_run(); 2203 return 0; 2204 } 2205 2206 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle, 2207 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level, 2208 uint16_t * out_local_cid) { 2209 2210 log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu); 2211 2212 2213 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2214 if (!connection) { 2215 log_error("no hci_connection for handle 0x%04x", con_handle); 2216 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 2217 } 2218 2219 l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level); 2220 if (!channel) { 2221 return BTSTACK_MEMORY_ALLOC_FAILED; 2222 } 2223 log_info("l2cap_le_create_channel %p", channel); 2224 2225 // store local_cid 2226 if (out_local_cid){ 2227 *out_local_cid = channel->local_cid; 2228 } 2229 2230 // provide buffer 2231 channel->con_handle = con_handle; 2232 channel->receive_sdu_buffer = receive_sdu_buffer; 2233 channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST; 2234 channel->new_credits_incoming = initial_credits; 2235 channel->automatic_credits = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS; 2236 2237 // add to connections list 2238 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel); 2239 2240 // go 2241 l2cap_run(); 2242 return 0; 2243 } 2244 2245 /** 2246 * @brief Provide credtis for LE Data Channel 2247 * @param local_cid L2CAP LE Data Channel Identifier 2248 * @param credits Number additional credits for peer 2249 */ 2250 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){ 2251 2252 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2253 if (!channel) { 2254 log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid); 2255 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2256 } 2257 2258 // check state 2259 if (channel->state != L2CAP_STATE_OPEN){ 2260 log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid); 2261 } 2262 2263 // assert incoming credits + credits <= 0xffff 2264 uint32_t total_credits = channel->credits_incoming; 2265 total_credits += channel->new_credits_incoming; 2266 total_credits += credits; 2267 if (total_credits > 0xffff){ 2268 log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming, 2269 channel->new_credits_incoming, credits); 2270 } 2271 2272 // set credits_granted 2273 channel->new_credits_incoming += credits; 2274 2275 // go 2276 l2cap_run(); 2277 return 0; 2278 } 2279 2280 /** 2281 * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module 2282 * @param local_cid L2CAP LE Data Channel Identifier 2283 */ 2284 int l2cap_le_can_send_now(uint16_t local_cid){ 2285 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2286 if (!channel) { 2287 log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid); 2288 return 0; 2289 } 2290 2291 // check state 2292 if (channel->state != L2CAP_STATE_OPEN) return 0; 2293 2294 // check queue 2295 if (channel->send_sdu_buffer) return 0; 2296 2297 // fine, go ahead 2298 return 1; 2299 } 2300 2301 /** 2302 * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible 2303 * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function 2304 * so packet handler should be ready to handle it 2305 * @param local_cid L2CAP LE Data Channel Identifier 2306 */ 2307 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){ 2308 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2309 if (!channel) { 2310 log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid); 2311 return 0; 2312 } 2313 channel->waiting_for_can_send_now = 1; 2314 l2cap_le_notify_channel_can_send(channel); 2315 return 0; 2316 } 2317 2318 /** 2319 * @brief Send data via LE Data Channel 2320 * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event 2321 * @param local_cid L2CAP LE Data Channel Identifier 2322 * @param data data to send 2323 * @param size data size 2324 */ 2325 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){ 2326 2327 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2328 if (!channel) { 2329 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 2330 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2331 } 2332 2333 if (len > channel->remote_mtu){ 2334 log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid); 2335 return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU; 2336 } 2337 2338 if (channel->send_sdu_buffer){ 2339 log_info("l2cap_send cid 0x%02x, cannot send", local_cid); 2340 return BTSTACK_ACL_BUFFERS_FULL; 2341 } 2342 2343 channel->send_sdu_buffer = data; 2344 channel->send_sdu_len = len; 2345 channel->send_sdu_pos = 0; 2346 2347 l2cap_run(); 2348 return 0; 2349 } 2350 2351 /** 2352 * @brief Disconnect from LE Data Channel 2353 * @param local_cid L2CAP LE Data Channel Identifier 2354 */ 2355 uint8_t l2cap_le_disconnect(uint16_t local_cid) 2356 { 2357 l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid); 2358 if (!channel) { 2359 log_error("l2cap_send no channel for cid 0x%02x", local_cid); 2360 return L2CAP_LOCAL_CID_DOES_NOT_EXIST; 2361 } 2362 2363 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 2364 l2cap_run(); 2365 return 0; 2366 } 2367 2368 #endif 2369