1 /* 2 * Copyright (C) 2009-2012 by Matthias Ringwald 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 MATTHIAS RINGWALD 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 [email protected] 34 * 35 */ 36 37 /* 38 * l2cap.c 39 * 40 * Logical Link Control and Adaption Protocl (L2CAP) 41 * 42 * Created by Matthias Ringwald on 5/16/09. 43 */ 44 45 #include "l2cap.h" 46 #include "hci.h" 47 #include "hci_dump.h" 48 #include "debug.h" 49 #include "btstack_memory.h" 50 51 #include <stdarg.h> 52 #include <string.h> 53 54 #include <stdio.h> 55 56 // nr of buffered acl packets in outgoing queue to get max performance 57 #define NR_BUFFERED_ACL_PACKETS 3 58 59 // used to cache l2cap rejects, echo, and informational requests 60 #define NR_PENDING_SIGNALING_RESPONSES 3 61 62 // offsets for L2CAP SIGNALING COMMANDS 63 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET 0 64 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET 1 65 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2 66 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET 4 67 68 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size); 69 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size); 70 71 // used to cache l2cap rejects, echo, and informational requests 72 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES]; 73 static int signaling_responses_pending; 74 75 static linked_list_t l2cap_channels; 76 static linked_list_t l2cap_services; 77 static void (*packet_handler) (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler; 78 static int new_credits_blocked = 0; 79 80 static btstack_packet_handler_t attribute_protocol_packet_handler; 81 static btstack_packet_handler_t security_protocol_packet_handler; 82 static uint8_t require_security_level2_for_outgoing_sdp; 83 84 // prototypes 85 static void l2cap_finialize_channel_close(l2cap_channel_t *channel); 86 static l2cap_service_t * l2cap_get_service(uint16_t psm); 87 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status); 88 static void l2cap_emit_channel_closed(l2cap_channel_t *channel); 89 static void l2cap_emit_connection_request(l2cap_channel_t *channel); 90 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel); 91 92 93 void l2cap_init(){ 94 new_credits_blocked = 0; 95 signaling_responses_pending = 0; 96 97 l2cap_channels = NULL; 98 l2cap_services = NULL; 99 100 packet_handler = null_packet_handler; 101 attribute_protocol_packet_handler = NULL; 102 security_protocol_packet_handler = NULL; 103 104 require_security_level2_for_outgoing_sdp = 0; 105 106 // 107 // register callback with HCI 108 // 109 hci_register_packet_handler(&l2cap_packet_handler); 110 hci_connectable_control(0); // no services yet 111 } 112 113 114 /** Register L2CAP packet handlers */ 115 static void null_packet_handler(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){ 116 } 117 void l2cap_register_packet_handler(void (*handler)(void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){ 118 packet_handler = handler; 119 } 120 121 // notify client/protocol handler 122 void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){ 123 if (channel->packet_handler) { 124 (* (channel->packet_handler))(type, channel->local_cid, data, size); 125 } else { 126 (*packet_handler)(channel->connection, type, channel->local_cid, data, size); 127 } 128 } 129 130 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) { 131 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", 132 status, bd_addr_to_str(channel->address), channel->handle, channel->psm, 133 channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout); 134 uint8_t event[23]; 135 event[0] = L2CAP_EVENT_CHANNEL_OPENED; 136 event[1] = sizeof(event) - 2; 137 event[2] = status; 138 bt_flip_addr(&event[3], channel->address); 139 bt_store_16(event, 9, channel->handle); 140 bt_store_16(event, 11, channel->psm); 141 bt_store_16(event, 13, channel->local_cid); 142 bt_store_16(event, 15, channel->remote_cid); 143 bt_store_16(event, 17, channel->local_mtu); 144 bt_store_16(event, 19, channel->remote_mtu); 145 bt_store_16(event, 21, channel->flush_timeout); 146 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 147 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 148 } 149 150 void l2cap_emit_channel_closed(l2cap_channel_t *channel) { 151 log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid); 152 uint8_t event[4]; 153 event[0] = L2CAP_EVENT_CHANNEL_CLOSED; 154 event[1] = sizeof(event) - 2; 155 bt_store_16(event, 2, channel->local_cid); 156 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 157 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 158 } 159 160 void l2cap_emit_connection_request(l2cap_channel_t *channel) { 161 log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x", 162 bd_addr_to_str(channel->address), channel->handle, channel->psm, channel->local_cid, channel->remote_cid); 163 uint8_t event[16]; 164 event[0] = L2CAP_EVENT_INCOMING_CONNECTION; 165 event[1] = sizeof(event) - 2; 166 bt_flip_addr(&event[2], channel->address); 167 bt_store_16(event, 8, channel->handle); 168 bt_store_16(event, 10, channel->psm); 169 bt_store_16(event, 12, channel->local_cid); 170 bt_store_16(event, 14, channel->remote_cid); 171 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 172 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 173 } 174 175 void l2cap_emit_connection_parameter_update_response(uint16_t handle, uint16_t result){ 176 uint8_t event[6]; 177 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE; 178 event[1] = 4; 179 bt_store_16(event, 2, handle); 180 bt_store_16(event, 4, result); 181 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 182 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, event, sizeof(event)); 183 } 184 185 static void l2cap_emit_service_registered(void *connection, uint8_t status, uint16_t psm){ 186 log_info("L2CAP_EVENT_SERVICE_REGISTERED status 0x%x psm 0x%x", status, psm); 187 uint8_t event[5]; 188 event[0] = L2CAP_EVENT_SERVICE_REGISTERED; 189 event[1] = sizeof(event) - 2; 190 event[2] = status; 191 bt_store_16(event, 3, psm); 192 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 193 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, event, sizeof(event)); 194 } 195 196 void l2cap_emit_credits(l2cap_channel_t *channel, uint8_t credits) { 197 198 log_info("L2CAP_EVENT_CREDITS local_cid 0x%x credits %u", channel->local_cid, credits); 199 // track credits 200 channel->packets_granted += credits; 201 202 uint8_t event[5]; 203 event[0] = L2CAP_EVENT_CREDITS; 204 event[1] = sizeof(event) - 2; 205 bt_store_16(event, 2, channel->local_cid); 206 event[4] = credits; 207 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 208 l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event)); 209 } 210 211 void l2cap_block_new_credits(uint8_t blocked){ 212 new_credits_blocked = blocked; 213 } 214 215 void l2cap_hand_out_credits(void){ 216 217 if (new_credits_blocked) return; // we're told not to. used by daemon 218 219 linked_list_iterator_t it; 220 linked_list_iterator_init(&it, &l2cap_channels); 221 while (linked_list_iterator_has_next(&it)){ 222 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 223 if (!hci_number_free_acl_slots_for_handle(channel->handle)) return; 224 if (channel->state != L2CAP_STATE_OPEN) continue; 225 if (hci_number_outgoing_packets(channel->handle) < NR_BUFFERED_ACL_PACKETS && channel->packets_granted == 0) { 226 l2cap_emit_credits(channel, 1); 227 } 228 } 229 } 230 231 l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){ 232 linked_list_iterator_t it; 233 linked_list_iterator_init(&it, &l2cap_channels); 234 while (linked_list_iterator_has_next(&it)){ 235 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 236 if ( channel->local_cid == local_cid) { 237 return channel; 238 } 239 } 240 return NULL; 241 } 242 243 int l2cap_can_send_packet_now(uint16_t local_cid){ 244 l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid); 245 if (!channel) return 0; 246 if (!channel->packets_granted) return 0; 247 return hci_can_send_acl_packet_now(channel->handle); 248 } 249 250 // @deprecated 251 int l2cap_can_send_connectionless_packet_now(void){ 252 // TODO provide real handle 253 return l2cap_can_send_fixed_channel_packet_now(0x1234); 254 } 255 256 int l2cap_can_send_fixed_channel_packet_now(uint16_t handle){ 257 return hci_can_send_acl_packet_now(handle); 258 } 259 260 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){ 261 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 262 if (channel) { 263 return channel->remote_mtu; 264 } 265 return 0; 266 } 267 268 static l2cap_channel_t * l2cap_channel_for_rtx_timer(timer_source_t * ts){ 269 linked_list_iterator_t it; 270 linked_list_iterator_init(&it, &l2cap_channels); 271 while (linked_list_iterator_has_next(&it)){ 272 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 273 if ( &channel->rtx == ts) { 274 return channel; 275 } 276 } 277 return NULL; 278 } 279 280 static void l2cap_rtx_timeout(timer_source_t * ts){ 281 l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts); 282 if (!ts) return; 283 284 log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid); 285 286 // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq 287 // and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state." 288 // notify client 289 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT); 290 291 // discard channel 292 // no need to stop timer here, it is removed from list during timer callback 293 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 294 btstack_memory_l2cap_channel_free(channel); 295 } 296 297 static void l2cap_stop_rtx(l2cap_channel_t * channel){ 298 log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid); 299 run_loop_remove_timer(&channel->rtx); 300 } 301 302 static void l2cap_start_rtx(l2cap_channel_t * channel){ 303 log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid); 304 l2cap_stop_rtx(channel); 305 run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout); 306 run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS); 307 run_loop_add_timer(&channel->rtx); 308 } 309 310 static void l2cap_start_ertx(l2cap_channel_t * channel){ 311 log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid); 312 l2cap_stop_rtx(channel); 313 run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout); 314 run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS); 315 run_loop_add_timer(&channel->rtx); 316 } 317 318 void l2cap_require_security_level_2_for_outgoing_sdp(){ 319 require_security_level2_for_outgoing_sdp = 1; 320 } 321 322 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){ 323 return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp); 324 } 325 326 int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){ 327 328 if (!hci_can_send_acl_packet_now(handle)){ 329 log_info("l2cap_send_signaling_packet, cannot send"); 330 return BTSTACK_ACL_BUFFERS_FULL; 331 } 332 333 // log_info("l2cap_send_signaling_packet type %u", cmd); 334 hci_reserve_packet_buffer(); 335 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 336 va_list argptr; 337 va_start(argptr, identifier); 338 uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr); 339 va_end(argptr); 340 // log_info("l2cap_send_signaling_packet con %u!", handle); 341 return hci_send_acl_packet_buffer(len); 342 } 343 344 #ifdef HAVE_BLE 345 int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){ 346 347 if (!hci_can_send_acl_packet_now(handle)){ 348 log_info("l2cap_send_signaling_packet, cannot send"); 349 return BTSTACK_ACL_BUFFERS_FULL; 350 } 351 352 // log_info("l2cap_send_signaling_packet type %u", cmd); 353 hci_reserve_packet_buffer(); 354 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 355 va_list argptr; 356 va_start(argptr, identifier); 357 uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr); 358 va_end(argptr); 359 // log_info("l2cap_send_signaling_packet con %u!", handle); 360 return hci_send_acl_packet_buffer(len); 361 } 362 #endif 363 364 uint8_t *l2cap_get_outgoing_buffer(void){ 365 return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes 366 } 367 368 int l2cap_reserve_packet_buffer(void){ 369 return hci_reserve_packet_buffer(); 370 } 371 372 void l2cap_release_packet_buffer(void){ 373 hci_release_packet_buffer(); 374 } 375 376 377 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){ 378 379 if (!hci_is_packet_buffer_reserved()){ 380 log_error("l2cap_send_prepared called without reserving packet first"); 381 return BTSTACK_ACL_BUFFERS_FULL; 382 } 383 384 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 385 if (!channel) { 386 log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid); 387 return -1; // TODO: define error 388 } 389 390 if (channel->packets_granted == 0){ 391 log_error("l2cap_send_prepared cid 0x%02x, no credits!", local_cid); 392 return -1; // TODO: define error 393 } 394 395 if (!hci_can_send_prepared_acl_packet_now(channel->handle)){ 396 log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid); 397 return BTSTACK_ACL_BUFFERS_FULL; 398 } 399 400 --channel->packets_granted; 401 402 log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used, credits left %u;", 403 local_cid, channel->handle, channel->packets_granted); 404 405 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 406 407 int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02; 408 409 // 0 - Connection handle : PB=pb : BC=00 410 bt_store_16(acl_buffer, 0, channel->handle | (pb << 12) | (0 << 14)); 411 // 2 - ACL length 412 bt_store_16(acl_buffer, 2, len + 4); 413 // 4 - L2CAP packet length 414 bt_store_16(acl_buffer, 4, len + 0); 415 // 6 - L2CAP channel DEST 416 bt_store_16(acl_buffer, 6, channel->remote_cid); 417 // send 418 int err = hci_send_acl_packet_buffer(len+8); 419 420 l2cap_hand_out_credits(); 421 422 return err; 423 } 424 425 int l2cap_send_prepared_connectionless(uint16_t handle, uint16_t cid, uint16_t len){ 426 427 if (!hci_is_packet_buffer_reserved()){ 428 log_error("l2cap_send_prepared_connectionless called without reserving packet first"); 429 return BTSTACK_ACL_BUFFERS_FULL; 430 } 431 432 if (!hci_can_send_prepared_acl_packet_now(handle)){ 433 log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", handle, cid); 434 return BTSTACK_ACL_BUFFERS_FULL; 435 } 436 437 log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", handle, cid); 438 439 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 440 441 int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02; 442 443 // 0 - Connection handle : PB=pb : BC=00 444 bt_store_16(acl_buffer, 0, handle | (pb << 12) | (0 << 14)); 445 // 2 - ACL length 446 bt_store_16(acl_buffer, 2, len + 4); 447 // 4 - L2CAP packet length 448 bt_store_16(acl_buffer, 4, len + 0); 449 // 6 - L2CAP channel DEST 450 bt_store_16(acl_buffer, 6, cid); 451 // send 452 int err = hci_send_acl_packet_buffer(len+8); 453 454 l2cap_hand_out_credits(); 455 456 return err; 457 } 458 459 int l2cap_send_internal(uint16_t local_cid, uint8_t *data, uint16_t len){ 460 461 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 462 if (!channel) { 463 log_error("l2cap_send_internal no channel for cid 0x%02x", local_cid); 464 return -1; // TODO: define error 465 } 466 467 if (!hci_can_send_acl_packet_now(channel->handle)){ 468 log_info("l2cap_send_internal cid 0x%02x, cannot send", local_cid); 469 return BTSTACK_ACL_BUFFERS_FULL; 470 } 471 472 hci_reserve_packet_buffer(); 473 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 474 475 memcpy(&acl_buffer[8], data, len); 476 477 return l2cap_send_prepared(local_cid, len); 478 } 479 480 int l2cap_send_connectionless(uint16_t handle, uint16_t cid, uint8_t *data, uint16_t len){ 481 482 if (!hci_can_send_acl_packet_now(handle)){ 483 log_info("l2cap_send_internal cid 0x%02x, cannot send", cid); 484 return BTSTACK_ACL_BUFFERS_FULL; 485 } 486 487 hci_reserve_packet_buffer(); 488 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 489 490 memcpy(&acl_buffer[8], data, len); 491 492 return l2cap_send_prepared_connectionless(handle, cid, len); 493 } 494 495 int l2cap_send_echo_request(uint16_t handle, uint8_t *data, uint16_t len){ 496 return l2cap_send_signaling_packet(handle, ECHO_REQUEST, 0x77, len, data); 497 } 498 499 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 500 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag); 501 } 502 503 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){ 504 channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag); 505 } 506 507 508 509 // MARK: L2CAP_RUN 510 // process outstanding signaling tasks 511 void l2cap_run(void){ 512 513 // check pending signaling responses 514 while (signaling_responses_pending){ 515 516 hci_con_handle_t handle = signaling_responses[0].handle; 517 518 if (!hci_can_send_acl_packet_now(handle)) break; 519 520 uint8_t sig_id = signaling_responses[0].sig_id; 521 uint16_t infoType = signaling_responses[0].data; // INFORMATION_REQUEST 522 uint16_t result = signaling_responses[0].data; // CONNECTION_REQUEST, COMMAND_REJECT 523 524 switch (signaling_responses[0].code){ 525 case CONNECTION_REQUEST: 526 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0); 527 // also disconnect if result is 0x0003 - security blocked 528 hci_disconnect_security_block(handle); 529 break; 530 case ECHO_REQUEST: 531 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL); 532 break; 533 case INFORMATION_REQUEST: 534 switch (infoType){ 535 case 1: { // Connectionless MTU 536 uint16_t connectionless_mtu = hci_max_acl_data_packet_length(); 537 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu); 538 break; 539 } 540 case 2: { // Extended Features Supported 541 // extended features request supported, only supporing fixed channel map 542 uint32_t features = 0x80; 543 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features); 544 break; 545 } 546 case 3: { // Fixed Channels Supported 547 uint8_t map[8]; 548 memset(map, 0, 8); 549 map[0] = 0x01; // L2CAP Signaling Channel 550 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map); 551 break; 552 } 553 default: 554 // all other types are not supported 555 l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL); 556 break; 557 } 558 break; 559 case COMMAND_REJECT: 560 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL); 561 #ifdef HAVE_BLE 562 case COMMAND_REJECT_LE: 563 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL); 564 break; 565 #endif 566 default: 567 // should not happen 568 break; 569 } 570 571 // remove first item 572 signaling_responses_pending--; 573 int i; 574 for (i=0; i < signaling_responses_pending; i++){ 575 memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t)); 576 } 577 } 578 579 uint8_t config_options[4]; 580 linked_list_iterator_t it; 581 linked_list_iterator_init(&it, &l2cap_channels); 582 while (linked_list_iterator_has_next(&it)){ 583 584 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 585 // log_info("l2cap_run: state %u, var 0x%02x", channel->state, channel->state_var); 586 switch (channel->state){ 587 588 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 589 case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT: 590 if (!hci_can_send_acl_packet_now(channel->handle)) break; 591 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) { 592 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND); 593 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0); 594 } 595 break; 596 597 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 598 if (!hci_can_send_command_packet_now()) break; 599 // send connection request - set state first 600 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE; 601 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch 602 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 603 break; 604 605 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE: 606 if (!hci_can_send_acl_packet_now(channel->handle)) break; 607 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0); 608 // discard channel - l2cap_finialize_channel_close without sending l2cap close event 609 l2cap_stop_rtx(channel); 610 linked_list_iterator_remove(&it); 611 btstack_memory_l2cap_channel_free(channel); 612 break; 613 614 case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT: 615 if (!hci_can_send_acl_packet_now(channel->handle)) break; 616 channel->state = L2CAP_STATE_CONFIG; 617 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 618 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0); 619 break; 620 621 case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST: 622 if (!hci_can_send_acl_packet_now(channel->handle)) break; 623 // success, start l2cap handshake 624 channel->local_sig_id = l2cap_next_sig_id(); 625 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP; 626 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid); 627 l2cap_start_rtx(channel); 628 break; 629 630 case L2CAP_STATE_CONFIG: 631 if (!hci_can_send_acl_packet_now(channel->handle)) break; 632 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){ 633 uint16_t flags = 0; 634 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 635 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) { 636 flags = 1; 637 } else { 638 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP); 639 } 640 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){ 641 l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL); 642 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){ 643 config_options[0] = 1; // MTU 644 config_options[1] = 2; // len param 645 bt_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu); 646 l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options); 647 channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 648 } else { 649 l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL); 650 } 651 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 652 } 653 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){ 654 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 655 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ); 656 channel->local_sig_id = l2cap_next_sig_id(); 657 config_options[0] = 1; // MTU 658 config_options[1] = 2; // len param 659 bt_store_16( (uint8_t*)&config_options, 2, channel->local_mtu); 660 l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options); 661 l2cap_start_rtx(channel); 662 } 663 if (l2cap_channel_ready_for_open(channel)){ 664 channel->state = L2CAP_STATE_OPEN; 665 l2cap_emit_channel_opened(channel, 0); // success 666 l2cap_emit_credits(channel, 1); 667 } 668 break; 669 670 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE: 671 if (!hci_can_send_acl_packet_now(channel->handle)) break; 672 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid); 673 // 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 :) 674 l2cap_finialize_channel_close(channel); // -- remove from list 675 break; 676 677 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 678 if (!hci_can_send_acl_packet_now(channel->handle)) break; 679 channel->local_sig_id = l2cap_next_sig_id(); 680 channel->state = L2CAP_STATE_WAIT_DISCONNECT; 681 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid); 682 break; 683 default: 684 break; 685 } 686 } 687 } 688 689 uint16_t l2cap_max_mtu(void){ 690 int classic_acl_length = hci_max_acl_data_packet_length(); 691 if (classic_acl_length == 0) return 0; 692 return classic_acl_length - L2CAP_HEADER_SIZE; 693 } 694 695 uint16_t l2cap_max_le_mtu(){ 696 int le_acl_length = hci_max_acl_le_data_packet_length(); 697 if (le_acl_length == 0) return 0; 698 return le_acl_length - L2CAP_HEADER_SIZE; 699 } 700 701 static void l2cap_handle_connection_complete(uint16_t handle, l2cap_channel_t * channel){ 702 if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) { 703 log_info("l2cap_handle_connection_complete expected state"); 704 // success, start l2cap handshake 705 channel->handle = handle; 706 channel->local_cid = l2cap_next_local_cid(); 707 // check remote SSP feature first 708 channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES; 709 } 710 } 711 712 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){ 713 if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return; 714 715 // we have been waiting for remote supported features, if both support SSP, 716 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)); 717 if (hci_ssp_supported_on_both_sides(channel->handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){ 718 // request security level 2 719 channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE; 720 gap_request_security_level(channel->handle, LEVEL_2); 721 return; 722 } 723 // fine, go ahead 724 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 725 } 726 727 // open outgoing L2CAP channel 728 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler, 729 bd_addr_t address, uint16_t psm, uint16_t mtu){ 730 731 log_info("L2CAP_CREATE_CHANNEL_MTU addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, mtu); 732 733 // alloc structure 734 l2cap_channel_t * chan = btstack_memory_l2cap_channel_get(); 735 if (!chan) { 736 // emit error event 737 l2cap_channel_t dummy_channel; 738 BD_ADDR_COPY(dummy_channel.address, address); 739 dummy_channel.psm = psm; 740 l2cap_emit_channel_opened(&dummy_channel, BTSTACK_MEMORY_ALLOC_FAILED); 741 return; 742 } 743 // limit local mtu to max acl packet length 744 if (mtu > l2cap_max_mtu()) { 745 mtu = l2cap_max_mtu(); 746 } 747 748 // fill in 749 BD_ADDR_COPY(chan->address, address); 750 chan->psm = psm; 751 chan->handle = 0; 752 chan->connection = connection; 753 chan->packet_handler = packet_handler; 754 chan->remote_mtu = L2CAP_MINIMAL_MTU; 755 chan->local_mtu = mtu; 756 chan->packets_granted = 0; 757 758 // set initial state 759 chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION; 760 chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE; 761 chan->remote_sig_id = L2CAP_SIG_ID_INVALID; 762 chan->local_sig_id = L2CAP_SIG_ID_INVALID; 763 chan->required_security_level = LEVEL_0; 764 765 // add to connections list 766 linked_list_add(&l2cap_channels, (linked_item_t *) chan); 767 768 // check if hci connection is already usable 769 hci_connection_t * conn = hci_connection_for_bd_addr_and_type((bd_addr_t*)address, BD_ADDR_TYPE_CLASSIC); 770 if (conn){ 771 log_info("l2cap_create_channel_internal, hci connection already exists"); 772 l2cap_handle_connection_complete(conn->con_handle, chan); 773 // check ir remote supported fearures are already received 774 if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) { 775 l2cap_handle_remote_supported_features_received(chan); 776 } 777 } 778 779 l2cap_run(); 780 } 781 782 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){ 783 log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason); 784 // find channel for local_cid 785 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 786 if (channel) { 787 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 788 } 789 // process 790 l2cap_run(); 791 } 792 793 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){ 794 linked_list_iterator_t it; 795 linked_list_iterator_init(&it, &l2cap_channels); 796 while (linked_list_iterator_has_next(&it)){ 797 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 798 if ( BD_ADDR_CMP( channel->address, address) != 0) continue; 799 // channel for this address found 800 switch (channel->state){ 801 case L2CAP_STATE_WAIT_CONNECTION_COMPLETE: 802 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 803 // failure, forward error code 804 l2cap_emit_channel_opened(channel, status); 805 // discard channel 806 l2cap_stop_rtx(channel); 807 linked_list_iterator_remove(&it); 808 btstack_memory_l2cap_channel_free(channel); 809 break; 810 default: 811 break; 812 } 813 } 814 } 815 816 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){ 817 linked_list_iterator_t it; 818 linked_list_iterator_init(&it, &l2cap_channels); 819 while (linked_list_iterator_has_next(&it)){ 820 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 821 if ( ! BD_ADDR_CMP( channel->address, address) ){ 822 l2cap_handle_connection_complete(handle, channel); 823 } 824 } 825 // process 826 l2cap_run(); 827 } 828 829 void l2cap_event_handler(uint8_t *packet, uint16_t size){ 830 831 bd_addr_t address; 832 hci_con_handle_t handle; 833 linked_list_iterator_t it; 834 int hci_con_used; 835 836 switch(packet[0]){ 837 838 // handle connection complete events 839 case HCI_EVENT_CONNECTION_COMPLETE: 840 bt_flip_addr(address, &packet[5]); 841 if (packet[2] == 0){ 842 handle = READ_BT_16(packet, 3); 843 l2cap_handle_connection_success_for_addr(address, handle); 844 } else { 845 l2cap_handle_connection_failed_for_addr(address, packet[2]); 846 } 847 break; 848 849 // handle successful create connection cancel command 850 case HCI_EVENT_COMMAND_COMPLETE: 851 if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) { 852 if (packet[5] == 0){ 853 bt_flip_addr(address, &packet[6]); 854 // CONNECTION TERMINATED BY LOCAL HOST (0X16) 855 l2cap_handle_connection_failed_for_addr(address, 0x16); 856 } 857 } 858 l2cap_run(); // try sending signaling packets first 859 break; 860 861 case HCI_EVENT_COMMAND_STATUS: 862 l2cap_run(); // try sending signaling packets first 863 break; 864 865 // handle disconnection complete events 866 case HCI_EVENT_DISCONNECTION_COMPLETE: 867 // send l2cap disconnect events for all channels on this handle and free them 868 handle = READ_BT_16(packet, 3); 869 linked_list_iterator_init(&it, &l2cap_channels); 870 while (linked_list_iterator_has_next(&it)){ 871 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 872 if (channel->handle != handle) continue; 873 l2cap_emit_channel_closed(channel); 874 l2cap_stop_rtx(channel); 875 linked_list_iterator_remove(&it); 876 btstack_memory_l2cap_channel_free(channel); 877 } 878 break; 879 880 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 881 l2cap_run(); // try sending signaling packets first 882 l2cap_hand_out_credits(); 883 break; 884 885 // HCI Connection Timeouts 886 case L2CAP_EVENT_TIMEOUT_CHECK: 887 handle = READ_BT_16(packet, 2); 888 if (hci_authentication_active_for_handle(handle)) break; 889 hci_con_used = 0; 890 linked_list_iterator_init(&it, &l2cap_channels); 891 while (linked_list_iterator_has_next(&it)){ 892 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 893 if (channel->handle != handle) continue; 894 hci_con_used = 1; 895 break; 896 } 897 if (hci_con_used) break; 898 if (!hci_can_send_command_packet_now()) break; 899 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection 900 break; 901 902 case DAEMON_EVENT_HCI_PACKET_SENT: 903 linked_list_iterator_init(&it, &l2cap_channels); 904 while (linked_list_iterator_has_next(&it)){ 905 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 906 if (!channel->packet_handler) continue; 907 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size); 908 } 909 if (attribute_protocol_packet_handler) { 910 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 911 } 912 if (security_protocol_packet_handler) { 913 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 914 } 915 break; 916 917 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 918 handle = READ_BT_16(packet, 3); 919 linked_list_iterator_init(&it, &l2cap_channels); 920 while (linked_list_iterator_has_next(&it)){ 921 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 922 if (channel->handle != handle) continue; 923 l2cap_handle_remote_supported_features_received(channel); 924 break; 925 } 926 break; 927 928 case GAP_SECURITY_LEVEL: 929 handle = READ_BT_16(packet, 2); 930 log_info("l2cap - security level update"); 931 linked_list_iterator_init(&it, &l2cap_channels); 932 while (linked_list_iterator_has_next(&it)){ 933 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 934 if (channel->handle != handle) continue; 935 936 log_info("l2cap - state %u", channel->state); 937 938 gap_security_level_t actual_level = packet[4]; 939 gap_security_level_t required_level = channel->required_security_level; 940 941 switch (channel->state){ 942 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 943 if (actual_level >= required_level){ 944 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 945 l2cap_emit_connection_request(channel); 946 } else { 947 channel->reason = 0x03; // security block 948 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 949 } 950 break; 951 952 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE: 953 if (actual_level >= required_level){ 954 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 955 } else { 956 // disconnnect, authentication not good enough 957 hci_disconnect_security_block(handle); 958 } 959 break; 960 961 default: 962 break; 963 } 964 } 965 break; 966 967 default: 968 break; 969 } 970 971 // pass on: main packet handler, att and sm packet handlers 972 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size); 973 if (attribute_protocol_packet_handler){ 974 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 975 } 976 if (security_protocol_packet_handler) { 977 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 978 } 979 980 l2cap_run(); 981 } 982 983 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){ 984 channel->remote_sig_id = identifier; 985 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 986 l2cap_run(); 987 } 988 989 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){ 990 // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused." 991 if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) { 992 signaling_responses[signaling_responses_pending].handle = handle; 993 signaling_responses[signaling_responses_pending].code = code; 994 signaling_responses[signaling_responses_pending].sig_id = sig_id; 995 signaling_responses[signaling_responses_pending].data = data; 996 signaling_responses_pending++; 997 l2cap_run(); 998 } 999 } 1000 1001 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){ 1002 1003 // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid); 1004 l2cap_service_t *service = l2cap_get_service(psm); 1005 if (!service) { 1006 // 0x0002 PSM not supported 1007 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002); 1008 return; 1009 } 1010 1011 hci_connection_t * hci_connection = hci_connection_for_handle( handle ); 1012 if (!hci_connection) { 1013 // 1014 log_error("no hci_connection for handle %u", handle); 1015 return; 1016 } 1017 1018 // reject connection (0x03 security block) and disconnect if both have SSP, connection is not encrypted and PSM != SDP 1019 if ( hci_ssp_supported_on_both_sides(handle) 1020 && gap_security_level(handle) == LEVEL_0 1021 && !l2cap_security_level_0_allowed_for_PSM(psm)){ 1022 1023 // 0x0003 Security Block 1024 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0003); 1025 return; 1026 } 1027 1028 1029 // alloc structure 1030 // log_info("l2cap_handle_connection_request register channel"); 1031 l2cap_channel_t * channel = btstack_memory_l2cap_channel_get(); 1032 if (!channel){ 1033 // 0x0004 No resources available 1034 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004); 1035 return; 1036 } 1037 1038 // fill in 1039 BD_ADDR_COPY(channel->address, hci_connection->address); 1040 channel->psm = psm; 1041 channel->handle = handle; 1042 channel->connection = service->connection; 1043 channel->packet_handler = service->packet_handler; 1044 channel->local_cid = l2cap_next_local_cid(); 1045 channel->remote_cid = source_cid; 1046 channel->local_mtu = service->mtu; 1047 channel->remote_mtu = L2CAP_DEFAULT_MTU; 1048 channel->packets_granted = 0; 1049 channel->remote_sig_id = sig_id; 1050 channel->required_security_level = service->required_security_level; 1051 1052 // limit local mtu to max acl packet length 1053 if (channel->local_mtu > l2cap_max_mtu()) { 1054 channel->local_mtu = l2cap_max_mtu(); 1055 } 1056 1057 // set initial state 1058 channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE; 1059 channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND; 1060 1061 // add to connections list 1062 linked_list_add(&l2cap_channels, (linked_item_t *) channel); 1063 1064 // assert security requirements 1065 gap_request_security_level(handle, channel->required_security_level); 1066 } 1067 1068 void l2cap_accept_connection_internal(uint16_t local_cid){ 1069 log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid); 1070 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1071 if (!channel) { 1072 log_error("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid); 1073 return; 1074 } 1075 1076 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 1077 1078 // process 1079 l2cap_run(); 1080 } 1081 1082 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){ 1083 log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x, reason %x", local_cid, reason); 1084 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 1085 if (!channel) { 1086 log_error( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid); 1087 return; 1088 } 1089 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 1090 channel->reason = reason; 1091 l2cap_run(); 1092 } 1093 1094 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){ 1095 1096 channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1097 1098 uint16_t flags = READ_BT_16(command, 6); 1099 if (flags & 1) { 1100 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 1101 } 1102 1103 // accept the other's configuration options 1104 uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1105 uint16_t pos = 8; 1106 while (pos < end_pos){ 1107 uint8_t option_hint = command[pos] >> 7; 1108 uint8_t option_type = command[pos] & 0x7f; 1109 log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type); 1110 pos++; 1111 uint8_t length = command[pos++]; 1112 // MTU { type(8): 1, len(8):2, MTU(16) } 1113 if (option_type == 1 && length == 2){ 1114 channel->remote_mtu = READ_BT_16(command, pos); 1115 // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu); 1116 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 1117 } 1118 // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)} 1119 if (option_type == 2 && length == 2){ 1120 channel->flush_timeout = READ_BT_16(command, pos); 1121 } 1122 // check for unknown options 1123 if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){ 1124 log_info("l2cap cid %u, unknown options", channel->local_cid); 1125 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID); 1126 } 1127 pos += length; 1128 } 1129 } 1130 1131 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){ 1132 // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var); 1133 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0; 1134 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0; 1135 return 1; 1136 } 1137 1138 1139 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){ 1140 1141 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1142 uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1143 uint16_t result = 0; 1144 1145 log_info("L2CAP signaling handler code %u, state %u", code, channel->state); 1146 1147 // handle DISCONNECT REQUESTS seperately 1148 if (code == DISCONNECTION_REQUEST){ 1149 switch (channel->state){ 1150 case L2CAP_STATE_CONFIG: 1151 case L2CAP_STATE_OPEN: 1152 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 1153 case L2CAP_STATE_WAIT_DISCONNECT: 1154 l2cap_handle_disconnect_request(channel, identifier); 1155 break; 1156 1157 default: 1158 // ignore in other states 1159 break; 1160 } 1161 return; 1162 } 1163 1164 // @STATEMACHINE(l2cap) 1165 switch (channel->state) { 1166 1167 case L2CAP_STATE_WAIT_CONNECT_RSP: 1168 switch (code){ 1169 case CONNECTION_RESPONSE: 1170 l2cap_stop_rtx(channel); 1171 result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1172 switch (result) { 1173 case 0: 1174 // successful connection 1175 channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1176 channel->state = L2CAP_STATE_CONFIG; 1177 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1178 break; 1179 case 1: 1180 // connection pending. get some coffee, but start the ERTX 1181 l2cap_start_ertx(channel); 1182 break; 1183 default: 1184 // channel closed 1185 channel->state = L2CAP_STATE_CLOSED; 1186 // map l2cap connection response result to BTstack status enumeration 1187 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result); 1188 1189 // drop link key if security block 1190 if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){ 1191 hci_drop_link_key_for_bd_addr(&channel->address); 1192 } 1193 1194 // discard channel 1195 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 1196 btstack_memory_l2cap_channel_free(channel); 1197 break; 1198 } 1199 break; 1200 1201 default: 1202 //@TODO: implement other signaling packets 1203 break; 1204 } 1205 break; 1206 1207 case L2CAP_STATE_CONFIG: 1208 result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1209 switch (code) { 1210 case CONFIGURE_REQUEST: 1211 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 1212 l2cap_signaling_handle_configure_request(channel, command); 1213 if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){ 1214 // only done if continuation not set 1215 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ); 1216 } 1217 break; 1218 case CONFIGURE_RESPONSE: 1219 l2cap_stop_rtx(channel); 1220 switch (result){ 1221 case 0: // success 1222 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP); 1223 break; 1224 case 4: // pending 1225 l2cap_start_ertx(channel); 1226 break; 1227 default: 1228 // retry on negative result 1229 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1230 break; 1231 } 1232 break; 1233 default: 1234 break; 1235 } 1236 if (l2cap_channel_ready_for_open(channel)){ 1237 // for open: 1238 channel->state = L2CAP_STATE_OPEN; 1239 l2cap_emit_channel_opened(channel, 0); 1240 l2cap_emit_credits(channel, 1); 1241 } 1242 break; 1243 1244 case L2CAP_STATE_WAIT_DISCONNECT: 1245 switch (code) { 1246 case DISCONNECTION_RESPONSE: 1247 l2cap_finialize_channel_close(channel); 1248 break; 1249 default: 1250 //@TODO: implement other signaling packets 1251 break; 1252 } 1253 break; 1254 1255 case L2CAP_STATE_CLOSED: 1256 // @TODO handle incoming requests 1257 break; 1258 1259 case L2CAP_STATE_OPEN: 1260 //@TODO: implement other signaling packets, e.g. re-configure 1261 break; 1262 default: 1263 break; 1264 } 1265 // log_info("new state %u", channel->state); 1266 } 1267 1268 1269 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){ 1270 1271 // get code, signalind identifier and command len 1272 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1273 uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1274 1275 // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST 1276 if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){ 1277 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1278 return; 1279 } 1280 1281 // general commands without an assigned channel 1282 switch(code) { 1283 1284 case CONNECTION_REQUEST: { 1285 uint16_t psm = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1286 uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 1287 l2cap_handle_connection_request(handle, sig_id, psm, source_cid); 1288 return; 1289 } 1290 1291 case ECHO_REQUEST: 1292 l2cap_register_signaling_response(handle, code, sig_id, 0); 1293 return; 1294 1295 case INFORMATION_REQUEST: { 1296 uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1297 l2cap_register_signaling_response(handle, code, sig_id, infoType); 1298 return; 1299 } 1300 1301 default: 1302 break; 1303 } 1304 1305 1306 // Get potential destination CID 1307 uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1308 1309 // Find channel for this sig_id and connection handle 1310 linked_list_iterator_t it; 1311 linked_list_iterator_init(&it, &l2cap_channels); 1312 while (linked_list_iterator_has_next(&it)){ 1313 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 1314 if (channel->handle != handle) continue; 1315 if (code & 1) { 1316 // match odd commands (responses) by previous signaling identifier 1317 if (channel->local_sig_id == sig_id) { 1318 l2cap_signaling_handler_channel(channel, command); 1319 break; 1320 } 1321 } else { 1322 // match even commands (requests) by local channel id 1323 if (channel->local_cid == dest_cid) { 1324 l2cap_signaling_handler_channel(channel, command); 1325 break; 1326 } 1327 } 1328 } 1329 } 1330 1331 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){ 1332 1333 // Get Channel ID 1334 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 1335 hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet); 1336 1337 switch (channel_id) { 1338 1339 case L2CAP_CID_SIGNALING: { 1340 1341 uint16_t command_offset = 8; 1342 while (command_offset < size) { 1343 1344 // handle signaling commands 1345 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]); 1346 1347 // increment command_offset 1348 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1349 } 1350 break; 1351 } 1352 1353 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1354 if (attribute_protocol_packet_handler) { 1355 (*attribute_protocol_packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1356 } 1357 break; 1358 1359 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1360 if (security_protocol_packet_handler) { 1361 (*security_protocol_packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1362 } 1363 break; 1364 1365 case L2CAP_CID_SIGNALING_LE: { 1366 switch (packet[8]){ 1367 case CONNECTION_PARAMETER_UPDATE_RESPONSE: { 1368 uint16_t result = READ_BT_16(packet, 12); 1369 l2cap_emit_connection_parameter_update_response(handle, result); 1370 break; 1371 } 1372 case CONNECTION_PARAMETER_UPDATE_REQUEST: { 1373 uint8_t event[10]; 1374 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST; 1375 event[1] = 8; 1376 memcpy(&event[2], &packet[12], 8); 1377 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1378 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, event, sizeof(event)); 1379 break; 1380 } 1381 default: { 1382 uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1]; 1383 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1384 break; 1385 } 1386 } 1387 break; 1388 } 1389 1390 default: { 1391 // Find channel for this channel_id and connection handle 1392 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id); 1393 if (channel) { 1394 l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1395 } 1396 break; 1397 } 1398 } 1399 } 1400 1401 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1402 switch (packet_type) { 1403 case HCI_EVENT_PACKET: 1404 l2cap_event_handler(packet, size); 1405 break; 1406 case HCI_ACL_DATA_PACKET: 1407 l2cap_acl_handler(packet, size); 1408 break; 1409 default: 1410 break; 1411 } 1412 l2cap_run(); 1413 } 1414 1415 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 1416 void l2cap_finialize_channel_close(l2cap_channel_t *channel){ 1417 channel->state = L2CAP_STATE_CLOSED; 1418 l2cap_emit_channel_closed(channel); 1419 // discard channel 1420 l2cap_stop_rtx(channel); 1421 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 1422 btstack_memory_l2cap_channel_free(channel); 1423 } 1424 1425 l2cap_service_t * l2cap_get_service(uint16_t psm){ 1426 linked_list_iterator_t it; 1427 linked_list_iterator_init(&it, &l2cap_services); 1428 while (linked_list_iterator_has_next(&it)){ 1429 l2cap_service_t * service = (l2cap_service_t *) linked_list_iterator_next(&it); 1430 if ( service->psm == psm){ 1431 return service; 1432 }; 1433 } 1434 return NULL; 1435 } 1436 1437 void l2cap_register_service_internal(void *connection, btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){ 1438 1439 log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu); 1440 1441 // check for alread registered psm 1442 // TODO: emit error event 1443 l2cap_service_t *service = l2cap_get_service(psm); 1444 if (service) { 1445 log_error("l2cap_register_service_internal: PSM %u already registered", psm); 1446 l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm); 1447 return; 1448 } 1449 1450 // alloc structure 1451 // TODO: emit error event 1452 service = btstack_memory_l2cap_service_get(); 1453 if (!service) { 1454 log_error("l2cap_register_service_internal: no memory for l2cap_service_t"); 1455 l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm); 1456 return; 1457 } 1458 1459 // fill in 1460 service->psm = psm; 1461 service->mtu = mtu; 1462 service->connection = connection; 1463 service->packet_handler = packet_handler; 1464 service->required_security_level = security_level; 1465 1466 // add to services list 1467 linked_list_add(&l2cap_services, (linked_item_t *) service); 1468 1469 // enable page scan 1470 hci_connectable_control(1); 1471 1472 // done 1473 l2cap_emit_service_registered(connection, 0, psm); 1474 } 1475 1476 void l2cap_unregister_service_internal(void *connection, uint16_t psm){ 1477 1478 log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm); 1479 1480 l2cap_service_t *service = l2cap_get_service(psm); 1481 if (!service) return; 1482 linked_list_remove(&l2cap_services, (linked_item_t *) service); 1483 btstack_memory_l2cap_service_free(service); 1484 1485 // disable page scan when no services registered 1486 if (!linked_list_empty(&l2cap_services)) return; 1487 hci_connectable_control(0); 1488 } 1489 1490 1491 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol 1492 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) { 1493 switch(channel_id){ 1494 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1495 attribute_protocol_packet_handler = packet_handler; 1496 break; 1497 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1498 security_protocol_packet_handler = packet_handler; 1499 break; 1500 } 1501 } 1502 1503 #ifdef HAVE_BLE 1504 // Request LE connection parameter update 1505 int l2cap_le_request_connection_parameter_update(uint16_t handle, uint16_t interval_min, uint16_t interval_max, uint16_t slave_latency, uint16_t timeout_multiplier){ 1506 if (!hci_can_send_acl_packet_now(handle)){ 1507 log_info("l2cap_send_signaling_packet, cannot send"); 1508 return BTSTACK_ACL_BUFFERS_FULL; 1509 } 1510 // log_info("l2cap_send_signaling_packet type %u", cmd); 1511 hci_reserve_packet_buffer(); 1512 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1513 uint16_t len = l2cap_le_create_connection_parameter_update_request(acl_buffer, handle, interval_min, interval_max, slave_latency, timeout_multiplier); 1514 return hci_send_acl_packet_buffer(len); 1515 } 1516 #endif 1517 1518