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