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