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, 19, 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 690 uint16_t l2cap_max_mtu(void){ 691 int classic_acl_lenght = hci_max_acl_data_packet_length(); 692 if (classic_acl_lenght == 0) return 0; 693 return hci_max_acl_data_packet_length() - L2CAP_HEADER_SIZE; 694 } 695 696 uint16_t l2cap_max_le_mtu(void){ 697 return L2CAP_LE_DEFAULT_MTU; 698 } 699 700 static void l2cap_handle_connection_complete(uint16_t handle, l2cap_channel_t * channel){ 701 if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) { 702 log_info("l2cap_handle_connection_complete expected state"); 703 // success, start l2cap handshake 704 channel->handle = handle; 705 channel->local_cid = l2cap_next_local_cid(); 706 // check remote SSP feature first 707 channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES; 708 } 709 } 710 711 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){ 712 if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return; 713 714 // we have been waiting for remote supported features, if both support SSP, 715 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)); 716 if (hci_ssp_supported_on_both_sides(channel->handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){ 717 // request security level 2 718 channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE; 719 gap_request_security_level(channel->handle, LEVEL_2); 720 return; 721 } 722 // fine, go ahead 723 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 724 } 725 726 // open outgoing L2CAP channel 727 void l2cap_create_channel_internal(void * connection, btstack_packet_handler_t packet_handler, 728 bd_addr_t address, uint16_t psm, uint16_t mtu){ 729 730 log_info("L2CAP_CREATE_CHANNEL_MTU addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, mtu); 731 732 // alloc structure 733 l2cap_channel_t * chan = btstack_memory_l2cap_channel_get(); 734 if (!chan) { 735 // emit error event 736 l2cap_channel_t dummy_channel; 737 BD_ADDR_COPY(dummy_channel.address, address); 738 dummy_channel.psm = psm; 739 l2cap_emit_channel_opened(&dummy_channel, BTSTACK_MEMORY_ALLOC_FAILED); 740 return; 741 } 742 // limit local mtu to max acl packet length 743 if (mtu > l2cap_max_mtu()) { 744 mtu = l2cap_max_mtu(); 745 } 746 747 // fill in 748 BD_ADDR_COPY(chan->address, address); 749 chan->psm = psm; 750 chan->handle = 0; 751 chan->connection = connection; 752 chan->packet_handler = packet_handler; 753 chan->remote_mtu = L2CAP_MINIMAL_MTU; 754 chan->local_mtu = mtu; 755 chan->packets_granted = 0; 756 757 // set initial state 758 chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION; 759 chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE; 760 chan->remote_sig_id = L2CAP_SIG_ID_INVALID; 761 chan->local_sig_id = L2CAP_SIG_ID_INVALID; 762 chan->required_security_level = LEVEL_0; 763 764 // add to connections list 765 linked_list_add(&l2cap_channels, (linked_item_t *) chan); 766 767 // check if hci connection is already usable 768 hci_connection_t * conn = hci_connection_for_bd_addr_and_type((bd_addr_t*)address, BD_ADDR_TYPE_CLASSIC); 769 if (conn){ 770 log_info("l2cap_create_channel_internal, hci connection already exists"); 771 l2cap_handle_connection_complete(conn->con_handle, chan); 772 // check ir remote supported fearures are already received 773 if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) { 774 l2cap_handle_remote_supported_features_received(chan); 775 } 776 } 777 778 l2cap_run(); 779 } 780 781 void l2cap_disconnect_internal(uint16_t local_cid, uint8_t reason){ 782 log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason); 783 // find channel for local_cid 784 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 785 if (channel) { 786 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST; 787 } 788 // process 789 l2cap_run(); 790 } 791 792 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){ 793 linked_list_iterator_t it; 794 linked_list_iterator_init(&it, &l2cap_channels); 795 while (linked_list_iterator_has_next(&it)){ 796 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 797 if ( BD_ADDR_CMP( channel->address, address) != 0) continue; 798 // channel for this address found 799 switch (channel->state){ 800 case L2CAP_STATE_WAIT_CONNECTION_COMPLETE: 801 case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION: 802 // failure, forward error code 803 l2cap_emit_channel_opened(channel, status); 804 // discard channel 805 l2cap_stop_rtx(channel); 806 linked_list_iterator_remove(&it); 807 btstack_memory_l2cap_channel_free(channel); 808 break; 809 default: 810 break; 811 } 812 } 813 } 814 815 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){ 816 linked_list_iterator_t it; 817 linked_list_iterator_init(&it, &l2cap_channels); 818 while (linked_list_iterator_has_next(&it)){ 819 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 820 if ( ! BD_ADDR_CMP( channel->address, address) ){ 821 l2cap_handle_connection_complete(handle, channel); 822 } 823 } 824 // process 825 l2cap_run(); 826 } 827 828 void l2cap_event_handler(uint8_t *packet, uint16_t size){ 829 830 bd_addr_t address; 831 hci_con_handle_t handle; 832 linked_list_iterator_t it; 833 int hci_con_used; 834 835 switch(packet[0]){ 836 837 // handle connection complete events 838 case HCI_EVENT_CONNECTION_COMPLETE: 839 bt_flip_addr(address, &packet[5]); 840 if (packet[2] == 0){ 841 handle = READ_BT_16(packet, 3); 842 l2cap_handle_connection_success_for_addr(address, handle); 843 } else { 844 l2cap_handle_connection_failed_for_addr(address, packet[2]); 845 } 846 break; 847 848 // handle successful create connection cancel command 849 case HCI_EVENT_COMMAND_COMPLETE: 850 if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) { 851 if (packet[5] == 0){ 852 bt_flip_addr(address, &packet[6]); 853 // CONNECTION TERMINATED BY LOCAL HOST (0X16) 854 l2cap_handle_connection_failed_for_addr(address, 0x16); 855 } 856 } 857 l2cap_run(); // try sending signaling packets first 858 break; 859 860 case HCI_EVENT_COMMAND_STATUS: 861 l2cap_run(); // try sending signaling packets first 862 break; 863 864 // handle disconnection complete events 865 case HCI_EVENT_DISCONNECTION_COMPLETE: 866 // send l2cap disconnect events for all channels on this handle and free them 867 handle = READ_BT_16(packet, 3); 868 linked_list_iterator_init(&it, &l2cap_channels); 869 while (linked_list_iterator_has_next(&it)){ 870 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 871 if (channel->handle != handle) continue; 872 l2cap_emit_channel_closed(channel); 873 l2cap_stop_rtx(channel); 874 linked_list_iterator_remove(&it); 875 btstack_memory_l2cap_channel_free(channel); 876 } 877 break; 878 879 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 880 l2cap_run(); // try sending signaling packets first 881 l2cap_hand_out_credits(); 882 break; 883 884 // HCI Connection Timeouts 885 case L2CAP_EVENT_TIMEOUT_CHECK: 886 handle = READ_BT_16(packet, 2); 887 if (hci_authentication_active_for_handle(handle)) break; 888 hci_con_used = 0; 889 linked_list_iterator_init(&it, &l2cap_channels); 890 while (linked_list_iterator_has_next(&it)){ 891 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 892 if (channel->handle != handle) continue; 893 hci_con_used = 1; 894 break; 895 } 896 if (hci_con_used) break; 897 if (!hci_can_send_command_packet_now()) break; 898 hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection 899 break; 900 901 case DAEMON_EVENT_HCI_PACKET_SENT: 902 linked_list_iterator_init(&it, &l2cap_channels); 903 while (linked_list_iterator_has_next(&it)){ 904 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 905 if (!channel->packet_handler) continue; 906 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size); 907 } 908 if (attribute_protocol_packet_handler) { 909 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 910 } 911 if (security_protocol_packet_handler) { 912 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 913 } 914 break; 915 916 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 917 handle = READ_BT_16(packet, 3); 918 linked_list_iterator_init(&it, &l2cap_channels); 919 while (linked_list_iterator_has_next(&it)){ 920 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 921 if (channel->handle != handle) continue; 922 l2cap_handle_remote_supported_features_received(channel); 923 break; 924 } 925 break; 926 927 case GAP_SECURITY_LEVEL: 928 handle = READ_BT_16(packet, 2); 929 log_info("l2cap - security level update"); 930 linked_list_iterator_init(&it, &l2cap_channels); 931 while (linked_list_iterator_has_next(&it)){ 932 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 933 if (channel->handle != handle) continue; 934 935 log_info("l2cap - state %u", channel->state); 936 937 gap_security_level_t actual_level = packet[4]; 938 gap_security_level_t required_level = channel->required_security_level; 939 940 switch (channel->state){ 941 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE: 942 if (actual_level >= required_level){ 943 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT; 944 l2cap_emit_connection_request(channel); 945 } else { 946 channel->reason = 0x03; // security block 947 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 948 } 949 break; 950 951 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE: 952 if (actual_level >= required_level){ 953 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST; 954 } else { 955 // disconnnect, authentication not good enough 956 hci_disconnect_security_block(handle); 957 } 958 break; 959 960 default: 961 break; 962 } 963 } 964 break; 965 966 default: 967 break; 968 } 969 970 // pass on: main packet handler, att and sm packet handlers 971 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, packet, size); 972 if (attribute_protocol_packet_handler){ 973 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 974 } 975 if (security_protocol_packet_handler) { 976 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size); 977 } 978 979 l2cap_run(); 980 } 981 982 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){ 983 channel->remote_sig_id = identifier; 984 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE; 985 l2cap_run(); 986 } 987 988 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){ 989 // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused." 990 if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) { 991 signaling_responses[signaling_responses_pending].handle = handle; 992 signaling_responses[signaling_responses_pending].code = code; 993 signaling_responses[signaling_responses_pending].sig_id = sig_id; 994 signaling_responses[signaling_responses_pending].data = data; 995 signaling_responses_pending++; 996 l2cap_run(); 997 } 998 } 999 1000 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){ 1001 1002 // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid); 1003 l2cap_service_t *service = l2cap_get_service(psm); 1004 if (!service) { 1005 // 0x0002 PSM not supported 1006 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002); 1007 return; 1008 } 1009 1010 hci_connection_t * hci_connection = hci_connection_for_handle( handle ); 1011 if (!hci_connection) { 1012 // 1013 log_error("no hci_connection for handle %u", handle); 1014 return; 1015 } 1016 1017 // reject connection (0x03 security block) and disconnect if both have SSP, connection is not encrypted and PSM != SDP 1018 if ( hci_ssp_supported_on_both_sides(handle) 1019 && gap_security_level(handle) == LEVEL_0 1020 && !l2cap_security_level_0_allowed_for_PSM(psm)){ 1021 1022 // 0x0003 Security Block 1023 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0003); 1024 return; 1025 } 1026 1027 1028 // alloc structure 1029 // log_info("l2cap_handle_connection_request register channel"); 1030 l2cap_channel_t * channel = btstack_memory_l2cap_channel_get(); 1031 if (!channel){ 1032 // 0x0004 No resources available 1033 l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004); 1034 return; 1035 } 1036 1037 // fill in 1038 BD_ADDR_COPY(channel->address, hci_connection->address); 1039 channel->psm = psm; 1040 channel->handle = handle; 1041 channel->connection = service->connection; 1042 channel->packet_handler = service->packet_handler; 1043 channel->local_cid = l2cap_next_local_cid(); 1044 channel->remote_cid = source_cid; 1045 channel->local_mtu = service->mtu; 1046 channel->remote_mtu = L2CAP_DEFAULT_MTU; 1047 channel->packets_granted = 0; 1048 channel->remote_sig_id = sig_id; 1049 channel->required_security_level = service->required_security_level; 1050 1051 // limit local mtu to max acl packet length 1052 if (channel->local_mtu > l2cap_max_mtu()) { 1053 channel->local_mtu = l2cap_max_mtu(); 1054 } 1055 1056 // set initial state 1057 channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE; 1058 channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND; 1059 1060 // add to connections list 1061 linked_list_add(&l2cap_channels, (linked_item_t *) channel); 1062 1063 // assert security requirements 1064 gap_request_security_level(handle, channel->required_security_level); 1065 } 1066 1067 void l2cap_accept_connection_internal(uint16_t local_cid){ 1068 log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid); 1069 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid); 1070 if (!channel) { 1071 log_error("l2cap_accept_connection_internal called but local_cid 0x%x not found", local_cid); 1072 return; 1073 } 1074 1075 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT; 1076 1077 // process 1078 l2cap_run(); 1079 } 1080 1081 void l2cap_decline_connection_internal(uint16_t local_cid, uint8_t reason){ 1082 log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x, reason %x", local_cid, reason); 1083 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid); 1084 if (!channel) { 1085 log_error( "l2cap_decline_connection_internal called but local_cid 0x%x not found", local_cid); 1086 return; 1087 } 1088 channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE; 1089 channel->reason = reason; 1090 l2cap_run(); 1091 } 1092 1093 void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){ 1094 1095 channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1096 1097 uint16_t flags = READ_BT_16(command, 6); 1098 if (flags & 1) { 1099 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT); 1100 } 1101 1102 // accept the other's configuration options 1103 uint16_t end_pos = 4 + READ_BT_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1104 uint16_t pos = 8; 1105 while (pos < end_pos){ 1106 uint8_t option_hint = command[pos] >> 7; 1107 uint8_t option_type = command[pos] & 0x7f; 1108 log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type); 1109 pos++; 1110 uint8_t length = command[pos++]; 1111 // MTU { type(8): 1, len(8):2, MTU(16) } 1112 if (option_type == 1 && length == 2){ 1113 channel->remote_mtu = READ_BT_16(command, pos); 1114 // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu); 1115 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU); 1116 } 1117 // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)} 1118 if (option_type == 2 && length == 2){ 1119 channel->flush_timeout = READ_BT_16(command, pos); 1120 } 1121 // check for unknown options 1122 if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){ 1123 log_info("l2cap cid %u, unknown options", channel->local_cid); 1124 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID); 1125 } 1126 pos += length; 1127 } 1128 } 1129 1130 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){ 1131 // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var); 1132 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0; 1133 if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0; 1134 return 1; 1135 } 1136 1137 1138 void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){ 1139 1140 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1141 uint8_t identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1142 uint16_t result = 0; 1143 1144 log_info("L2CAP signaling handler code %u, state %u", code, channel->state); 1145 1146 // handle DISCONNECT REQUESTS seperately 1147 if (code == DISCONNECTION_REQUEST){ 1148 switch (channel->state){ 1149 case L2CAP_STATE_CONFIG: 1150 case L2CAP_STATE_OPEN: 1151 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST: 1152 case L2CAP_STATE_WAIT_DISCONNECT: 1153 l2cap_handle_disconnect_request(channel, identifier); 1154 break; 1155 1156 default: 1157 // ignore in other states 1158 break; 1159 } 1160 return; 1161 } 1162 1163 // @STATEMACHINE(l2cap) 1164 switch (channel->state) { 1165 1166 case L2CAP_STATE_WAIT_CONNECT_RSP: 1167 switch (code){ 1168 case CONNECTION_RESPONSE: 1169 l2cap_stop_rtx(channel); 1170 result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1171 switch (result) { 1172 case 0: 1173 // successful connection 1174 channel->remote_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1175 channel->state = L2CAP_STATE_CONFIG; 1176 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1177 break; 1178 case 1: 1179 // connection pending. get some coffee, but start the ERTX 1180 l2cap_start_ertx(channel); 1181 break; 1182 default: 1183 // channel closed 1184 channel->state = L2CAP_STATE_CLOSED; 1185 // map l2cap connection response result to BTstack status enumeration 1186 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result); 1187 1188 // drop link key if security block 1189 if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){ 1190 hci_drop_link_key_for_bd_addr(&channel->address); 1191 } 1192 1193 // discard channel 1194 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 1195 btstack_memory_l2cap_channel_free(channel); 1196 break; 1197 } 1198 break; 1199 1200 default: 1201 //@TODO: implement other signaling packets 1202 break; 1203 } 1204 break; 1205 1206 case L2CAP_STATE_CONFIG: 1207 result = READ_BT_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4); 1208 switch (code) { 1209 case CONFIGURE_REQUEST: 1210 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP); 1211 l2cap_signaling_handle_configure_request(channel, command); 1212 if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){ 1213 // only done if continuation not set 1214 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ); 1215 } 1216 break; 1217 case CONFIGURE_RESPONSE: 1218 l2cap_stop_rtx(channel); 1219 switch (result){ 1220 case 0: // success 1221 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP); 1222 break; 1223 case 4: // pending 1224 l2cap_start_ertx(channel); 1225 break; 1226 default: 1227 // retry on negative result 1228 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ); 1229 break; 1230 } 1231 break; 1232 default: 1233 break; 1234 } 1235 if (l2cap_channel_ready_for_open(channel)){ 1236 // for open: 1237 channel->state = L2CAP_STATE_OPEN; 1238 l2cap_emit_channel_opened(channel, 0); 1239 l2cap_emit_credits(channel, 1); 1240 } 1241 break; 1242 1243 case L2CAP_STATE_WAIT_DISCONNECT: 1244 switch (code) { 1245 case DISCONNECTION_RESPONSE: 1246 l2cap_finialize_channel_close(channel); 1247 break; 1248 default: 1249 //@TODO: implement other signaling packets 1250 break; 1251 } 1252 break; 1253 1254 case L2CAP_STATE_CLOSED: 1255 // @TODO handle incoming requests 1256 break; 1257 1258 case L2CAP_STATE_OPEN: 1259 //@TODO: implement other signaling packets, e.g. re-configure 1260 break; 1261 default: 1262 break; 1263 } 1264 // log_info("new state %u", channel->state); 1265 } 1266 1267 1268 void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){ 1269 1270 // get code, signalind identifier and command len 1271 uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET]; 1272 uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET]; 1273 1274 // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST 1275 if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){ 1276 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1277 return; 1278 } 1279 1280 // general commands without an assigned channel 1281 switch(code) { 1282 1283 case CONNECTION_REQUEST: { 1284 uint16_t psm = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1285 uint16_t source_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2); 1286 l2cap_handle_connection_request(handle, sig_id, psm, source_cid); 1287 return; 1288 } 1289 1290 case ECHO_REQUEST: 1291 l2cap_register_signaling_response(handle, code, sig_id, 0); 1292 return; 1293 1294 case INFORMATION_REQUEST: { 1295 uint16_t infoType = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1296 l2cap_register_signaling_response(handle, code, sig_id, infoType); 1297 return; 1298 } 1299 1300 default: 1301 break; 1302 } 1303 1304 1305 // Get potential destination CID 1306 uint16_t dest_cid = READ_BT_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET); 1307 1308 // Find channel for this sig_id and connection handle 1309 linked_list_iterator_t it; 1310 linked_list_iterator_init(&it, &l2cap_channels); 1311 while (linked_list_iterator_has_next(&it)){ 1312 l2cap_channel_t * channel = (l2cap_channel_t *) linked_list_iterator_next(&it); 1313 if (channel->handle != handle) continue; 1314 if (code & 1) { 1315 // match odd commands (responses) by previous signaling identifier 1316 if (channel->local_sig_id == sig_id) { 1317 l2cap_signaling_handler_channel(channel, command); 1318 break; 1319 } 1320 } else { 1321 // match even commands (requests) by local channel id 1322 if (channel->local_cid == dest_cid) { 1323 l2cap_signaling_handler_channel(channel, command); 1324 break; 1325 } 1326 } 1327 } 1328 } 1329 1330 void l2cap_acl_handler( uint8_t *packet, uint16_t size ){ 1331 1332 // Get Channel ID 1333 uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet); 1334 hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet); 1335 1336 switch (channel_id) { 1337 1338 case L2CAP_CID_SIGNALING: { 1339 1340 uint16_t command_offset = 8; 1341 while (command_offset < size) { 1342 1343 // handle signaling commands 1344 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]); 1345 1346 // increment command_offset 1347 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + READ_BT_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET); 1348 } 1349 break; 1350 } 1351 1352 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1353 if (attribute_protocol_packet_handler) { 1354 (*attribute_protocol_packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1355 } 1356 break; 1357 1358 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1359 if (security_protocol_packet_handler) { 1360 (*security_protocol_packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1361 } 1362 break; 1363 1364 case L2CAP_CID_SIGNALING_LE: { 1365 switch (packet[8]){ 1366 case CONNECTION_PARAMETER_UPDATE_RESPONSE: { 1367 uint16_t result = READ_BT_16(packet, 12); 1368 l2cap_emit_connection_parameter_update_response(handle, result); 1369 break; 1370 } 1371 case CONNECTION_PARAMETER_UPDATE_REQUEST: { 1372 uint8_t event[10]; 1373 event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST; 1374 event[1] = 8; 1375 memcpy(&event[2], &packet[12], 8); 1376 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1377 (*packet_handler)(NULL, HCI_EVENT_PACKET, 0, event, sizeof(event)); 1378 break; 1379 } 1380 default: { 1381 uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1]; 1382 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN); 1383 break; 1384 } 1385 } 1386 break; 1387 } 1388 1389 default: { 1390 // Find channel for this channel_id and connection handle 1391 l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id); 1392 if (channel) { 1393 l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER); 1394 } 1395 break; 1396 } 1397 } 1398 } 1399 1400 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1401 switch (packet_type) { 1402 case HCI_EVENT_PACKET: 1403 l2cap_event_handler(packet, size); 1404 break; 1405 case HCI_ACL_DATA_PACKET: 1406 l2cap_acl_handler(packet, size); 1407 break; 1408 default: 1409 break; 1410 } 1411 l2cap_run(); 1412 } 1413 1414 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE 1415 void l2cap_finialize_channel_close(l2cap_channel_t *channel){ 1416 channel->state = L2CAP_STATE_CLOSED; 1417 l2cap_emit_channel_closed(channel); 1418 // discard channel 1419 l2cap_stop_rtx(channel); 1420 linked_list_remove(&l2cap_channels, (linked_item_t *) channel); 1421 btstack_memory_l2cap_channel_free(channel); 1422 } 1423 1424 l2cap_service_t * l2cap_get_service(uint16_t psm){ 1425 linked_list_iterator_t it; 1426 linked_list_iterator_init(&it, &l2cap_services); 1427 while (linked_list_iterator_has_next(&it)){ 1428 l2cap_service_t * service = (l2cap_service_t *) linked_list_iterator_next(&it); 1429 if ( service->psm == psm){ 1430 return service; 1431 }; 1432 } 1433 return NULL; 1434 } 1435 1436 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){ 1437 1438 log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu); 1439 1440 // check for alread registered psm 1441 // TODO: emit error event 1442 l2cap_service_t *service = l2cap_get_service(psm); 1443 if (service) { 1444 log_error("l2cap_register_service_internal: PSM %u already registered", psm); 1445 l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm); 1446 return; 1447 } 1448 1449 // alloc structure 1450 // TODO: emit error event 1451 service = btstack_memory_l2cap_service_get(); 1452 if (!service) { 1453 log_error("l2cap_register_service_internal: no memory for l2cap_service_t"); 1454 l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm); 1455 return; 1456 } 1457 1458 // fill in 1459 service->psm = psm; 1460 service->mtu = mtu; 1461 service->connection = connection; 1462 service->packet_handler = packet_handler; 1463 service->required_security_level = security_level; 1464 1465 // add to services list 1466 linked_list_add(&l2cap_services, (linked_item_t *) service); 1467 1468 // enable page scan 1469 hci_connectable_control(1); 1470 1471 // done 1472 l2cap_emit_service_registered(connection, 0, psm); 1473 } 1474 1475 void l2cap_unregister_service_internal(void *connection, uint16_t psm){ 1476 1477 log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm); 1478 1479 l2cap_service_t *service = l2cap_get_service(psm); 1480 if (!service) return; 1481 linked_list_remove(&l2cap_services, (linked_item_t *) service); 1482 btstack_memory_l2cap_service_free(service); 1483 1484 // disable page scan when no services registered 1485 if (!linked_list_empty(&l2cap_services)) return; 1486 hci_connectable_control(0); 1487 } 1488 1489 1490 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol 1491 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) { 1492 switch(channel_id){ 1493 case L2CAP_CID_ATTRIBUTE_PROTOCOL: 1494 attribute_protocol_packet_handler = packet_handler; 1495 break; 1496 case L2CAP_CID_SECURITY_MANAGER_PROTOCOL: 1497 security_protocol_packet_handler = packet_handler; 1498 break; 1499 } 1500 } 1501 1502 #ifdef HAVE_BLE 1503 // Request LE connection parameter update 1504 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){ 1505 if (!hci_can_send_acl_packet_now(handle)){ 1506 log_info("l2cap_send_signaling_packet, cannot send"); 1507 return BTSTACK_ACL_BUFFERS_FULL; 1508 } 1509 // log_info("l2cap_send_signaling_packet type %u", cmd); 1510 hci_reserve_packet_buffer(); 1511 uint8_t *acl_buffer = hci_get_outgoing_packet_buffer(); 1512 uint16_t len = l2cap_le_create_connection_parameter_update_request(acl_buffer, handle, interval_min, interval_max, slave_latency, timeout_multiplier); 1513 return hci_send_acl_packet_buffer(len); 1514 } 1515 #endif 1516 1517