1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN 24 * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define BTSTACK_FILE__ "hci.c" 39 40 /* 41 * hci.c 42 * 43 * Created by Matthias Ringwald on 4/29/09. 44 * 45 */ 46 47 #include "btstack_config.h" 48 49 50 #ifdef ENABLE_CLASSIC 51 #ifdef HAVE_EMBEDDED_TICK 52 #include "btstack_run_loop_embedded.h" 53 #endif 54 #endif 55 56 #ifdef ENABLE_BLE 57 #include "gap.h" 58 #include "ble/le_device_db.h" 59 #endif 60 61 #include <stdarg.h> 62 #include <string.h> 63 #include <inttypes.h> 64 65 #include "btstack_debug.h" 66 #include "btstack_event.h" 67 #include "btstack_linked_list.h" 68 #include "btstack_memory.h" 69 #include "bluetooth_company_id.h" 70 #include "bluetooth_data_types.h" 71 #include "gap.h" 72 #include "hci.h" 73 #include "hci_cmd.h" 74 #include "hci_dump.h" 75 #include "ad_parser.h" 76 77 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 78 #include <stdio.h> // sprintf 79 #endif 80 81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 82 #ifndef HCI_HOST_ACL_PACKET_NUM 83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM" 84 #endif 85 #ifndef HCI_HOST_ACL_PACKET_LEN 86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN" 87 #endif 88 #ifndef HCI_HOST_SCO_PACKET_NUM 89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM" 90 #endif 91 #ifndef HCI_HOST_SCO_PACKET_LEN 92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN" 93 #endif 94 #endif 95 96 #if defined(ENABLE_SCO_OVER_HCI) && defined(ENABLE_SCO_OVER_PCM) 97 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM." 98 #endif 99 100 #if defined(ENABLE_SCO_OVER_HCI) && defined(HAVE_SCO_TRANSPORT) 101 #error "SCO data can either be routed over HCI or over PCM, but not over both. Please only enable ENABLE_SCO_OVER_HCI or HAVE_SCO_TRANSPORT." 102 #endif 103 104 #define HCI_CONNECTION_TIMEOUT_MS 10000 105 106 #ifndef HCI_RESET_RESEND_TIMEOUT_MS 107 #define HCI_RESET_RESEND_TIMEOUT_MS 200 108 #endif 109 110 // Names are arbitrarily shortened to 32 bytes if not requested otherwise 111 #ifndef GAP_INQUIRY_MAX_NAME_LEN 112 #define GAP_INQUIRY_MAX_NAME_LEN 32 113 #endif 114 115 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested 116 #define GAP_INQUIRY_DURATION_MIN 0x01 117 #define GAP_INQUIRY_DURATION_MAX 0x30 118 #define GAP_INQUIRY_MIN_PERIODIC_LEN_MIN 0x02 119 #define GAP_INQUIRY_MAX_PERIODIC_LEN_MIN 0x03 120 #define GAP_INQUIRY_STATE_IDLE 0x00 121 #define GAP_INQUIRY_STATE_W4_ACTIVE 0x80 122 #define GAP_INQUIRY_STATE_ACTIVE 0x81 123 #define GAP_INQUIRY_STATE_W2_CANCEL 0x82 124 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x83 125 #define GAP_INQUIRY_STATE_PERIODIC 0x84 126 #define GAP_INQUIRY_STATE_W2_EXIT_PERIODIC 0x85 127 128 // GAP Remote Name Request 129 #define GAP_REMOTE_NAME_STATE_IDLE 0 130 #define GAP_REMOTE_NAME_STATE_W2_SEND 1 131 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2 132 133 // GAP Pairing 134 #define GAP_PAIRING_STATE_IDLE 0 135 #define GAP_PAIRING_STATE_SEND_PIN 1 136 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE 2 137 #define GAP_PAIRING_STATE_SEND_PASSKEY 3 138 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE 4 139 #define GAP_PAIRING_STATE_SEND_CONFIRMATION 5 140 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6 141 #define GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE 7 142 143 // 144 // compact storage of relevant supported HCI Commands. 145 // X-Macro below provides enumeration and mapping table into the supported 146 // commands bitmap (64 bytes) from HCI Read Local Supported Commands 147 // 148 149 // format: command name, byte offset, bit nr in 64-byte supported commands 150 // currently stored in 32-bit variable 151 #define SUPPORTED_HCI_COMMANDS \ 152 X( SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES , 2, 5) \ 153 X( SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE , 10, 4) \ 154 X( SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE , 14, 7) \ 155 X( SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING, 18, 3) \ 156 X( SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE , 20, 4) \ 157 X( SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2 , 22, 2) \ 158 X( SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED , 24, 6) \ 159 X( SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY, 32, 1) \ 160 X( SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST , 32, 3) \ 161 X( SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND , 32, 6) \ 162 X( SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH, 34, 0) \ 163 X( SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE , 35, 1) \ 164 X( SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH , 35, 3) \ 165 X( SUPPORTED_HCI_COMMAND_LE_SET_DEFAULT_PHY , 35, 5) \ 166 X( SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE , 36, 6) \ 167 X( SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2 , 41, 5) \ 168 X( SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE , 45, 7) \ 169 170 // enumerate supported commands 171 #define X(name, offset, bit) name, 172 enum { 173 SUPPORTED_HCI_COMMANDS 174 SUPPORTED_HCI_COMMANDS_COUNT 175 }; 176 #undef X 177 178 // prototypes 179 #ifdef ENABLE_CLASSIC 180 static void hci_update_scan_enable(void); 181 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable); 182 static int hci_local_ssp_activated(void); 183 static bool hci_remote_ssp_supported(hci_con_handle_t con_handle); 184 static bool hci_ssp_supported(hci_connection_t * connection); 185 static void hci_notify_if_sco_can_send_now(void); 186 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status); 187 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 188 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level); 189 static void hci_connection_timeout_handler(btstack_timer_source_t *timer); 190 static void hci_connection_timestamp(hci_connection_t *connection); 191 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn); 192 static void gap_inquiry_explode(uint8_t *packet, uint16_t size); 193 #endif 194 195 static int hci_power_control_on(void); 196 static void hci_power_control_off(void); 197 static void hci_state_reset(void); 198 static void hci_halting_timeout_handler(btstack_timer_source_t * ds); 199 static void hci_emit_transport_packet_sent(void); 200 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason); 201 static void hci_emit_nr_connections_changed(void); 202 static void hci_emit_hci_open_failed(void); 203 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status); 204 static void hci_emit_event(uint8_t * event, uint16_t size, int dump); 205 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size); 206 static void hci_run(void); 207 static int hci_is_le_connection(hci_connection_t * connection); 208 209 #ifdef ENABLE_CLASSIC 210 static int hci_have_usb_transport(void); 211 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection); 212 #endif 213 214 #ifdef ENABLE_BLE 215 static void hci_whitelist_free(void); 216 #ifdef ENABLE_LE_CENTRAL 217 // called from test/ble_client/advertising_data_parser.c 218 void le_handle_advertisement_report(uint8_t *packet, uint16_t size); 219 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address); 220 static hci_connection_t * gap_get_outgoing_connection(void); 221 static void hci_le_scan_stop(void); 222 static bool hci_run_general_gap_le(void); 223 #endif 224 #ifdef ENABLE_LE_PERIPHERAL 225 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 226 static void hci_periodic_advertiser_list_free(void); 227 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle); 228 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */ 229 #endif /* ENABLE_LE_PERIPHERAL */ 230 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 231 static uint8_t hci_iso_stream_create(hci_con_handle_t con_handle, uint8_t big_handle); 232 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream); 233 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle); 234 static void hci_iso_stream_requested_finalize(uint8_t big_handle); 235 static void hci_iso_stream_requested_confirm(uint8_t big_handle); 236 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size); 237 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle); 238 static void hci_iso_notify_can_send_now(void); 239 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status); 240 static void hci_emit_big_terminated(const le_audio_big_t * big); 241 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status); 242 static void hci_emit_big_sync_stopped(uint8_t big_handle); 243 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle); 244 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 245 #endif /* ENABLE_BLE */ 246 247 // the STACK is here 248 #ifndef HAVE_MALLOC 249 static hci_stack_t hci_stack_static; 250 #endif 251 static hci_stack_t * hci_stack = NULL; 252 253 #ifdef ENABLE_CLASSIC 254 // default name 255 static const char * default_classic_name = "BTstack 00:00:00:00:00:00"; 256 257 // test helper 258 static uint8_t disable_l2cap_timeouts = 0; 259 #endif 260 261 // reset connection state on create and on reconnect 262 // don't overwrite addr, con handle, role 263 static void hci_connection_init(hci_connection_t * conn){ 264 conn->authentication_flags = AUTH_FLAG_NONE; 265 conn->bonding_flags = 0; 266 conn->requested_security_level = LEVEL_0; 267 #ifdef ENABLE_CLASSIC 268 conn->request_role = HCI_ROLE_INVALID; 269 conn->sniff_subrating_max_latency = 0xffff; 270 conn->qos_service_type = HCI_SERVICE_TYPE_INVALID; 271 conn->link_key_type = INVALID_LINK_KEY; 272 btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler); 273 btstack_run_loop_set_timer_context(&conn->timeout, conn); 274 hci_connection_timestamp(conn); 275 #endif 276 conn->acl_recombination_length = 0; 277 conn->acl_recombination_pos = 0; 278 conn->num_packets_sent = 0; 279 280 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 281 #ifdef ENABLE_BLE 282 conn->le_phy_update_all_phys = 0xff; 283 #endif 284 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS 285 conn->le_max_tx_octets = 27; 286 #endif 287 #ifdef ENABLE_CLASSIC_PAIRING_OOB 288 conn->classic_oob_c_192 = NULL; 289 conn->classic_oob_r_192 = NULL; 290 conn->classic_oob_c_256 = NULL; 291 conn->classic_oob_r_256 = NULL; 292 #endif 293 } 294 295 /** 296 * create connection for given address 297 * 298 * @return connection OR NULL, if no memory left 299 */ 300 static hci_connection_t * create_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){ 301 log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type); 302 303 hci_connection_t * conn = btstack_memory_hci_connection_get(); 304 if (!conn) return NULL; 305 hci_connection_init(conn); 306 307 bd_addr_copy(conn->address, addr); 308 conn->address_type = addr_type; 309 conn->con_handle = HCI_CON_HANDLE_INVALID; 310 conn->role = HCI_ROLE_INVALID; 311 312 btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn); 313 314 return conn; 315 } 316 317 318 /** 319 * get le connection parameter range 320 * 321 * @return le connection parameter range struct 322 */ 323 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){ 324 *range = hci_stack->le_connection_parameter_range; 325 } 326 327 /** 328 * set le connection parameter range 329 * 330 */ 331 332 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){ 333 hci_stack->le_connection_parameter_range = *range; 334 } 335 336 /** 337 * @brief Test if connection parameters are inside in existing rage 338 * @param conn_interval_min (unit: 1.25ms) 339 * @param conn_interval_max (unit: 1.25ms) 340 * @param conn_latency 341 * @param supervision_timeout (unit: 10ms) 342 * @return 1 if included 343 */ 344 int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){ 345 if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0; 346 if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0; 347 348 if (le_conn_latency < existing_range->le_conn_latency_min) return 0; 349 if (le_conn_latency > existing_range->le_conn_latency_max) return 0; 350 351 if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0; 352 if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0; 353 354 return 1; 355 } 356 357 /** 358 * @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it) 359 * @note: default: 1 360 * @param max_peripheral_connections 361 */ 362 #ifdef ENABLE_LE_PERIPHERAL 363 void gap_set_max_number_peripheral_connections(int max_peripheral_connections){ 364 hci_stack->le_max_number_peripheral_connections = max_peripheral_connections; 365 } 366 #endif 367 368 /** 369 * get hci connections iterator 370 * 371 * @return hci connections iterator 372 */ 373 374 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){ 375 btstack_linked_list_iterator_init(it, &hci_stack->connections); 376 } 377 378 /** 379 * get connection for a given handle 380 * 381 * @return connection OR NULL, if not found 382 */ 383 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 384 btstack_linked_list_iterator_t it; 385 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 386 while (btstack_linked_list_iterator_has_next(&it)){ 387 hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 388 if ( item->con_handle == con_handle ) { 389 return item; 390 } 391 } 392 return NULL; 393 } 394 395 /** 396 * get connection for given address 397 * 398 * @return connection OR NULL, if not found 399 */ 400 hci_connection_t * hci_connection_for_bd_addr_and_type(const bd_addr_t addr, bd_addr_type_t addr_type){ 401 btstack_linked_list_iterator_t it; 402 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 403 while (btstack_linked_list_iterator_has_next(&it)){ 404 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 405 if (connection->address_type != addr_type) continue; 406 if (memcmp(addr, connection->address, 6) != 0) continue; 407 return connection; 408 } 409 return NULL; 410 } 411 412 #ifdef ENABLE_CLASSIC 413 414 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 415 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 416 } 417 418 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 419 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 420 } 421 422 #ifdef ENABLE_SCO_OVER_HCI 423 static int hci_number_sco_connections(void){ 424 int connections = 0; 425 btstack_linked_list_iterator_t it; 426 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 427 while (btstack_linked_list_iterator_has_next(&it)){ 428 hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it); 429 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 430 connections++; 431 } 432 return connections; 433 } 434 #endif 435 436 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){ 437 hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer); 438 #ifdef HAVE_EMBEDDED_TICK 439 if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 440 // connections might be timed out 441 hci_emit_l2cap_check_timeout(connection); 442 } 443 #else 444 if (btstack_run_loop_get_time_ms() > (connection->timestamp + HCI_CONNECTION_TIMEOUT_MS)){ 445 // connections might be timed out 446 hci_emit_l2cap_check_timeout(connection); 447 } 448 #endif 449 } 450 451 static void hci_connection_timestamp(hci_connection_t *connection){ 452 #ifdef HAVE_EMBEDDED_TICK 453 connection->timestamp = btstack_run_loop_embedded_get_ticks(); 454 #else 455 connection->timestamp = btstack_run_loop_get_time_ms(); 456 #endif 457 } 458 459 /** 460 * add authentication flags and reset timer 461 * @note: assumes classic connection 462 * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets 463 */ 464 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 465 bd_addr_t addr; 466 reverse_bd_addr(bd_addr, addr); 467 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 468 if (conn) { 469 connectionSetAuthenticationFlags(conn, flags); 470 hci_connection_timestamp(conn); 471 } 472 } 473 474 static bool hci_pairing_active(hci_connection_t * hci_connection){ 475 return (hci_connection->authentication_flags & AUTH_FLAG_PAIRING_ACTIVE_MASK) != 0; 476 } 477 478 static void hci_pairing_started(hci_connection_t * hci_connection, bool ssp){ 479 if (hci_pairing_active(hci_connection)) return; 480 if (ssp){ 481 hci_connection->authentication_flags |= AUTH_FLAG_SSP_PAIRING_ACTIVE; 482 } else { 483 hci_connection->authentication_flags |= AUTH_FLAG_LEGACY_PAIRING_ACTIVE; 484 } 485 // if we are initiator, we have sent an HCI Authenticate Request 486 bool initiator = (hci_connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0; 487 488 // if we are responder, use minimal service security level as required level 489 if (!initiator){ 490 hci_connection->requested_security_level = (gap_security_level_t) btstack_max((uint32_t) hci_connection->requested_security_level, (uint32_t) hci_stack->gap_minimal_service_security_level); 491 } 492 493 log_info("pairing started, ssp %u, initiator %u, requested level %u", (int) ssp, (int) initiator, hci_connection->requested_security_level); 494 495 uint8_t event[12]; 496 event[0] = GAP_EVENT_PAIRING_STARTED; 497 event[1] = 10; 498 little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle); 499 reverse_bd_addr(hci_connection->address, &event[4]); 500 event[10] = (uint8_t) ssp; 501 event[11] = (uint8_t) initiator; 502 hci_emit_event(event, sizeof(event), 1); 503 } 504 505 static void hci_pairing_complete(hci_connection_t * hci_connection, uint8_t status){ 506 hci_connection->requested_security_level = LEVEL_0; 507 if (!hci_pairing_active(hci_connection)) return; 508 hci_connection->authentication_flags &= ~AUTH_FLAG_PAIRING_ACTIVE_MASK; 509 #ifdef ENABLE_CLASSIC_PAIRING_OOB 510 hci_connection->classic_oob_c_192 = NULL; 511 hci_connection->classic_oob_r_192 = NULL; 512 hci_connection->classic_oob_c_256 = NULL; 513 hci_connection->classic_oob_r_256 = NULL; 514 #endif 515 log_info("pairing complete, status %02x", status); 516 517 uint8_t event[11]; 518 event[0] = GAP_EVENT_PAIRING_COMPLETE; 519 event[1] = 9; 520 little_endian_store_16(event, 2, (uint16_t) hci_connection->con_handle); 521 reverse_bd_addr(hci_connection->address, &event[4]); 522 event[10] = status; 523 hci_emit_event(event, sizeof(event), 1); 524 525 // emit dedicated bonding done on failure, otherwise verify that connection can be encrypted 526 if ((status != ERROR_CODE_SUCCESS) && ((hci_connection->bonding_flags & BONDING_DEDICATED) != 0)){ 527 hci_connection->bonding_flags &= ~BONDING_DEDICATED; 528 hci_connection->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 529 hci_connection->bonding_status = status; 530 } 531 } 532 533 bool hci_authentication_active_for_handle(hci_con_handle_t handle){ 534 hci_connection_t * conn = hci_connection_for_handle(handle); 535 if (!conn) return false; 536 return hci_pairing_active(conn); 537 } 538 539 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){ 540 if (!hci_stack->link_key_db) return; 541 log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr)); 542 hci_stack->link_key_db->delete_link_key(addr); 543 } 544 545 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){ 546 if (!hci_stack->link_key_db) return; 547 log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type); 548 hci_stack->link_key_db->put_link_key(addr, link_key, type); 549 } 550 551 bool gap_get_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t * type){ 552 if (!hci_stack->link_key_db) return false; 553 int result = hci_stack->link_key_db->get_link_key(addr, link_key, type) != 0; 554 log_info("link key for %s available %u, type %u", bd_addr_to_str(addr), result, (int) *type); 555 return result; 556 } 557 558 void gap_delete_all_link_keys(void){ 559 bd_addr_t addr; 560 link_key_t link_key; 561 link_key_type_t type; 562 btstack_link_key_iterator_t it; 563 int ok = gap_link_key_iterator_init(&it); 564 if (!ok) { 565 log_error("could not initialize iterator"); 566 return; 567 } 568 while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){ 569 gap_drop_link_key_for_bd_addr(addr); 570 } 571 gap_link_key_iterator_done(&it); 572 } 573 574 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){ 575 if (!hci_stack->link_key_db) return 0; 576 if (!hci_stack->link_key_db->iterator_init) return 0; 577 return hci_stack->link_key_db->iterator_init(it); 578 } 579 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){ 580 if (!hci_stack->link_key_db) return 0; 581 return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type); 582 } 583 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){ 584 if (!hci_stack->link_key_db) return; 585 hci_stack->link_key_db->iterator_done(it); 586 } 587 #endif 588 589 static bool hci_is_le_connection_type(bd_addr_type_t address_type){ 590 switch (address_type){ 591 case BD_ADDR_TYPE_LE_PUBLIC: 592 case BD_ADDR_TYPE_LE_RANDOM: 593 case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC: 594 case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM: 595 return true; 596 default: 597 return false; 598 } 599 } 600 601 static int hci_is_le_connection(hci_connection_t * connection){ 602 return hci_is_le_connection_type(connection->address_type); 603 } 604 605 /** 606 * count connections 607 */ 608 static int nr_hci_connections(void){ 609 int count = 0; 610 btstack_linked_item_t *it; 611 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL ; it = it->next){ 612 count++; 613 } 614 return count; 615 } 616 617 uint16_t hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){ 618 619 unsigned int num_packets_sent_classic = 0; 620 unsigned int num_packets_sent_le = 0; 621 622 btstack_linked_item_t *it; 623 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 624 hci_connection_t * connection = (hci_connection_t *) it; 625 if (hci_is_le_connection(connection)){ 626 num_packets_sent_le += connection->num_packets_sent; 627 } 628 if (connection->address_type == BD_ADDR_TYPE_ACL){ 629 num_packets_sent_classic += connection->num_packets_sent; 630 } 631 } 632 log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num); 633 int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic; 634 int free_slots_le = 0; 635 636 if (free_slots_classic < 0){ 637 log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num); 638 return 0; 639 } 640 641 if (hci_stack->le_acl_packets_total_num){ 642 // if we have LE slots, they are used 643 free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le; 644 if (free_slots_le < 0){ 645 log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num); 646 return 0; 647 } 648 } else { 649 // otherwise, classic slots are used for LE, too 650 free_slots_classic -= num_packets_sent_le; 651 if (free_slots_classic < 0){ 652 log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num); 653 return 0; 654 } 655 } 656 657 switch (address_type){ 658 case BD_ADDR_TYPE_UNKNOWN: 659 log_error("hci_number_free_acl_slots: unknown address type"); 660 return 0; 661 662 case BD_ADDR_TYPE_ACL: 663 return (uint16_t) free_slots_classic; 664 665 default: 666 if (hci_stack->le_acl_packets_total_num > 0){ 667 return (uint16_t) free_slots_le; 668 } 669 return (uint16_t) free_slots_classic; 670 } 671 } 672 673 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){ 674 // get connection type 675 hci_connection_t * connection = hci_connection_for_handle(con_handle); 676 if (!connection){ 677 log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle); 678 return 0; 679 } 680 return hci_number_free_acl_slots_for_connection_type(connection->address_type); 681 } 682 683 #ifdef ENABLE_CLASSIC 684 static int hci_number_free_sco_slots(void){ 685 unsigned int num_sco_packets_sent = 0; 686 btstack_linked_item_t *it; 687 if (hci_stack->synchronous_flow_control_enabled){ 688 // explicit flow control 689 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 690 hci_connection_t * connection = (hci_connection_t *) it; 691 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 692 num_sco_packets_sent += connection->num_packets_sent; 693 } 694 if (num_sco_packets_sent > hci_stack->sco_packets_total_num){ 695 log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num); 696 return 0; 697 } 698 return hci_stack->sco_packets_total_num - num_sco_packets_sent; 699 } else { 700 // implicit flow control -- TODO 701 int num_ready = 0; 702 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 703 hci_connection_t * connection = (hci_connection_t *) it; 704 if (connection->address_type != BD_ADDR_TYPE_SCO) continue; 705 if (connection->sco_tx_ready == 0) continue; 706 num_ready++; 707 } 708 return num_ready; 709 } 710 } 711 #endif 712 713 // only used to send HCI Host Number Completed Packets 714 static int hci_can_send_comand_packet_transport(void){ 715 if (hci_stack->hci_packet_buffer_reserved) return 0; 716 717 // check for async hci transport implementations 718 if (hci_stack->hci_transport->can_send_packet_now){ 719 if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){ 720 return 0; 721 } 722 } 723 return 1; 724 } 725 726 // new functions replacing hci_can_send_packet_now[_using_packet_buffer] 727 bool hci_can_send_command_packet_now(void){ 728 if (hci_can_send_comand_packet_transport() == 0) return false; 729 return hci_stack->num_cmd_packets > 0u; 730 } 731 732 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){ 733 // check for async hci transport implementations 734 if (!hci_stack->hci_transport->can_send_packet_now) return true; 735 return hci_stack->hci_transport->can_send_packet_now(packet_type); 736 } 737 738 static bool hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){ 739 if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false; 740 return hci_number_free_acl_slots_for_connection_type(address_type) > 0; 741 } 742 743 bool hci_can_send_acl_le_packet_now(void){ 744 if (hci_stack->hci_packet_buffer_reserved) return false; 745 return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC); 746 } 747 748 bool hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) { 749 if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return false; 750 return hci_number_free_acl_slots_for_handle(con_handle) > 0; 751 } 752 753 bool hci_can_send_acl_packet_now(hci_con_handle_t con_handle){ 754 if (hci_stack->hci_packet_buffer_reserved) return false; 755 return hci_can_send_prepared_acl_packet_now(con_handle); 756 } 757 758 #ifdef ENABLE_CLASSIC 759 bool hci_can_send_acl_classic_packet_now(void){ 760 if (hci_stack->hci_packet_buffer_reserved) return false; 761 return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_ACL); 762 } 763 764 bool hci_can_send_prepared_sco_packet_now(void){ 765 if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return false; 766 if (hci_have_usb_transport()){ 767 return hci_stack->sco_can_send_now; 768 } else { 769 return hci_number_free_sco_slots() > 0; 770 } 771 } 772 773 bool hci_can_send_sco_packet_now(void){ 774 if (hci_stack->hci_packet_buffer_reserved) return false; 775 return hci_can_send_prepared_sco_packet_now(); 776 } 777 778 void hci_request_sco_can_send_now_event(void){ 779 hci_stack->sco_waiting_for_can_send_now = 1; 780 hci_notify_if_sco_can_send_now(); 781 } 782 #endif 783 784 // used for internal checks in l2cap.c 785 bool hci_is_packet_buffer_reserved(void){ 786 return hci_stack->hci_packet_buffer_reserved; 787 } 788 789 // reserves outgoing packet buffer. 790 // @return 1 if successful 791 bool hci_reserve_packet_buffer(void){ 792 if (hci_stack->hci_packet_buffer_reserved) { 793 log_error("hci_reserve_packet_buffer called but buffer already reserved"); 794 return false; 795 } 796 hci_stack->hci_packet_buffer_reserved = true; 797 return true; 798 } 799 800 void hci_release_packet_buffer(void){ 801 hci_stack->hci_packet_buffer_reserved = false; 802 } 803 804 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 805 static int hci_transport_synchronous(void){ 806 return hci_stack->hci_transport->can_send_packet_now == NULL; 807 } 808 809 // used for debugging 810 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 811 static void hci_controller_dump_packets(void){ 812 // format: "{handle:04x}:{count:02d} " 813 char summaries[3][7 * 8 + 1]; 814 uint16_t totals[3]; 815 uint8_t index; 816 for (index = 0 ; index < 3 ; index++){ 817 summaries[index][0] = 0; 818 totals[index] = 0; 819 } 820 btstack_linked_item_t *it; 821 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 822 hci_connection_t * connection = (hci_connection_t *) it; 823 switch (connection->address_type){ 824 case BD_ADDR_TYPE_ACL: 825 index = 0; 826 break; 827 case BD_ADDR_TYPE_SCO: 828 index = 2; 829 break; 830 default: 831 index = 1; 832 break; 833 } 834 totals[index] += connection->num_packets_sent; 835 char item_text[10]; 836 sprintf(item_text, "%04x:%02d ", connection->con_handle,connection->num_packets_sent); 837 btstack_strcat(summaries[index], sizeof(summaries[0]), item_text); 838 } 839 for (index = 0 ; index < 3 ; index++){ 840 if (summaries[index][0] == 0){ 841 summaries[index][0] = '-'; 842 summaries[index][1] = 0; 843 } 844 } 845 log_info("Controller ACL BR/EDR: %s total %u / LE: %s total %u / SCO: %s total %u", summaries[0], totals[0], summaries[1], totals[1], summaries[2], totals[2]); 846 } 847 #endif 848 849 static uint8_t hci_send_acl_packet_fragments(hci_connection_t *connection){ 850 851 // log_info("hci_send_acl_packet_fragments %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle); 852 853 // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers 854 uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length; 855 if (hci_is_le_connection(connection) && (hci_stack->le_data_packets_length > 0u)){ 856 max_acl_data_packet_length = hci_stack->le_data_packets_length; 857 } 858 859 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS 860 if (hci_is_le_connection(connection) && (connection->le_max_tx_octets < max_acl_data_packet_length)){ 861 max_acl_data_packet_length = connection->le_max_tx_octets; 862 } 863 #endif 864 865 log_debug("hci_send_acl_packet_fragments entered"); 866 867 uint8_t status = ERROR_CODE_SUCCESS; 868 // multiple packets could be send on a synchronous HCI transport 869 while (true){ 870 871 log_debug("hci_send_acl_packet_fragments loop entered"); 872 873 // get current data 874 const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4u; 875 int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos; 876 bool more_fragments = false; 877 878 // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 879 if (current_acl_data_packet_length > max_acl_data_packet_length){ 880 more_fragments = true; 881 current_acl_data_packet_length = max_acl_data_packet_length; 882 } 883 884 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 885 if (acl_header_pos > 0u){ 886 uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 887 handle_and_flags = (handle_and_flags & 0xcfffu) | (1u << 12u); 888 little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags); 889 } 890 891 // update header len 892 little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2u, current_acl_data_packet_length); 893 894 // count packet 895 connection->num_packets_sent++; 896 log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", (int) more_fragments); 897 898 // update state for next fragment (if any) as "transport done" might be sent during send_packet already 899 if (more_fragments){ 900 // update start of next fragment to send 901 hci_stack->acl_fragmentation_pos += current_acl_data_packet_length; 902 } else { 903 // done 904 hci_stack->acl_fragmentation_pos = 0; 905 hci_stack->acl_fragmentation_total_size = 0; 906 } 907 908 // send packet 909 uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos]; 910 const int size = current_acl_data_packet_length + 4; 911 hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size); 912 hci_stack->acl_fragmentation_tx_active = 1; 913 int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 914 if (err != 0){ 915 // no error from HCI Transport expected 916 status = ERROR_CODE_HARDWARE_FAILURE; 917 } 918 919 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 920 hci_controller_dump_packets(); 921 #endif 922 923 log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", (int) more_fragments); 924 925 // done yet? 926 if (!more_fragments) break; 927 928 // can send more? 929 if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return status; 930 } 931 932 log_debug("hci_send_acl_packet_fragments loop over"); 933 934 // release buffer now for synchronous transport 935 if (hci_transport_synchronous()){ 936 hci_stack->acl_fragmentation_tx_active = 0; 937 hci_release_packet_buffer(); 938 hci_emit_transport_packet_sent(); 939 } 940 941 return status; 942 } 943 944 // pre: caller has reserved the packet buffer 945 uint8_t hci_send_acl_packet_buffer(int size){ 946 btstack_assert(hci_stack->hci_packet_buffer_reserved); 947 948 uint8_t * packet = hci_stack->hci_packet_buffer; 949 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 950 951 // check for free places on Bluetooth module 952 if (!hci_can_send_prepared_acl_packet_now(con_handle)) { 953 log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller"); 954 hci_release_packet_buffer(); 955 hci_emit_transport_packet_sent(); 956 return BTSTACK_ACL_BUFFERS_FULL; 957 } 958 959 hci_connection_t *connection = hci_connection_for_handle( con_handle); 960 if (!connection) { 961 log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle); 962 hci_release_packet_buffer(); 963 hci_emit_transport_packet_sent(); 964 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 965 } 966 967 #ifdef ENABLE_CLASSIC 968 hci_connection_timestamp(connection); 969 #endif 970 971 // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size); 972 973 // setup data 974 hci_stack->acl_fragmentation_total_size = size; 975 hci_stack->acl_fragmentation_pos = 4; // start of L2CAP packet 976 977 return hci_send_acl_packet_fragments(connection); 978 } 979 980 #ifdef ENABLE_CLASSIC 981 // pre: caller has reserved the packet buffer 982 uint8_t hci_send_sco_packet_buffer(int size){ 983 btstack_assert(hci_stack->hci_packet_buffer_reserved); 984 985 uint8_t * packet = hci_stack->hci_packet_buffer; 986 987 // skip checks in loopback mode 988 if (!hci_stack->loopback_mode){ 989 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); // same for ACL and SCO 990 991 // check for free places on Bluetooth module 992 if (!hci_can_send_prepared_sco_packet_now()) { 993 log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller"); 994 hci_release_packet_buffer(); 995 hci_emit_transport_packet_sent(); 996 return BTSTACK_ACL_BUFFERS_FULL; 997 } 998 999 // track send packet in connection struct 1000 hci_connection_t *connection = hci_connection_for_handle( con_handle); 1001 if (!connection) { 1002 log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle); 1003 hci_release_packet_buffer(); 1004 hci_emit_transport_packet_sent(); 1005 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 1006 } 1007 1008 if (hci_have_usb_transport()){ 1009 // token used 1010 hci_stack->sco_can_send_now = false; 1011 } else { 1012 if (hci_stack->synchronous_flow_control_enabled){ 1013 connection->num_packets_sent++; 1014 } else { 1015 connection->sco_tx_ready--; 1016 } 1017 } 1018 } 1019 1020 hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size); 1021 1022 #ifdef HAVE_SCO_TRANSPORT 1023 hci_stack->sco_transport->send_packet(packet, size); 1024 hci_release_packet_buffer(); 1025 hci_emit_transport_packet_sent(); 1026 1027 return 0; 1028 #else 1029 int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size); 1030 if (hci_transport_synchronous()){ 1031 hci_release_packet_buffer(); 1032 hci_emit_transport_packet_sent(); 1033 } 1034 1035 if (err != 0){ 1036 return ERROR_CODE_HARDWARE_FAILURE; 1037 } 1038 return ERROR_CODE_SUCCESS; 1039 #endif 1040 } 1041 #endif 1042 1043 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 1044 static uint8_t hci_send_iso_packet_fragments(void){ 1045 1046 uint16_t max_iso_data_packet_length = hci_stack->le_iso_packets_length; 1047 uint8_t status = ERROR_CODE_SUCCESS; 1048 // multiple packets could be send on a synchronous HCI transport 1049 while (true){ 1050 1051 // get current data 1052 const uint16_t iso_header_pos = hci_stack->iso_fragmentation_pos - 4u; 1053 int current_iso_data_packet_length = hci_stack->iso_fragmentation_total_size - hci_stack->iso_fragmentation_pos; 1054 bool more_fragments = false; 1055 1056 // if ISO packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 1057 if (current_iso_data_packet_length > max_iso_data_packet_length){ 1058 more_fragments = true; 1059 current_iso_data_packet_length = max_iso_data_packet_length; 1060 } 1061 1062 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 1063 uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1064 uint8_t pb_flags; 1065 if (iso_header_pos == 0u){ 1066 // first fragment, keep TS field 1067 pb_flags = more_fragments ? 0x00 : 0x02; 1068 handle_and_flags = (handle_and_flags & 0x4fffu) | (pb_flags << 12u); 1069 } else { 1070 // later fragment, drop TS field 1071 pb_flags = more_fragments ? 0x01 : 0x03; 1072 handle_and_flags = (handle_and_flags & 0x0fffu) | (pb_flags << 12u); 1073 } 1074 little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos, handle_and_flags); 1075 1076 // update header len 1077 little_endian_store_16(hci_stack->hci_packet_buffer, iso_header_pos + 2u, current_iso_data_packet_length); 1078 1079 // update state for next fragment (if any) as "transport done" might be sent during send_packet already 1080 if (more_fragments){ 1081 // update start of next fragment to send 1082 hci_stack->iso_fragmentation_pos += current_iso_data_packet_length; 1083 } else { 1084 // done 1085 hci_stack->iso_fragmentation_pos = 0; 1086 hci_stack->iso_fragmentation_total_size = 0; 1087 } 1088 1089 // send packet 1090 uint8_t * packet = &hci_stack->hci_packet_buffer[iso_header_pos]; 1091 const int size = current_iso_data_packet_length + 4; 1092 hci_dump_packet(HCI_ISO_DATA_PACKET, 0, packet, size); 1093 hci_stack->iso_fragmentation_tx_active = true; 1094 int err = hci_stack->hci_transport->send_packet(HCI_ISO_DATA_PACKET, packet, size); 1095 if (err != 0){ 1096 // no error from HCI Transport expected 1097 status = ERROR_CODE_HARDWARE_FAILURE; 1098 } 1099 1100 // done yet? 1101 if (!more_fragments) break; 1102 1103 // can send more? 1104 if (!hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)) return false; 1105 } 1106 1107 // release buffer now for synchronous transport 1108 if (hci_transport_synchronous()){ 1109 hci_stack->iso_fragmentation_tx_active = false; 1110 hci_release_packet_buffer(); 1111 hci_emit_transport_packet_sent(); 1112 } 1113 1114 return status; 1115 } 1116 1117 uint8_t hci_send_iso_packet_buffer(uint16_t size){ 1118 btstack_assert(hci_stack->hci_packet_buffer_reserved); 1119 1120 hci_con_handle_t con_handle = (hci_con_handle_t) little_endian_read_16(hci_stack->hci_packet_buffer, 0) & 0xfff; 1121 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(con_handle); 1122 if (iso_stream == NULL){ 1123 hci_release_packet_buffer(); 1124 hci_iso_notify_can_send_now(); 1125 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 1126 } 1127 1128 // TODO: check for space on controller 1129 1130 // skip iso packets if needed 1131 if (iso_stream->num_packets_to_skip > 0){ 1132 iso_stream->num_packets_to_skip--; 1133 // pretend it was processed and trigger next one 1134 hci_release_packet_buffer(); 1135 hci_iso_notify_can_send_now(); 1136 return ERROR_CODE_SUCCESS; 1137 } 1138 1139 // track outgoing packet sent 1140 log_info("Outgoing ISO packet for con handle 0x%04x", con_handle); 1141 iso_stream->num_packets_sent++; 1142 1143 // setup data 1144 hci_stack->iso_fragmentation_total_size = size; 1145 hci_stack->iso_fragmentation_pos = 4; // start of L2CAP packet 1146 1147 return hci_send_iso_packet_fragments(); 1148 } 1149 #endif 1150 1151 static void acl_handler(uint8_t *packet, uint16_t size){ 1152 1153 // get info 1154 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 1155 hci_connection_t *conn = hci_connection_for_handle(con_handle); 1156 uint8_t acl_flags = READ_ACL_FLAGS(packet); 1157 uint16_t acl_length = READ_ACL_LENGTH(packet); 1158 1159 // ignore non-registered handle 1160 if (!conn){ 1161 log_error("acl_handler called with non-registered handle %u!" , con_handle); 1162 return; 1163 } 1164 1165 // assert packet is complete 1166 if ((acl_length + 4u) != size){ 1167 log_error("acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4); 1168 return; 1169 } 1170 1171 #ifdef ENABLE_CLASSIC 1172 // update idle timestamp 1173 hci_connection_timestamp(conn); 1174 #endif 1175 1176 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 1177 hci_stack->host_completed_packets = 1; 1178 conn->num_packets_completed++; 1179 #endif 1180 1181 // handle different packet types 1182 switch (acl_flags & 0x03u) { 1183 1184 case 0x01: // continuation fragment 1185 1186 // sanity checks 1187 if (conn->acl_recombination_pos == 0u) { 1188 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle); 1189 return; 1190 } 1191 if ((conn->acl_recombination_pos + acl_length) > (4u + HCI_ACL_BUFFER_SIZE)){ 1192 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x", 1193 conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 1194 conn->acl_recombination_pos = 0; 1195 return; 1196 } 1197 1198 // append fragment payload (header already stored) 1199 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], 1200 &packet[4], acl_length); 1201 conn->acl_recombination_pos += acl_length; 1202 1203 // forward complete L2CAP packet if complete. 1204 if (conn->acl_recombination_pos >= (conn->acl_recombination_length + 4u + 4u)){ // pos already incl. ACL header 1205 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos); 1206 // reset recombination buffer 1207 conn->acl_recombination_length = 0; 1208 conn->acl_recombination_pos = 0; 1209 } 1210 break; 1211 1212 case 0x02: { // first fragment 1213 1214 // sanity check 1215 if (conn->acl_recombination_pos) { 1216 // we just received the first fragment, but still have data. Only warn if the packet wasn't a flushable packet 1217 if ((conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE+1] >> 4) != 0x02){ 1218 log_error( "ACL First Fragment but %u bytes in buffer for handle 0x%02x, dropping stale fragments", conn->acl_recombination_pos, con_handle); 1219 } 1220 conn->acl_recombination_pos = 0; 1221 } 1222 1223 // peek into L2CAP packet! 1224 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 1225 1226 // compare fragment size to L2CAP packet size 1227 if (acl_length >= (l2cap_length + 4u)){ 1228 // forward fragment as L2CAP packet 1229 hci_emit_acl_packet(packet, acl_length + 4u); 1230 } else { 1231 1232 if (acl_length > HCI_ACL_BUFFER_SIZE){ 1233 log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x", 1234 4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle); 1235 return; 1236 } 1237 1238 // store first fragment and tweak acl length for complete package 1239 (void)memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], 1240 packet, acl_length + 4u); 1241 conn->acl_recombination_pos = acl_length + 4u; 1242 conn->acl_recombination_length = l2cap_length; 1243 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2u, l2cap_length +4u); 1244 } 1245 break; 1246 1247 } 1248 default: 1249 log_error( "acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03); 1250 return; 1251 } 1252 1253 // execute main loop 1254 hci_run(); 1255 } 1256 1257 static void hci_connection_stop_timer(hci_connection_t * conn){ 1258 btstack_run_loop_remove_timer(&conn->timeout); 1259 #ifdef ENABLE_CLASSIC 1260 btstack_run_loop_remove_timer(&conn->timeout_sco); 1261 #endif 1262 } 1263 1264 static void hci_shutdown_connection(hci_connection_t *conn){ 1265 log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address)); 1266 1267 #ifdef ENABLE_CLASSIC 1268 #if defined(ENABLE_SCO_OVER_HCI) || defined(HAVE_SCO_TRANSPORT) 1269 bd_addr_type_t addr_type = conn->address_type; 1270 #endif 1271 #ifdef HAVE_SCO_TRANSPORT 1272 hci_con_handle_t con_handle = conn->con_handle; 1273 #endif 1274 #endif 1275 1276 hci_connection_stop_timer(conn); 1277 1278 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 1279 btstack_memory_hci_connection_free( conn ); 1280 1281 // now it's gone 1282 hci_emit_nr_connections_changed(); 1283 1284 #ifdef ENABLE_CLASSIC 1285 #ifdef ENABLE_SCO_OVER_HCI 1286 // update SCO 1287 if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->hci_transport != NULL) && (hci_stack->hci_transport->set_sco_config != NULL)){ 1288 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections()); 1289 } 1290 #endif 1291 #ifdef HAVE_SCO_TRANSPORT 1292 if ((addr_type == BD_ADDR_TYPE_SCO) && (hci_stack->sco_transport != NULL)){ 1293 hci_stack->sco_transport->close(con_handle); 1294 } 1295 #endif 1296 #endif 1297 } 1298 1299 #ifdef ENABLE_CLASSIC 1300 1301 static const uint16_t packet_type_sizes[] = { 1302 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 1303 HCI_ACL_DH1_SIZE, 0, 0, 0, 1304 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 1305 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 1306 }; 1307 static const uint8_t packet_type_feature_requirement_bit[] = { 1308 0, // 3 slot packets 1309 1, // 5 slot packets 1310 25, // EDR 2 mpbs 1311 26, // EDR 3 mbps 1312 39, // 3 slot EDR packts 1313 40, // 5 slot EDR packet 1314 }; 1315 static const uint16_t packet_type_feature_packet_mask[] = { 1316 0x0f00, // 3 slot packets 1317 0xf000, // 5 slot packets 1318 0x1102, // EDR 2 mpbs 1319 0x2204, // EDR 3 mbps 1320 0x0300, // 3 slot EDR packts 1321 0x3000, // 5 slot EDR packet 1322 }; 1323 1324 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 1325 // enable packet types based on size 1326 uint16_t packet_types = 0; 1327 unsigned int i; 1328 for (i=0;i<16;i++){ 1329 if (packet_type_sizes[i] == 0) continue; 1330 if (packet_type_sizes[i] <= buffer_size){ 1331 packet_types |= 1 << i; 1332 } 1333 } 1334 // disable packet types due to missing local supported features 1335 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 1336 unsigned int bit_idx = packet_type_feature_requirement_bit[i]; 1337 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 1338 if (feature_set) continue; 1339 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 1340 packet_types &= ~packet_type_feature_packet_mask[i]; 1341 } 1342 // flip bits for "may not be used" 1343 packet_types ^= 0x3306; 1344 return packet_types; 1345 } 1346 1347 uint16_t hci_usable_acl_packet_types(void){ 1348 return hci_stack->packet_types; 1349 } 1350 #endif 1351 1352 uint8_t* hci_get_outgoing_packet_buffer(void){ 1353 // hci packet buffer is >= acl data packet length 1354 return hci_stack->hci_packet_buffer; 1355 } 1356 1357 uint16_t hci_max_acl_data_packet_length(void){ 1358 return hci_stack->acl_data_packet_length; 1359 } 1360 1361 #ifdef ENABLE_CLASSIC 1362 bool hci_extended_sco_link_supported(void){ 1363 // No. 31, byte 3, bit 7 1364 return (hci_stack->local_supported_features[3] & (1 << 7)) != 0; 1365 } 1366 #endif 1367 1368 bool hci_non_flushable_packet_boundary_flag_supported(void){ 1369 // No. 54, byte 6, bit 6 1370 return (hci_stack->local_supported_features[6u] & (1u << 6u)) != 0u; 1371 } 1372 1373 #ifdef ENABLE_CLASSIC 1374 static int gap_ssp_supported(void){ 1375 // No. 51, byte 6, bit 3 1376 return (hci_stack->local_supported_features[6u] & (1u << 3u)) != 0u; 1377 } 1378 #endif 1379 1380 static int hci_classic_supported(void){ 1381 #ifdef ENABLE_CLASSIC 1382 // No. 37, byte 4, bit 5, = No BR/EDR Support 1383 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 1384 #else 1385 return 0; 1386 #endif 1387 } 1388 1389 static int hci_le_supported(void){ 1390 #ifdef ENABLE_BLE 1391 // No. 37, byte 4, bit 6 = LE Supported (Controller) 1392 return (hci_stack->local_supported_features[4u] & (1u << 6u)) != 0u; 1393 #else 1394 return 0; 1395 #endif 1396 } 1397 1398 static bool hci_command_supported(uint8_t command_index){ 1399 return (hci_stack->local_supported_commands & (1LU << command_index)) != 0; 1400 } 1401 1402 #ifdef ENABLE_BLE 1403 1404 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 1405 static bool hci_extended_advertising_supported(void){ 1406 return hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_EXTENDED_ADVERTISING_ENABLE); 1407 } 1408 #endif 1409 1410 static void hci_get_own_address_for_addr_type(uint8_t own_addr_type, bd_addr_t own_addr){ 1411 if (own_addr_type == BD_ADDR_TYPE_LE_PUBLIC){ 1412 (void)memcpy(own_addr, hci_stack->local_bd_addr, 6); 1413 } else { 1414 (void)memcpy(own_addr, hci_stack->le_random_address, 6); 1415 } 1416 } 1417 1418 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){ 1419 *addr_type = hci_stack->le_own_addr_type; 1420 hci_get_own_address_for_addr_type(hci_stack->le_own_addr_type, addr); 1421 } 1422 1423 #ifdef ENABLE_LE_PERIPHERAL 1424 void gap_le_get_own_advertisements_address(uint8_t * addr_type, bd_addr_t addr){ 1425 *addr_type = hci_stack->le_advertisements_own_addr_type; 1426 hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, addr); 1427 }; 1428 #endif 1429 1430 #ifdef ENABLE_LE_CENTRAL 1431 1432 /** 1433 * @brief Get own addr type and address used for LE connections (Central) 1434 */ 1435 void gap_le_get_own_connection_address(uint8_t * addr_type, bd_addr_t addr){ 1436 *addr_type = hci_stack->le_connection_own_addr_type; 1437 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, addr); 1438 } 1439 1440 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){ 1441 1442 uint16_t offset = 3; 1443 uint8_t num_reports = packet[offset]; 1444 offset += 1; 1445 1446 uint16_t i; 1447 uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var 1448 for (i=0; (i<num_reports) && (offset < size);i++){ 1449 // sanity checks on data_length: 1450 uint8_t data_length = packet[offset + 8]; 1451 if (data_length > LE_ADVERTISING_DATA_SIZE) return; 1452 if ((offset + 9u + data_length + 1u) > size) return; 1453 // setup event 1454 uint8_t event_size = 10u + data_length; 1455 uint16_t pos = 0; 1456 event[pos++] = GAP_EVENT_ADVERTISING_REPORT; 1457 event[pos++] = event_size; 1458 (void)memcpy(&event[pos], &packet[offset], 1 + 1 + 6); // event type + address type + address 1459 offset += 8; 1460 pos += 8; 1461 event[pos++] = packet[offset + 1 + data_length]; // rssi 1462 event[pos++] = data_length; 1463 offset++; 1464 (void)memcpy(&event[pos], &packet[offset], data_length); 1465 pos += data_length; 1466 offset += data_length + 1u; // rssi 1467 hci_emit_event(event, pos, 1); 1468 } 1469 } 1470 1471 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 1472 void le_handle_extended_advertisement_report(uint8_t *packet, uint16_t size) { 1473 uint16_t offset = 3; 1474 uint8_t num_reports = packet[offset++]; 1475 uint8_t event[2 + 255]; // use upper bound to avoid var size automatic var 1476 uint8_t i; 1477 for (i=0; (i<num_reports) && (offset < size);i++){ 1478 // sanity checks on data_length: 1479 uint16_t data_length = packet[offset + 23]; 1480 if (data_length > LE_ADVERTISING_DATA_SIZE) return; 1481 if ((offset + 24u + data_length) > size) return; 1482 uint16_t event_type = little_endian_read_16(packet, offset); 1483 offset += 2; 1484 if ((event_type & 0x10) != 0) { 1485 // setup legacy event 1486 uint8_t legacy_event_type; 1487 switch (event_type){ 1488 case 0b0010011: 1489 // ADV_IND 1490 legacy_event_type = 0; 1491 break; 1492 case 0b0010101: 1493 // ADV_DIRECT_IND 1494 legacy_event_type = 1; 1495 break; 1496 case 0b0010010: 1497 // ADV_SCAN_IND 1498 legacy_event_type = 2; 1499 break; 1500 case 0b0010000: 1501 // ADV_NONCONN_IND 1502 legacy_event_type = 3; 1503 break; 1504 case 0b0011011: 1505 case 0b0011010: 1506 // SCAN_RSP 1507 legacy_event_type = 4; 1508 break; 1509 default: 1510 legacy_event_type = 0; 1511 break; 1512 } 1513 uint16_t pos = 0; 1514 event[pos++] = GAP_EVENT_ADVERTISING_REPORT; 1515 event[pos++] = 10u + data_length; 1516 event[pos++] = legacy_event_type; 1517 // copy address type + address 1518 (void) memcpy(&event[pos], &packet[offset], 1 + 6); 1519 offset += 7; 1520 pos += 7; 1521 // skip primary_phy, secondary_phy, advertising_sid, tx_power 1522 offset += 4; 1523 // copy rssi 1524 event[pos++] = packet[offset++]; 1525 // skip periodic advertising interval and direct address 1526 offset += 9; 1527 // copy data len + data; 1528 (void) memcpy(&event[pos], &packet[offset], 1 + data_length); 1529 pos += 1 +data_length; 1530 offset += 1+ data_length; 1531 hci_emit_event(event, pos, 1); 1532 } else { 1533 event[0] = GAP_EVENT_EXTENDED_ADVERTISING_REPORT; 1534 uint8_t report_len = 24 + data_length; 1535 event[1] = report_len; 1536 little_endian_store_16(event, 2, event_type); 1537 memcpy(&event[4], &packet[offset], report_len); 1538 offset += report_len; 1539 hci_emit_event(event, 2 + report_len, 1); 1540 } 1541 } 1542 } 1543 #endif 1544 1545 #endif 1546 #endif 1547 1548 #ifdef ENABLE_BLE 1549 #ifdef ENABLE_LE_PERIPHERAL 1550 static void hci_update_advertisements_enabled_for_current_roles(void){ 1551 if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ENABLED) != 0){ 1552 // get number of active le slave connections 1553 int num_slave_connections = 0; 1554 btstack_linked_list_iterator_t it; 1555 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 1556 while (btstack_linked_list_iterator_has_next(&it)){ 1557 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 1558 log_info("state %u, role %u, le_con %u", con->state, con->role, hci_is_le_connection(con)); 1559 if (con->state != OPEN) continue; 1560 if (con->role != HCI_ROLE_SLAVE) continue; 1561 if (!hci_is_le_connection(con)) continue; 1562 num_slave_connections++; 1563 } 1564 log_info("Num LE Peripheral roles: %u of %u", num_slave_connections, hci_stack->le_max_number_peripheral_connections); 1565 hci_stack->le_advertisements_enabled_for_current_roles = num_slave_connections < hci_stack->le_max_number_peripheral_connections; 1566 } else { 1567 hci_stack->le_advertisements_enabled_for_current_roles = false; 1568 } 1569 } 1570 #endif 1571 #endif 1572 1573 #ifdef ENABLE_CLASSIC 1574 static void gap_run_set_local_name(void){ 1575 hci_reserve_packet_buffer(); 1576 uint8_t * packet = hci_stack->hci_packet_buffer; 1577 // construct HCI Command and send 1578 uint16_t opcode = hci_write_local_name.opcode; 1579 hci_stack->last_cmd_opcode = opcode; 1580 packet[0] = opcode & 0xff; 1581 packet[1] = opcode >> 8; 1582 packet[2] = DEVICE_NAME_LEN; 1583 memset(&packet[3], 0, DEVICE_NAME_LEN); 1584 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name); 1585 uint16_t bytes_to_copy = btstack_min(name_len, DEVICE_NAME_LEN); 1586 // if shorter than DEVICE_NAME_LEN, it's implicitly NULL-terminated by memset call 1587 (void)memcpy(&packet[3], hci_stack->local_name, bytes_to_copy); 1588 // expand '00:00:00:00:00:00' in name with bd_addr 1589 btstack_replace_bd_addr_placeholder(&packet[3], bytes_to_copy, hci_stack->local_bd_addr); 1590 hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN); 1591 } 1592 1593 static void gap_run_set_eir_data(void){ 1594 hci_reserve_packet_buffer(); 1595 uint8_t * packet = hci_stack->hci_packet_buffer; 1596 // construct HCI Command in-place and send 1597 uint16_t opcode = hci_write_extended_inquiry_response.opcode; 1598 hci_stack->last_cmd_opcode = opcode; 1599 uint16_t offset = 0; 1600 packet[offset++] = opcode & 0xff; 1601 packet[offset++] = opcode >> 8; 1602 packet[offset++] = 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN; 1603 packet[offset++] = 0; // FEC not required 1604 memset(&packet[offset], 0, EXTENDED_INQUIRY_RESPONSE_DATA_LEN); 1605 if (hci_stack->eir_data){ 1606 // copy items and expand '00:00:00:00:00:00' in name with bd_addr 1607 ad_context_t context; 1608 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, hci_stack->eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)) { 1609 uint8_t data_type = ad_iterator_get_data_type(&context); 1610 uint8_t size = ad_iterator_get_data_len(&context); 1611 const uint8_t *data = ad_iterator_get_data(&context); 1612 // copy item 1613 packet[offset++] = size + 1; 1614 packet[offset++] = data_type; 1615 memcpy(&packet[offset], data, size); 1616 // update name item 1617 if ((data_type == BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME) || (data_type == BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME)){ 1618 btstack_replace_bd_addr_placeholder(&packet[offset], size, hci_stack->local_bd_addr); 1619 } 1620 offset += size; 1621 } 1622 } else { 1623 uint16_t name_len = (uint16_t) strlen(hci_stack->local_name); 1624 uint16_t bytes_to_copy = btstack_min(name_len, EXTENDED_INQUIRY_RESPONSE_DATA_LEN - 2); 1625 packet[offset++] = bytes_to_copy + 1; 1626 packet[offset++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME; 1627 (void)memcpy(&packet[6], hci_stack->local_name, bytes_to_copy); 1628 // expand '00:00:00:00:00:00' in name with bd_addr 1629 btstack_replace_bd_addr_placeholder(&packet[offset], bytes_to_copy, hci_stack->local_bd_addr); 1630 } 1631 hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + EXTENDED_INQUIRY_RESPONSE_DATA_LEN); 1632 } 1633 1634 static void hci_run_gap_tasks_classic(void){ 1635 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_CLASS_OF_DEVICE) != 0) { 1636 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_CLASS_OF_DEVICE; 1637 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 1638 return; 1639 } 1640 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_LOCAL_NAME) != 0) { 1641 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_LOCAL_NAME; 1642 gap_run_set_local_name(); 1643 return; 1644 } 1645 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_EIR_DATA) != 0) { 1646 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_EIR_DATA; 1647 gap_run_set_eir_data(); 1648 return; 1649 } 1650 if ((hci_stack->gap_tasks_classic & GAP_TASK_SET_DEFAULT_LINK_POLICY) != 0) { 1651 hci_stack->gap_tasks_classic &= ~GAP_TASK_SET_DEFAULT_LINK_POLICY; 1652 hci_send_cmd(&hci_write_default_link_policy_setting, hci_stack->default_link_policy_settings); 1653 return; 1654 } 1655 // write page scan activity 1656 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY) != 0) { 1657 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY; 1658 hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window); 1659 return; 1660 } 1661 // write page scan type 1662 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_SCAN_TYPE) != 0) { 1663 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_SCAN_TYPE; 1664 hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type); 1665 return; 1666 } 1667 // write page timeout 1668 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_PAGE_TIMEOUT) != 0) { 1669 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_PAGE_TIMEOUT; 1670 hci_send_cmd(&hci_write_page_timeout, hci_stack->page_timeout); 1671 return; 1672 } 1673 // send scan enable 1674 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_SCAN_ENABLE) != 0) { 1675 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_SCAN_ENABLE; 1676 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 1677 return; 1678 } 1679 // send write scan activity 1680 if ((hci_stack->gap_tasks_classic & GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY) != 0) { 1681 hci_stack->gap_tasks_classic &= ~GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY; 1682 hci_send_cmd(&hci_write_inquiry_scan_activity, hci_stack->inquiry_scan_interval, hci_stack->inquiry_scan_window); 1683 return; 1684 } 1685 } 1686 #endif 1687 1688 #ifndef HAVE_HOST_CONTROLLER_API 1689 1690 static uint32_t hci_transport_uart_get_main_baud_rate(void){ 1691 if (!hci_stack->config) return 0; 1692 uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1693 // Limit baud rate for Broadcom chipsets to 3 mbps 1694 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) && (baud_rate > 3000000)){ 1695 baud_rate = 3000000; 1696 } 1697 return baud_rate; 1698 } 1699 1700 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){ 1701 UNUSED(ds); 1702 1703 switch (hci_stack->substate){ 1704 case HCI_INIT_W4_SEND_RESET: 1705 log_info("Resend HCI Reset"); 1706 hci_stack->substate = HCI_INIT_SEND_RESET; 1707 hci_stack->num_cmd_packets = 1; 1708 hci_run(); 1709 break; 1710 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET: 1711 log_info("Resend HCI Reset - CSR Warm Boot with Link Reset"); 1712 if (hci_stack->hci_transport->reset_link){ 1713 hci_stack->hci_transport->reset_link(); 1714 } 1715 1716 /* fall through */ 1717 1718 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 1719 log_info("Resend HCI Reset - CSR Warm Boot"); 1720 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 1721 hci_stack->num_cmd_packets = 1; 1722 hci_run(); 1723 break; 1724 case HCI_INIT_W4_SEND_BAUD_CHANGE: 1725 if (hci_stack->hci_transport->set_baudrate){ 1726 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1727 log_info("Local baud rate change to %" PRIu32 "(timeout handler)", baud_rate); 1728 hci_stack->hci_transport->set_baudrate(baud_rate); 1729 } 1730 // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP 1731 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){ 1732 if (hci_stack->hci_transport->reset_link){ 1733 log_info("Link Reset"); 1734 hci_stack->hci_transport->reset_link(); 1735 } 1736 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT; 1737 hci_run(); 1738 } 1739 break; 1740 case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY: 1741 // otherwise continue 1742 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1743 hci_send_cmd(&hci_read_local_supported_commands); 1744 break; 1745 default: 1746 break; 1747 } 1748 } 1749 #endif 1750 1751 static void hci_initializing_next_state(void){ 1752 hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1); 1753 } 1754 1755 static void hci_init_done(void){ 1756 // done. tell the app 1757 log_info("hci_init_done -> HCI_STATE_WORKING"); 1758 hci_stack->state = HCI_STATE_WORKING; 1759 hci_emit_state(); 1760 } 1761 1762 // assumption: hci_can_send_command_packet_now() == true 1763 static void hci_initializing_run(void){ 1764 log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now()); 1765 1766 if (!hci_can_send_command_packet_now()) return; 1767 1768 #ifndef HAVE_HOST_CONTROLLER_API 1769 bool need_baud_change = hci_stack->config 1770 && hci_stack->chipset 1771 && hci_stack->chipset->set_baudrate_command 1772 && hci_stack->hci_transport->set_baudrate 1773 && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 1774 #endif 1775 1776 switch (hci_stack->substate){ 1777 case HCI_INIT_SEND_RESET: 1778 hci_state_reset(); 1779 1780 #ifndef HAVE_HOST_CONTROLLER_API 1781 // prepare reset if command complete not received in 100ms 1782 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1783 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1784 btstack_run_loop_add_timer(&hci_stack->timeout); 1785 #endif 1786 // send command 1787 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 1788 hci_send_cmd(&hci_reset); 1789 break; 1790 case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION: 1791 hci_send_cmd(&hci_read_local_version_information); 1792 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION; 1793 break; 1794 1795 #ifndef HAVE_HOST_CONTROLLER_API 1796 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 1797 hci_state_reset(); 1798 // prepare reset if command complete not received in 100ms 1799 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1800 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1801 btstack_run_loop_add_timer(&hci_stack->timeout); 1802 // send command 1803 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 1804 hci_send_cmd(&hci_reset); 1805 break; 1806 case HCI_INIT_SEND_RESET_ST_WARM_BOOT: 1807 hci_state_reset(); 1808 hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT; 1809 hci_send_cmd(&hci_reset); 1810 break; 1811 case HCI_INIT_SEND_BAUD_CHANGE_BCM: { 1812 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1813 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer); 1814 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1815 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM; 1816 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]); 1817 break; 1818 } 1819 case HCI_INIT_SET_BD_ADDR: 1820 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr)); 1821 hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer); 1822 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1823 hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR; 1824 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]); 1825 break; 1826 case HCI_INIT_SEND_READ_LOCAL_NAME: 1827 #ifdef ENABLE_CLASSIC 1828 hci_send_cmd(&hci_read_local_name); 1829 hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME; 1830 break; 1831 #endif 1832 /* fall through */ 1833 1834 case HCI_INIT_SEND_BAUD_CHANGE: 1835 if (need_baud_change) { 1836 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 1837 hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer); 1838 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1839 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 1840 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3u + hci_stack->hci_packet_buffer[2u]); 1841 // STLC25000D: baudrate change happens within 0.5 s after command was send, 1842 // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial) 1843 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){ 1844 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1845 btstack_run_loop_add_timer(&hci_stack->timeout); 1846 } 1847 break; 1848 } 1849 1850 /* fall through */ 1851 1852 case HCI_INIT_CUSTOM_INIT: 1853 // Custom initialization 1854 if (hci_stack->chipset && hci_stack->chipset->next_command){ 1855 hci_stack->chipset_result = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer); 1856 bool send_cmd = false; 1857 switch (hci_stack->chipset_result){ 1858 case BTSTACK_CHIPSET_VALID_COMMAND: 1859 send_cmd = true; 1860 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT; 1861 break; 1862 case BTSTACK_CHIPSET_WARMSTART_REQUIRED: 1863 send_cmd = true; 1864 // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete 1865 log_info("CSR Warm Boot"); 1866 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS); 1867 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1868 btstack_run_loop_add_timer(&hci_stack->timeout); 1869 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO) 1870 && hci_stack->config 1871 && hci_stack->chipset 1872 // && hci_stack->chipset->set_baudrate_command -- there's no such command 1873 && hci_stack->hci_transport->set_baudrate 1874 && hci_transport_uart_get_main_baud_rate()){ 1875 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE; 1876 } else { 1877 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET; 1878 } 1879 break; 1880 default: 1881 break; 1882 } 1883 1884 if (send_cmd){ 1885 int size = 3u + hci_stack->hci_packet_buffer[2u]; 1886 hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0); 1887 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size); 1888 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 1889 break; 1890 } 1891 log_info("Init script done"); 1892 1893 // Init script download on Broadcom chipsets causes: 1894 if ( (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) && 1895 ( (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) 1896 || (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA)) ){ 1897 1898 // - baud rate to reset, restore UART baud rate if needed 1899 if (need_baud_change) { 1900 uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init; 1901 log_info("Local baud rate change to %" PRIu32 " after init script (bcm)", baud_rate); 1902 hci_stack->hci_transport->set_baudrate(baud_rate); 1903 } 1904 1905 uint16_t bcm_delay_ms = 300; 1906 // - UART may or may not be disabled during update and Controller RTS may or may not be high during this time 1907 // -> Work around: wait here. 1908 log_info("BCM delay (%u ms) after init script", bcm_delay_ms); 1909 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY; 1910 btstack_run_loop_set_timer(&hci_stack->timeout, bcm_delay_ms); 1911 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler); 1912 btstack_run_loop_add_timer(&hci_stack->timeout); 1913 break; 1914 } 1915 } 1916 #endif 1917 /* fall through */ 1918 1919 case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS: 1920 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS; 1921 hci_send_cmd(&hci_read_local_supported_commands); 1922 break; 1923 case HCI_INIT_READ_BD_ADDR: 1924 hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR; 1925 hci_send_cmd(&hci_read_bd_addr); 1926 break; 1927 case HCI_INIT_READ_BUFFER_SIZE: 1928 // only read buffer size if supported 1929 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_BUFFER_SIZE)){ 1930 hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE; 1931 hci_send_cmd(&hci_read_buffer_size); 1932 break; 1933 } 1934 1935 /* fall through */ 1936 1937 case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES: 1938 hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES; 1939 hci_send_cmd(&hci_read_local_supported_features); 1940 break; 1941 1942 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 1943 case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL: 1944 hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL; 1945 hci_send_cmd(&hci_set_controller_to_host_flow_control, 3); // ACL + SCO Flow Control 1946 break; 1947 case HCI_INIT_HOST_BUFFER_SIZE: 1948 hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE; 1949 hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN, 1950 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM); 1951 break; 1952 #endif 1953 1954 case HCI_INIT_SET_EVENT_MASK: 1955 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK; 1956 if (hci_le_supported()){ 1957 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x3FFFFFFFU); 1958 } else { 1959 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 1960 hci_send_cmd(&hci_set_event_mask,0xFFFFFFFFU, 0x1FFFFFFFU); 1961 } 1962 break; 1963 1964 case HCI_INIT_SET_EVENT_MASK_2: 1965 // On Bluettooth PTS dongle (BL 654) with PacketCraft HCI Firmware (LMP subversion) 0x5244, 1966 // setting Event Mask 2 causes Controller to drop Encryption Change events. 1967 if (hci_command_supported(SUPPORTED_HCI_COMMAND_SET_EVENT_MASK_PAGE_2) 1968 && (hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_PACKETCRAFT_INC)){ 1969 hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK_2; 1970 // Encryption Change Event v2 - bit 25 1971 hci_send_cmd(&hci_set_event_mask_2,0x02000000U, 0x0); 1972 break; 1973 } 1974 1975 #ifdef ENABLE_CLASSIC 1976 /* fall through */ 1977 1978 case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE: 1979 if (hci_classic_supported() && gap_ssp_supported()){ 1980 hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE; 1981 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 1982 break; 1983 } 1984 1985 /* fall through */ 1986 1987 case HCI_INIT_WRITE_INQUIRY_MODE: 1988 if (hci_classic_supported()){ 1989 hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE; 1990 hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode); 1991 break; 1992 } 1993 1994 /* fall through */ 1995 1996 case HCI_INIT_WRITE_SECURE_CONNECTIONS_HOST_ENABLE: 1997 // skip write secure connections host support if not supported or disabled 1998 if (hci_classic_supported() && hci_stack->secure_connections_enable 1999 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SECURE_CONNECTIONS_HOST)) { 2000 hci_stack->secure_connections_active = true; 2001 hci_stack->substate = HCI_INIT_W4_WRITE_SECURE_CONNECTIONS_HOST_ENABLE; 2002 hci_send_cmd(&hci_write_secure_connections_host_support, 1); 2003 break; 2004 } 2005 2006 /* fall through */ 2007 2008 case HCI_INIT_SET_MIN_ENCRYPTION_KEY_SIZE: 2009 // skip set min encryption key size 2010 if (hci_classic_supported() && hci_command_supported(SUPPORTED_HCI_COMMAND_SET_MIN_ENCRYPTION_KEY_SIZE)) { 2011 hci_stack->substate = HCI_INIT_W4_SET_MIN_ENCRYPTION_KEY_SIZE; 2012 hci_send_cmd(&hci_set_min_encryption_key_size, hci_stack->gap_required_encyrption_key_size); 2013 break; 2014 } 2015 2016 #ifdef ENABLE_SCO_OVER_HCI 2017 /* fall through */ 2018 2019 // only sent if ENABLE_SCO_OVER_HCI is defined 2020 case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE: 2021 // skip write synchronous flow control if not supported 2022 if (hci_classic_supported() 2023 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE)) { 2024 hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE; 2025 hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled 2026 break; 2027 } 2028 /* fall through */ 2029 2030 case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING: 2031 // skip write default erroneous data reporting if not supported 2032 if (hci_classic_supported() 2033 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING)) { 2034 hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING; 2035 hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1); 2036 break; 2037 } 2038 #endif 2039 2040 #if defined(ENABLE_SCO_OVER_HCI) || defined(ENABLE_SCO_OVER_PCM) 2041 /* fall through */ 2042 2043 // only sent if manufacturer is Broadcom and ENABLE_SCO_OVER_HCI or ENABLE_SCO_OVER_PCM is defined 2044 case HCI_INIT_BCM_WRITE_SCO_PCM_INT: 2045 if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){ 2046 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT; 2047 #ifdef ENABLE_SCO_OVER_HCI 2048 log_info("BCM: Route SCO data via HCI transport"); 2049 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0); 2050 #endif 2051 #ifdef ENABLE_SCO_OVER_PCM 2052 log_info("BCM: Route SCO data via PCM interface"); 2053 #ifdef ENABLE_BCM_PCM_WBS 2054 // 512 kHz bit clock for 2 channels x 16 bit x 16 kHz 2055 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 2, 0, 1, 1); 2056 #else 2057 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz 2058 hci_send_cmd(&hci_bcm_write_sco_pcm_int, 0, 1, 0, 1, 1); 2059 #endif 2060 #endif 2061 break; 2062 } 2063 #endif 2064 2065 #ifdef ENABLE_SCO_OVER_PCM 2066 /* fall through */ 2067 2068 case HCI_INIT_BCM_WRITE_I2SPCM_INTERFACE_PARAM: 2069 if (hci_classic_supported() && (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION)){ 2070 hci_stack->substate = HCI_INIT_W4_BCM_WRITE_I2SPCM_INTERFACE_PARAM; 2071 log_info("BCM: Config PCM interface for I2S"); 2072 #ifdef ENABLE_BCM_PCM_WBS 2073 // 512 kHz bit clock for 2 channels x 16 bit x 8 kHz 2074 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 2); 2075 #else 2076 // 256 kHz bit clock for 2 channels x 16 bit x 8 kHz 2077 hci_send_cmd(&hci_bcm_write_i2spcm_interface_param, 1, 1, 0, 1); 2078 #endif 2079 break; 2080 } 2081 #endif 2082 #endif 2083 2084 #ifdef ENABLE_BLE 2085 /* fall through */ 2086 2087 // LE INIT 2088 case HCI_INIT_LE_READ_BUFFER_SIZE: 2089 if (hci_le_supported()){ 2090 hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE; 2091 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_BUFFER_SIZE_V2)){ 2092 hci_send_cmd(&hci_le_read_buffer_size_v2); 2093 } else { 2094 hci_send_cmd(&hci_le_read_buffer_size); 2095 } 2096 break; 2097 } 2098 2099 /* fall through */ 2100 2101 case HCI_INIT_WRITE_LE_HOST_SUPPORTED: 2102 // skip write le host if not supported (e.g. on LE only EM9301) 2103 if (hci_le_supported() 2104 && hci_command_supported(SUPPORTED_HCI_COMMAND_WRITE_LE_HOST_SUPPORTED)) { 2105 // LE Supported Host = 1, Simultaneous Host = 0 2106 hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED; 2107 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 2108 break; 2109 } 2110 2111 /* fall through */ 2112 2113 case HCI_INIT_LE_SET_EVENT_MASK: 2114 if (hci_le_supported()){ 2115 hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK; 2116 hci_send_cmd(&hci_le_set_event_mask, 0xfffffdff, 0x07); // all events from core v5.3 without LE Enhanced Connection Complete 2117 break; 2118 } 2119 #endif 2120 2121 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 2122 /* fall through */ 2123 2124 case HCI_INIT_LE_READ_MAX_DATA_LENGTH: 2125 if (hci_le_supported() 2126 && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_READ_MAXIMUM_DATA_LENGTH)) { 2127 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH; 2128 hci_send_cmd(&hci_le_read_maximum_data_length); 2129 break; 2130 } 2131 2132 /* fall through */ 2133 2134 case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH: 2135 if (hci_le_supported() 2136 && hci_command_supported(SUPPORTED_HCI_COMMAND_LE_WRITE_SUGGESTED_DEFAULT_DATA_LENGTH)) { 2137 hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH; 2138 hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time); 2139 break; 2140 } 2141 #endif 2142 2143 #ifdef ENABLE_LE_CENTRAL 2144 /* fall through */ 2145 2146 case HCI_INIT_READ_WHITE_LIST_SIZE: 2147 if (hci_le_supported()){ 2148 hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE; 2149 hci_send_cmd(&hci_le_read_white_list_size); 2150 break; 2151 } 2152 2153 #endif 2154 2155 #ifdef ENABLE_LE_PERIPHERAL 2156 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 2157 /* fall through */ 2158 2159 case HCI_INIT_LE_READ_MAX_ADV_DATA_LEN: 2160 if (hci_extended_advertising_supported()){ 2161 hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_ADV_DATA_LEN; 2162 hci_send_cmd(&hci_le_read_maximum_advertising_data_length); 2163 break; 2164 } 2165 #endif 2166 #endif 2167 /* fall through */ 2168 2169 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 2170 case HCI_INIT_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS: 2171 if (hci_le_supported()) { 2172 hci_stack->substate = HCI_INIT_W4_LE_SET_HOST_FEATURE_CONNECTED_ISO_STREAMS; 2173 hci_send_cmd(&hci_le_set_host_feature, 32, 1); 2174 break; 2175 } 2176 #endif 2177 2178 /* fall through */ 2179 2180 case HCI_INIT_DONE: 2181 hci_stack->substate = HCI_INIT_DONE; 2182 // main init sequence complete 2183 #ifdef ENABLE_CLASSIC 2184 // check if initial Classic GAP Tasks are completed 2185 if (hci_classic_supported() && (hci_stack->gap_tasks_classic != 0)) { 2186 hci_run_gap_tasks_classic(); 2187 break; 2188 } 2189 #endif 2190 #ifdef ENABLE_BLE 2191 #ifdef ENABLE_LE_CENTRAL 2192 // check if initial LE GAP Tasks are completed 2193 if (hci_le_supported() && hci_stack->le_scanning_param_update) { 2194 hci_run_general_gap_le(); 2195 break; 2196 } 2197 #endif 2198 #endif 2199 hci_init_done(); 2200 break; 2201 2202 default: 2203 return; 2204 } 2205 } 2206 2207 static bool hci_initializing_event_handler_command_completed(const uint8_t * packet){ 2208 bool command_completed = false; 2209 if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){ 2210 uint16_t opcode = little_endian_read_16(packet,3); 2211 if (opcode == hci_stack->last_cmd_opcode){ 2212 command_completed = true; 2213 log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate); 2214 } else { 2215 log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate); 2216 } 2217 } 2218 2219 if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){ 2220 uint8_t status = packet[2]; 2221 uint16_t opcode = little_endian_read_16(packet,4); 2222 if (opcode == hci_stack->last_cmd_opcode){ 2223 if (status){ 2224 command_completed = true; 2225 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate); 2226 } else { 2227 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode); 2228 } 2229 } else { 2230 log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 2231 } 2232 } 2233 #ifndef HAVE_HOST_CONTROLLER_API 2234 // Vendor == CSR 2235 if ((hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){ 2236 // TODO: track actual command 2237 command_completed = true; 2238 } 2239 2240 // Vendor == Toshiba 2241 if ((hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE) && (hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC)){ 2242 // TODO: track actual command 2243 command_completed = true; 2244 // Fix: no HCI Command Complete received, so num_cmd_packets not reset 2245 hci_stack->num_cmd_packets = 1; 2246 } 2247 #endif 2248 2249 return command_completed; 2250 } 2251 2252 static void hci_initializing_event_handler(const uint8_t * packet, uint16_t size){ 2253 2254 UNUSED(size); // ok: less than 6 bytes are read from our buffer 2255 2256 bool command_completed = hci_initializing_event_handler_command_completed(packet); 2257 2258 #ifndef HAVE_HOST_CONTROLLER_API 2259 2260 // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661: 2261 // Command complete for HCI Reset arrives after we've resent the HCI Reset command 2262 // 2263 // HCI Reset 2264 // Timeout 100 ms 2265 // HCI Reset 2266 // Command Complete Reset 2267 // HCI Read Local Version Information 2268 // Command Complete Reset - but we expected Command Complete Read Local Version Information 2269 // hang... 2270 // 2271 // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend 2272 if (!command_completed 2273 && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE) 2274 && (hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION)){ 2275 2276 uint16_t opcode = little_endian_read_16(packet,3); 2277 if (opcode == hci_reset.opcode){ 2278 hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION; 2279 return; 2280 } 2281 } 2282 2283 // CSR & H5 2284 // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend 2285 if (!command_completed 2286 && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE) 2287 && (hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS)){ 2288 2289 uint16_t opcode = little_endian_read_16(packet,3); 2290 if (opcode == hci_reset.opcode){ 2291 hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS; 2292 return; 2293 } 2294 } 2295 2296 // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT 2297 // fix: Correct substate and behave as command below 2298 if (command_completed){ 2299 switch (hci_stack->substate){ 2300 case HCI_INIT_SEND_RESET: 2301 hci_stack->substate = HCI_INIT_W4_SEND_RESET; 2302 break; 2303 case HCI_INIT_SEND_RESET_CSR_WARM_BOOT: 2304 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT; 2305 break; 2306 default: 2307 break; 2308 } 2309 } 2310 2311 #endif 2312 2313 if (!command_completed) return; 2314 2315 bool need_baud_change = false; 2316 bool need_addr_change = false; 2317 2318 #ifndef HAVE_HOST_CONTROLLER_API 2319 need_baud_change = hci_stack->config 2320 && hci_stack->chipset 2321 && hci_stack->chipset->set_baudrate_command 2322 && hci_stack->hci_transport->set_baudrate 2323 && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main; 2324 2325 need_addr_change = hci_stack->custom_bd_addr_set 2326 && hci_stack->chipset 2327 && hci_stack->chipset->set_bd_addr_command; 2328 #endif 2329 2330 switch(hci_stack->substate){ 2331 2332 #ifndef HAVE_HOST_CONTROLLER_API 2333 case HCI_INIT_SEND_RESET: 2334 // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET 2335 // fix: just correct substate and behave as command below 2336 2337 /* fall through */ 2338 #endif 2339 2340 case HCI_INIT_W4_SEND_RESET: 2341 btstack_run_loop_remove_timer(&hci_stack->timeout); 2342 hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION; 2343 return; 2344 2345 #ifndef HAVE_HOST_CONTROLLER_API 2346 case HCI_INIT_W4_SEND_BAUD_CHANGE: 2347 // for STLC2500D, baud rate change already happened. 2348 // for others, baud rate gets changed now 2349 if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){ 2350 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 2351 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change)", baud_rate); 2352 hci_stack->hci_transport->set_baudrate(baud_rate); 2353 } 2354 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 2355 return; 2356 case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT: 2357 btstack_run_loop_remove_timer(&hci_stack->timeout); 2358 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 2359 return; 2360 case HCI_INIT_W4_CUSTOM_INIT: 2361 // repeat custom init 2362 hci_stack->substate = HCI_INIT_CUSTOM_INIT; 2363 return; 2364 #endif 2365 2366 case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS: 2367 if (need_baud_change && (hci_stack->chipset_result != BTSTACK_CHIPSET_NO_INIT_SCRIPT) && 2368 ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) || 2369 (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) { 2370 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM; 2371 return; 2372 } 2373 if (need_addr_change){ 2374 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 2375 return; 2376 } 2377 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2378 return; 2379 #ifndef HAVE_HOST_CONTROLLER_API 2380 case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM: 2381 if (need_baud_change){ 2382 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate(); 2383 log_info("Local baud rate change to %" PRIu32 "(w4_send_baud_change_bcm))", baud_rate); 2384 hci_stack->hci_transport->set_baudrate(baud_rate); 2385 } 2386 if (need_addr_change){ 2387 hci_stack->substate = HCI_INIT_SET_BD_ADDR; 2388 return; 2389 } 2390 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2391 return; 2392 case HCI_INIT_W4_SET_BD_ADDR: 2393 // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command 2394 if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) 2395 || (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){ 2396 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT; 2397 return; 2398 } 2399 // skipping st warm boot 2400 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2401 return; 2402 case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT: 2403 hci_stack->substate = HCI_INIT_READ_BD_ADDR; 2404 return; 2405 #endif 2406 2407 case HCI_INIT_DONE: 2408 // set state if we came here by fall through 2409 hci_stack->substate = HCI_INIT_DONE; 2410 return; 2411 2412 default: 2413 break; 2414 } 2415 hci_initializing_next_state(); 2416 } 2417 2418 static void hci_handle_connection_failed(hci_connection_t * conn, uint8_t status){ 2419 // CC2564C might emit Connection Complete for rejected incoming SCO connection 2420 // To prevent accidentally free'ing the HCI connection for the ACL connection, 2421 // check if we have been aware of the HCI connection 2422 switch (conn->state){ 2423 case SENT_CREATE_CONNECTION: 2424 case RECEIVED_CONNECTION_REQUEST: 2425 break; 2426 default: 2427 return; 2428 } 2429 2430 log_info("Outgoing connection to %s failed", bd_addr_to_str(conn->address)); 2431 bd_addr_t bd_address; 2432 (void)memcpy(&bd_address, conn->address, 6); 2433 2434 #ifdef ENABLE_CLASSIC 2435 // cache needed data 2436 int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED; 2437 #endif 2438 2439 // connection failed, remove entry 2440 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 2441 btstack_memory_hci_connection_free( conn ); 2442 2443 #ifdef ENABLE_CLASSIC 2444 // notify client if dedicated bonding 2445 if (notify_dedicated_bonding_failed){ 2446 log_info("hci notify_dedicated_bonding_failed"); 2447 hci_emit_dedicated_bonding_result(bd_address, status); 2448 } 2449 2450 // if authentication error, also delete link key 2451 if (status == ERROR_CODE_AUTHENTICATION_FAILURE) { 2452 gap_drop_link_key_for_bd_addr(bd_address); 2453 } 2454 #else 2455 UNUSED(status); 2456 #endif 2457 } 2458 2459 #ifdef ENABLE_CLASSIC 2460 static void hci_handle_remote_features_page_0(hci_connection_t * conn, const uint8_t * features){ 2461 // SSP Controller 2462 if (features[6] & (1 << 3)){ 2463 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER; 2464 } 2465 // eSCO 2466 if (features[3] & (1<<7)){ 2467 conn->remote_supported_features[0] |= 1; 2468 } 2469 // Extended features 2470 if (features[7] & (1<<7)){ 2471 conn->remote_supported_features[0] |= 2; 2472 } 2473 } 2474 2475 static void hci_handle_remote_features_page_1(hci_connection_t * conn, const uint8_t * features){ 2476 // SSP Host 2477 if (features[0] & (1 << 0)){ 2478 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP_HOST; 2479 } 2480 // SC Host 2481 if (features[0] & (1 << 3)){ 2482 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_HOST; 2483 } 2484 } 2485 2486 static void hci_handle_remote_features_page_2(hci_connection_t * conn, const uint8_t * features){ 2487 // SC Controller 2488 if (features[1] & (1 << 0)){ 2489 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 2490 } 2491 } 2492 2493 static void hci_handle_remote_features_received(hci_connection_t * conn){ 2494 conn->bonding_flags &= ~BONDING_REMOTE_FEATURES_QUERY_ACTIVE; 2495 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 2496 log_info("Remote features %02x, bonding flags %x", conn->remote_supported_features[0], conn->bonding_flags); 2497 if (conn->bonding_flags & BONDING_DEDICATED){ 2498 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2499 } 2500 } 2501 static bool hci_remote_sc_enabled(hci_connection_t * connection){ 2502 const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 2503 return (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask; 2504 } 2505 2506 #endif 2507 2508 static void handle_event_for_current_stack_state(const uint8_t * packet, uint16_t size) { 2509 // handle BT initialization 2510 if (hci_stack->state == HCI_STATE_INITIALIZING) { 2511 hci_initializing_event_handler(packet, size); 2512 } 2513 2514 // help with BT sleep 2515 if ((hci_stack->state == HCI_STATE_FALLING_ASLEEP) 2516 && (hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE) 2517 && (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE) 2518 && (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_WRITE_SCAN_ENABLE)){ 2519 hci_initializing_next_state(); 2520 } 2521 } 2522 2523 #ifdef ENABLE_CLASSIC 2524 static void hci_handle_read_encryption_key_size_complete(hci_connection_t * conn, uint8_t encryption_key_size) { 2525 conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED; 2526 conn->encryption_key_size = encryption_key_size; 2527 gap_security_level_t security_level = gap_security_level_for_connection(conn); 2528 2529 // trigger disconnect for dedicated bonding, skip emit security level as disconnect is pending 2530 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){ 2531 conn->bonding_flags &= ~BONDING_DEDICATED; 2532 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 2533 conn->bonding_status = security_level == 0 ? ERROR_CODE_INSUFFICIENT_SECURITY : ERROR_CODE_SUCCESS; 2534 return; 2535 } 2536 2537 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) != 0) { 2538 conn->requested_security_level = LEVEL_0; 2539 hci_emit_security_level(conn->con_handle, security_level); 2540 return; 2541 } 2542 2543 // Request remote features if not already done 2544 hci_trigger_remote_features_for_connection(conn); 2545 2546 // Request Authentication if not already done 2547 if ((conn->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) return; 2548 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2549 } 2550 #endif 2551 2552 static void hci_store_local_supported_commands(const uint8_t * packet){ 2553 // create mapping table 2554 #define X(name, offset, bit) { offset, bit }, 2555 static struct { 2556 uint8_t byte_offset; 2557 uint8_t bit_position; 2558 } supported_hci_commands_map [] = { 2559 SUPPORTED_HCI_COMMANDS 2560 }; 2561 #undef X 2562 2563 // create names for debug purposes 2564 #ifdef ENABLE_LOG_DEBUG 2565 #define X(name, offset, bit) #name, 2566 static const char * command_names[] = { 2567 SUPPORTED_HCI_COMMANDS 2568 }; 2569 #undef X 2570 #endif 2571 2572 hci_stack->local_supported_commands = 0; 2573 const uint8_t * commands_map = &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1]; 2574 uint16_t i; 2575 for (i = 0 ; i < SUPPORTED_HCI_COMMANDS_COUNT ; i++){ 2576 if ((commands_map[supported_hci_commands_map[i].byte_offset] & (1 << supported_hci_commands_map[i].bit_position)) != 0){ 2577 #ifdef ENABLE_LOG_DEBUG 2578 log_info("Command %s (%u) supported %u/%u", command_names[i], i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position); 2579 #else 2580 log_info("Command 0x%02x supported %u/%u", i, supported_hci_commands_map[i].byte_offset, supported_hci_commands_map[i].bit_position); 2581 #endif 2582 hci_stack->local_supported_commands |= (1LU << i); 2583 } 2584 } 2585 log_info("Local supported commands summary %04x", hci_stack->local_supported_commands); 2586 } 2587 2588 static void handle_command_complete_event(uint8_t * packet, uint16_t size){ 2589 UNUSED(size); 2590 2591 uint16_t manufacturer; 2592 #ifdef ENABLE_CLASSIC 2593 hci_con_handle_t handle; 2594 hci_connection_t * conn; 2595 #endif 2596 #if defined(ENABLE_CLASSIC) || (defined(ENABLE_BLE) && defined(ENABLE_LE_ISOCHRONOUS_STREAMS)) 2597 uint8_t status; 2598 #endif 2599 // get num cmd packets - limit to 1 to reduce complexity 2600 hci_stack->num_cmd_packets = packet[2] ? 1 : 0; 2601 2602 uint16_t opcode = hci_event_command_complete_get_command_opcode(packet); 2603 switch (opcode){ 2604 case HCI_OPCODE_HCI_READ_LOCAL_NAME: 2605 if (packet[5]) break; 2606 // terminate, name 248 chars 2607 packet[6+248] = 0; 2608 log_info("local name: %s", &packet[6]); 2609 break; 2610 case HCI_OPCODE_HCI_READ_BUFFER_SIZE: 2611 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 2612 if (hci_stack->state == HCI_STATE_INITIALIZING) { 2613 uint16_t acl_len = little_endian_read_16(packet, 6); 2614 uint16_t sco_len = packet[8]; 2615 2616 // determine usable ACL/SCO payload size 2617 hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE); 2618 hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE); 2619 2620 hci_stack->acl_packets_total_num = (uint8_t) little_endian_read_16(packet, 9); 2621 hci_stack->sco_packets_total_num = (uint8_t) little_endian_read_16(packet, 11); 2622 2623 log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u", 2624 acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num, 2625 hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num); 2626 } 2627 break; 2628 case HCI_OPCODE_HCI_READ_RSSI: 2629 if (packet[5] == ERROR_CODE_SUCCESS){ 2630 uint8_t event[5]; 2631 event[0] = GAP_EVENT_RSSI_MEASUREMENT; 2632 event[1] = 3; 2633 (void)memcpy(&event[2], &packet[6], 3); 2634 hci_emit_event(event, sizeof(event), 1); 2635 } 2636 break; 2637 #ifdef ENABLE_BLE 2638 case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE_V2: 2639 hci_stack->le_iso_packets_length = little_endian_read_16(packet, 9); 2640 hci_stack->le_iso_packets_total_num = packet[11]; 2641 log_info("hci_le_read_buffer_size_v2: iso size %u, iso count %u", 2642 hci_stack->le_iso_packets_length, hci_stack->le_iso_packets_total_num); 2643 2644 /* fall through */ 2645 2646 case HCI_OPCODE_HCI_LE_READ_BUFFER_SIZE: 2647 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6); 2648 hci_stack->le_acl_packets_total_num = packet[8]; 2649 // determine usable ACL payload size 2650 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){ 2651 hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE; 2652 } 2653 log_info("hci_le_read_buffer_size: acl size %u, acl count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num); 2654 break; 2655 #endif 2656 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION 2657 case HCI_OPCODE_HCI_LE_READ_MAXIMUM_DATA_LENGTH: 2658 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6); 2659 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8); 2660 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time); 2661 break; 2662 #endif 2663 #ifdef ENABLE_LE_CENTRAL 2664 case HCI_OPCODE_HCI_LE_READ_WHITE_LIST_SIZE: 2665 hci_stack->le_whitelist_capacity = packet[6]; 2666 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity); 2667 break; 2668 #endif 2669 #ifdef ENABLE_LE_PERIPHERAL 2670 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 2671 case HCI_OPCODE_HCI_LE_READ_MAXIMUM_ADVERTISING_DATA_LENGTH: 2672 hci_stack->le_maximum_advertising_data_length = little_endian_read_16(packet, 6); 2673 break; 2674 case HCI_OPCODE_HCI_LE_SET_EXTENDED_ADVERTISING_PARAMETERS: 2675 if (hci_stack->le_advertising_set_in_current_command != 0) { 2676 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command); 2677 hci_stack->le_advertising_set_in_current_command = 0; 2678 if (advertising_set == NULL) break; 2679 uint8_t adv_status = packet[6]; 2680 uint8_t tx_power = packet[7]; 2681 uint8_t event[] = { HCI_EVENT_META_GAP, 4, GAP_SUBEVENT_ADVERTISING_SET_INSTALLED, hci_stack->le_advertising_set_in_current_command, adv_status, tx_power }; 2682 if (adv_status == 0){ 2683 advertising_set->state |= LE_ADVERTISEMENT_STATE_PARAMS_SET; 2684 } 2685 hci_emit_event(event, sizeof(event), 1); 2686 } 2687 break; 2688 case HCI_OPCODE_HCI_LE_REMOVE_ADVERTISING_SET: 2689 if (hci_stack->le_advertising_set_in_current_command != 0) { 2690 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(hci_stack->le_advertising_set_in_current_command); 2691 hci_stack->le_advertising_set_in_current_command = 0; 2692 if (advertising_set == NULL) break; 2693 uint8_t adv_status = packet[5]; 2694 uint8_t event[] = { HCI_EVENT_META_GAP, 3, GAP_SUBEVENT_ADVERTISING_SET_REMOVED, hci_stack->le_advertising_set_in_current_command, adv_status }; 2695 if (adv_status == 0){ 2696 btstack_linked_list_remove(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) advertising_set); 2697 } 2698 hci_emit_event(event, sizeof(event), 1); 2699 } 2700 break; 2701 #endif 2702 #endif 2703 case HCI_OPCODE_HCI_READ_BD_ADDR: 2704 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], hci_stack->local_bd_addr); 2705 log_info("Local Address, Status: 0x%02x: Addr: %s", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 2706 #ifdef ENABLE_CLASSIC 2707 if (hci_stack->link_key_db){ 2708 hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr); 2709 } 2710 #endif 2711 break; 2712 #ifdef ENABLE_CLASSIC 2713 case HCI_OPCODE_HCI_WRITE_SCAN_ENABLE: 2714 hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable); 2715 break; 2716 case HCI_OPCODE_HCI_PERIODIC_INQUIRY_MODE: 2717 status = hci_event_command_complete_get_return_parameters(packet)[0]; 2718 if (status == ERROR_CODE_SUCCESS) { 2719 hci_stack->inquiry_state = GAP_INQUIRY_STATE_PERIODIC; 2720 } else { 2721 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 2722 } 2723 break; 2724 case HCI_OPCODE_HCI_INQUIRY_CANCEL: 2725 case HCI_OPCODE_HCI_EXIT_PERIODIC_INQUIRY_MODE: 2726 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){ 2727 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 2728 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 2729 hci_emit_event(event, sizeof(event), 1); 2730 } 2731 break; 2732 #endif 2733 case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_FEATURES: 2734 (void)memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1], 8); 2735 2736 #ifdef ENABLE_CLASSIC 2737 // determine usable ACL packet types based on host buffer size and supported features 2738 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]); 2739 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported()); 2740 #endif 2741 // Classic/LE 2742 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 2743 break; 2744 case HCI_OPCODE_HCI_READ_LOCAL_VERSION_INFORMATION: 2745 manufacturer = little_endian_read_16(packet, 10); 2746 // map Cypress to Broadcom 2747 if (manufacturer == BLUETOOTH_COMPANY_ID_CYPRESS_SEMICONDUCTOR){ 2748 log_info("Treat Cypress as Broadcom"); 2749 manufacturer = BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION; 2750 little_endian_store_16(packet, 10, manufacturer); 2751 } 2752 hci_stack->manufacturer = manufacturer; 2753 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer); 2754 break; 2755 case HCI_OPCODE_HCI_READ_LOCAL_SUPPORTED_COMMANDS: 2756 hci_store_local_supported_commands(packet); 2757 break; 2758 #ifdef ENABLE_CLASSIC 2759 case HCI_OPCODE_HCI_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE: 2760 if (packet[5]) return; 2761 hci_stack->synchronous_flow_control_enabled = 1; 2762 break; 2763 case HCI_OPCODE_HCI_READ_ENCRYPTION_KEY_SIZE: 2764 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2765 handle = little_endian_read_16(packet, OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1); 2766 conn = hci_connection_for_handle(handle); 2767 if (conn != NULL) { 2768 uint8_t key_size = 0; 2769 if (status == 0){ 2770 key_size = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+3]; 2771 log_info("Handle %04x key Size: %u", handle, key_size); 2772 } else { 2773 key_size = 1; 2774 log_info("Read Encryption Key Size failed 0x%02x-> assuming insecure connection with key size of 1", status); 2775 } 2776 hci_handle_read_encryption_key_size_complete(conn, key_size); 2777 } 2778 break; 2779 // assert pairing complete event is emitted. 2780 // note: for SSP, Simple Pairing Complete Event is sufficient, but we want to be more robust 2781 case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY: 2782 case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY: 2783 case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY: 2784 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 2785 // lookup connection by gap pairing addr 2786 conn = hci_connection_for_bd_addr_and_type(hci_stack->gap_pairing_addr, BD_ADDR_TYPE_ACL); 2787 if (conn == NULL) break; 2788 hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE); 2789 break; 2790 2791 #ifdef ENABLE_CLASSIC_PAIRING_OOB 2792 case HCI_OPCODE_HCI_READ_LOCAL_OOB_DATA: 2793 case HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA:{ 2794 uint8_t event[67]; 2795 event[0] = GAP_EVENT_LOCAL_OOB_DATA; 2796 event[1] = 65; 2797 (void)memset(&event[2], 0, 65); 2798 if (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE] == ERROR_CODE_SUCCESS){ 2799 (void)memcpy(&event[3], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 32); 2800 if (opcode == HCI_OPCODE_HCI_READ_LOCAL_EXTENDED_OOB_DATA){ 2801 event[2] = 3; 2802 (void)memcpy(&event[35], &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+33], 32); 2803 } else { 2804 event[2] = 1; 2805 } 2806 } 2807 hci_emit_event(event, sizeof(event), 0); 2808 break; 2809 } 2810 2811 // note: only needed if user does not provide OOB data 2812 case HCI_OPCODE_HCI_REMOTE_OOB_DATA_REQUEST_NEGATIVE_REPLY: 2813 conn = hci_connection_for_handle(hci_stack->classic_oob_con_handle); 2814 hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID; 2815 if (conn == NULL) break; 2816 hci_pairing_complete(conn, ERROR_CODE_AUTHENTICATION_FAILURE); 2817 break; 2818 #endif 2819 #endif 2820 #ifdef ENABLE_BLE 2821 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 2822 case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST: 2823 case HCI_OPCODE_HCI_LE_CREATE_CIS: 2824 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2825 if (status != ERROR_CODE_SUCCESS){ 2826 hci_iso_stream_requested_finalize(0xff); 2827 } 2828 break; 2829 case HCI_OPCODE_HCI_LE_SETUP_ISO_DATA_PATH: { 2830 // lookup BIG by state 2831 btstack_linked_list_iterator_t it; 2832 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 2833 while (btstack_linked_list_iterator_has_next(&it)) { 2834 le_audio_big_t *big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 2835 if (big->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){ 2836 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2837 if (status == ERROR_CODE_SUCCESS){ 2838 big->state_vars.next_bis++; 2839 if (big->state_vars.next_bis == big->num_bis){ 2840 big->state = LE_AUDIO_BIG_STATE_ACTIVE; 2841 hci_emit_big_created(big, ERROR_CODE_SUCCESS); 2842 } else { 2843 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 2844 } 2845 } else { 2846 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED; 2847 big->state_vars.status = status; 2848 } 2849 return; 2850 } 2851 } 2852 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 2853 while (btstack_linked_list_iterator_has_next(&it)) { 2854 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 2855 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH){ 2856 status = packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE]; 2857 if (status == ERROR_CODE_SUCCESS){ 2858 big_sync->state_vars.next_bis++; 2859 if (big_sync->state_vars.next_bis == big_sync->num_bis){ 2860 big_sync->state = LE_AUDIO_BIG_STATE_ACTIVE; 2861 hci_emit_big_sync_created(big_sync, ERROR_CODE_SUCCESS); 2862 } else { 2863 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 2864 } 2865 } else { 2866 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED; 2867 big_sync->state_vars.status = status; 2868 } 2869 return; 2870 } 2871 } 2872 break; 2873 } 2874 case HCI_OPCODE_HCI_LE_BIG_TERMINATE_SYNC: { 2875 // lookup BIG by state 2876 btstack_linked_list_iterator_t it; 2877 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 2878 while (btstack_linked_list_iterator_has_next(&it)) { 2879 le_audio_big_sync_t *big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 2880 uint8_t big_handle = big_sync->big_handle; 2881 switch (big_sync->state){ 2882 case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED: 2883 btstack_linked_list_iterator_remove(&it); 2884 hci_emit_big_sync_created(big_sync, big_sync->state_vars.status); 2885 return; 2886 default: 2887 btstack_linked_list_iterator_remove(&it); 2888 hci_emit_big_sync_stopped(big_handle); 2889 return; 2890 } 2891 } 2892 break; 2893 } 2894 #endif 2895 #endif 2896 default: 2897 break; 2898 } 2899 } 2900 2901 static void handle_command_status_event(uint8_t * packet, uint16_t size) { 2902 UNUSED(size); 2903 2904 // get num cmd packets - limit to 1 to reduce complexity 2905 hci_stack->num_cmd_packets = packet[3] ? 1 : 0; 2906 2907 // get opcode and command status 2908 uint16_t opcode = hci_event_command_status_get_command_opcode(packet); 2909 2910 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) || defined(ENABLE_LE_ISOCHRONOUS_STREAMS) 2911 uint8_t status = hci_event_command_status_get_status(packet); 2912 #endif 2913 2914 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) 2915 bd_addr_type_t addr_type; 2916 #endif 2917 2918 switch (opcode){ 2919 #ifdef ENABLE_CLASSIC 2920 case HCI_OPCODE_HCI_CREATE_CONNECTION: 2921 case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION: 2922 #endif 2923 #ifdef ENABLE_LE_CENTRAL 2924 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION: 2925 #endif 2926 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_CENTRAL) 2927 addr_type = hci_stack->outgoing_addr_type; 2928 2929 // reset outgoing address info 2930 memset(hci_stack->outgoing_addr, 0, 6); 2931 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_UNKNOWN; 2932 2933 // on error 2934 if (status != ERROR_CODE_SUCCESS){ 2935 #ifdef ENABLE_LE_CENTRAL 2936 if (hci_is_le_connection_type(addr_type)){ 2937 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 2938 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 2939 } 2940 #endif 2941 // error => outgoing connection failed 2942 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(hci_stack->outgoing_addr, addr_type); 2943 if (conn != NULL){ 2944 hci_handle_connection_failed(conn, status); 2945 } 2946 } 2947 break; 2948 #endif 2949 #ifdef ENABLE_CLASSIC 2950 case HCI_OPCODE_HCI_INQUIRY: 2951 if (status == ERROR_CODE_SUCCESS) { 2952 hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE; 2953 } else { 2954 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 2955 } 2956 break; 2957 #endif 2958 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 2959 case HCI_OPCODE_HCI_LE_CREATE_CIS: 2960 case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST: 2961 if (status == ERROR_CODE_SUCCESS){ 2962 hci_iso_stream_requested_confirm(0xff); 2963 } else { 2964 hci_iso_stream_requested_finalize(0xff); 2965 } 2966 break; 2967 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 2968 default: 2969 break; 2970 } 2971 } 2972 2973 #ifdef ENABLE_BLE 2974 static void event_handle_le_connection_complete(const uint8_t * packet){ 2975 bd_addr_t addr; 2976 bd_addr_type_t addr_type; 2977 hci_connection_t * conn; 2978 2979 // Connection management 2980 reverse_bd_addr(&packet[8], addr); 2981 addr_type = (bd_addr_type_t)packet[7]; 2982 log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr)); 2983 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2984 2985 #ifdef ENABLE_LE_CENTRAL 2986 // handle error: error is reported only to the initiator -> outgoing connection 2987 if (packet[3]){ 2988 2989 // handle cancelled outgoing connection 2990 // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command, 2991 // either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated. 2992 // In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)." 2993 if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){ 2994 // reset state 2995 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 2996 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 2997 // get outgoing connection conn struct for direct connect 2998 conn = gap_get_outgoing_connection(); 2999 } 3000 3001 // outgoing le connection establishment is done 3002 if (conn){ 3003 // remove entry 3004 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 3005 btstack_memory_hci_connection_free( conn ); 3006 } 3007 return; 3008 } 3009 #endif 3010 3011 // on success, both hosts receive connection complete event 3012 if (packet[6] == HCI_ROLE_MASTER){ 3013 #ifdef ENABLE_LE_CENTRAL 3014 // if we're master on an le connection, it was an outgoing connection and we're done with it 3015 // note: no hci_connection_t object exists yet for connect with whitelist 3016 if (hci_is_le_connection_type(addr_type)){ 3017 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 3018 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 3019 } 3020 #endif 3021 } else { 3022 #ifdef ENABLE_LE_PERIPHERAL 3023 // if we're slave, it was an incoming connection, advertisements have stopped 3024 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 3025 #endif 3026 } 3027 3028 // LE connections are auto-accepted, so just create a connection if there isn't one already 3029 if (!conn){ 3030 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 3031 } 3032 3033 // no memory, sorry. 3034 if (!conn){ 3035 return; 3036 } 3037 3038 conn->state = OPEN; 3039 conn->role = packet[6]; 3040 conn->con_handle = hci_subevent_le_connection_complete_get_connection_handle(packet); 3041 conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet); 3042 3043 #ifdef ENABLE_LE_PERIPHERAL 3044 if (packet[6] == HCI_ROLE_SLAVE){ 3045 hci_update_advertisements_enabled_for_current_roles(); 3046 } 3047 #endif 3048 3049 // init unenhanced att bearer mtu 3050 conn->att_connection.mtu = ATT_DEFAULT_MTU; 3051 conn->att_connection.mtu_exchanged = false; 3052 3053 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 3054 3055 // restart timer 3056 // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 3057 // btstack_run_loop_add_timer(&conn->timeout); 3058 3059 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 3060 3061 hci_emit_nr_connections_changed(); 3062 } 3063 #endif 3064 3065 #ifdef ENABLE_CLASSIC 3066 static bool hci_ssp_security_level_possible_for_io_cap(gap_security_level_t level, uint8_t io_cap_local, uint8_t io_cap_remote){ 3067 if (io_cap_local == SSP_IO_CAPABILITY_UNKNOWN) return false; 3068 // LEVEL_4 is tested by l2cap 3069 // LEVEL 3 requires MITM protection -> check io capabilities if Authenticated is possible 3070 // @see: Core Spec v5.3, Vol 3, Part C, Table 5.7 3071 if (level >= LEVEL_3){ 3072 // MITM not possible without keyboard or display 3073 if (io_cap_remote >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false; 3074 if (io_cap_local >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) return false; 3075 3076 // MITM possible if one side has keyboard and the other has keyboard or display 3077 if (io_cap_remote == SSP_IO_CAPABILITY_KEYBOARD_ONLY) return true; 3078 if (io_cap_local == SSP_IO_CAPABILITY_KEYBOARD_ONLY) return true; 3079 3080 // MITM not possible if one side has only display and other side has no keyboard 3081 if (io_cap_remote == SSP_IO_CAPABILITY_DISPLAY_ONLY) return false; 3082 if (io_cap_local == SSP_IO_CAPABILITY_DISPLAY_ONLY) return false; 3083 } 3084 // LEVEL 2 requires SSP, which is a given 3085 return true; 3086 } 3087 3088 static bool btstack_is_null(uint8_t * data, uint16_t size){ 3089 uint16_t i; 3090 for (i=0; i < size ; i++){ 3091 if (data[i] != 0) { 3092 return false; 3093 } 3094 } 3095 return true; 3096 } 3097 3098 static void hci_ssp_assess_security_on_io_cap_request(hci_connection_t * conn){ 3099 // get requested security level 3100 gap_security_level_t requested_security_level = conn->requested_security_level; 3101 if (hci_stack->gap_secure_connections_only_mode){ 3102 requested_security_level = LEVEL_4; 3103 } 3104 3105 // assess security: LEVEL 4 requires SC 3106 // skip this preliminary test if remote features are not available yet to work around potential issue in ESP32 controller 3107 if ((requested_security_level == LEVEL_4) && 3108 ((conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0) && 3109 !hci_remote_sc_enabled(conn)){ 3110 log_info("Level 4 required, but SC not supported -> abort"); 3111 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3112 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3113 return; 3114 } 3115 3116 // assess security based on io capabilities 3117 if (conn->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){ 3118 // responder: fully validate io caps of both sides as well as OOB data 3119 bool security_possible = false; 3120 security_possible = hci_ssp_security_level_possible_for_io_cap(requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io); 3121 3122 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3123 // We assume that both Controller can reach LEVEL 4, if one side has received P-192 and the other has received P-256, 3124 // so we merge the OOB data availability 3125 uint8_t have_oob_data = conn->io_cap_response_oob_data; 3126 if (conn->classic_oob_c_192 != NULL){ 3127 have_oob_data |= 1; 3128 } 3129 if (conn->classic_oob_c_256 != NULL){ 3130 have_oob_data |= 2; 3131 } 3132 // for up to Level 3, either P-192 as well as P-256 will do 3133 // if we don't support SC, then a) conn->classic_oob_c_256 will be NULL and b) remote should not report P-256 available 3134 // if remote does not SC, we should not receive P-256 data either 3135 if ((requested_security_level <= LEVEL_3) && (have_oob_data != 0)){ 3136 security_possible = true; 3137 } 3138 // for Level 4, P-256 is needed 3139 if ((requested_security_level == LEVEL_4 && ((have_oob_data & 2) != 0))){ 3140 security_possible = true; 3141 } 3142 #endif 3143 3144 if (security_possible == false){ 3145 log_info("IOCap/OOB insufficient for level %u -> abort", requested_security_level); 3146 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3147 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3148 return; 3149 } 3150 } else { 3151 // initiator: remote io cap not yet, only check if we have ability for MITM protection if requested and OOB is not supported 3152 #ifndef ENABLE_CLASSIC_PAIRING_OOB 3153 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 3154 if ((conn->requested_security_level >= LEVEL_3) && (hci_stack->ssp_io_capability >= SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT)){ 3155 log_info("Level 3+ required, but no input/output -> abort"); 3156 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3157 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3158 return; 3159 } 3160 #endif 3161 #endif 3162 } 3163 3164 #ifndef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 3165 if (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN){ 3166 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY); 3167 } else { 3168 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 3169 } 3170 #endif 3171 } 3172 3173 #endif 3174 3175 static void event_handler(uint8_t *packet, uint16_t size){ 3176 3177 uint16_t event_length = packet[1]; 3178 3179 // assert packet is complete 3180 if (size != (event_length + 2u)){ 3181 log_error("event_handler called with packet of wrong size %d, expected %u => dropping packet", size, event_length + 2); 3182 return; 3183 } 3184 3185 hci_con_handle_t handle; 3186 hci_connection_t * conn; 3187 int i; 3188 3189 #ifdef ENABLE_CLASSIC 3190 hci_link_type_t link_type; 3191 bd_addr_t addr; 3192 bd_addr_type_t addr_type; 3193 #endif 3194 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3195 hci_iso_stream_t * iso_stream; 3196 le_audio_big_t * big; 3197 le_audio_big_sync_t * big_sync; 3198 #endif 3199 3200 // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet)); 3201 3202 switch (hci_event_packet_get_type(packet)) { 3203 3204 case HCI_EVENT_COMMAND_COMPLETE: 3205 handle_command_complete_event(packet, size); 3206 break; 3207 3208 case HCI_EVENT_COMMAND_STATUS: 3209 handle_command_status_event(packet, size); 3210 break; 3211 3212 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{ 3213 if (size < 3) return; 3214 uint16_t num_handles = packet[2]; 3215 if (size != (3u + num_handles * 4u)) return; 3216 #ifdef ENABLE_CLASSIC 3217 bool notify_sco = false; 3218 #endif 3219 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3220 bool notify_iso = false; 3221 #endif 3222 uint16_t offset = 3; 3223 for (i=0; i<num_handles;i++){ 3224 handle = little_endian_read_16(packet, offset) & 0x0fffu; 3225 offset += 2u; 3226 uint16_t num_packets = little_endian_read_16(packet, offset); 3227 offset += 2u; 3228 3229 conn = hci_connection_for_handle(handle); 3230 if (conn != NULL) { 3231 3232 if (conn->num_packets_sent >= num_packets) { 3233 conn->num_packets_sent -= num_packets; 3234 } else { 3235 log_error("hci_number_completed_packets, more packet slots freed then sent."); 3236 conn->num_packets_sent = 0; 3237 } 3238 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_packets_sent); 3239 #ifdef ENABLE_CLASSIC 3240 if (conn->address_type == BD_ADDR_TYPE_SCO){ 3241 notify_sco = true; 3242 } 3243 #endif 3244 } 3245 3246 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 3247 hci_controller_dump_packets(); 3248 #endif 3249 3250 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3251 if (conn == NULL){ 3252 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(handle); 3253 if (iso_stream != NULL){ 3254 if (iso_stream->num_packets_sent >= num_packets) { 3255 iso_stream->num_packets_sent -= num_packets; 3256 } else { 3257 log_error("hci_number_completed_packets, more packet slots freed then sent."); 3258 iso_stream->num_packets_sent = 0; 3259 } 3260 uint8_t big_handle = iso_stream->big_handle; 3261 if (big_handle != 0xff){ 3262 le_audio_big_t * big = hci_big_for_handle(big_handle); 3263 if (big != NULL){ 3264 big->num_completed_timestamp_current_valid = true; 3265 big->num_completed_timestamp_current_ms = btstack_run_loop_get_time_ms(); 3266 } 3267 } 3268 log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", 3269 num_packets, handle, iso_stream->num_packets_sent); 3270 notify_iso = true; 3271 } 3272 } 3273 #endif 3274 } 3275 3276 #ifdef ENABLE_CLASSIC 3277 if (notify_sco){ 3278 hci_notify_if_sco_can_send_now(); 3279 } 3280 #endif 3281 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3282 if (notify_iso){ 3283 hci_iso_notify_can_send_now(); 3284 } 3285 #endif 3286 break; 3287 } 3288 3289 #ifdef ENABLE_CLASSIC 3290 case HCI_EVENT_FLUSH_OCCURRED: 3291 // flush occurs only if automatic flush has been enabled by gap_enable_link_watchdog() 3292 handle = hci_event_flush_occurred_get_handle(packet); 3293 conn = hci_connection_for_handle(handle); 3294 if (conn) { 3295 log_info("Flush occurred, disconnect 0x%04x", handle); 3296 conn->state = SEND_DISCONNECT; 3297 } 3298 break; 3299 3300 case HCI_EVENT_INQUIRY_COMPLETE: 3301 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){ 3302 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE; 3303 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 3304 hci_emit_event(event, sizeof(event), 1); 3305 } 3306 break; 3307 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 3308 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){ 3309 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE; 3310 } 3311 break; 3312 case HCI_EVENT_CONNECTION_REQUEST: 3313 reverse_bd_addr(&packet[2], addr); 3314 link_type = (hci_link_type_t) packet[11]; 3315 3316 // CVE-2020-26555: reject incoming connection from device with same BD ADDR 3317 if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0){ 3318 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR; 3319 bd_addr_copy(hci_stack->decline_addr, addr); 3320 break; 3321 } 3322 3323 if (hci_stack->gap_classic_accept_callback != NULL){ 3324 if ((*hci_stack->gap_classic_accept_callback)(addr, link_type) == 0){ 3325 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS; 3326 bd_addr_copy(hci_stack->decline_addr, addr); 3327 break; 3328 } 3329 } 3330 3331 // TODO: eval COD 8-10 3332 log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), (unsigned int) link_type); 3333 addr_type = (link_type == HCI_LINK_TYPE_ACL) ? BD_ADDR_TYPE_ACL : BD_ADDR_TYPE_SCO; 3334 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3335 if (!conn) { 3336 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 3337 } 3338 if (!conn) { 3339 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 3340 hci_stack->decline_reason = ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES; 3341 bd_addr_copy(hci_stack->decline_addr, addr); 3342 hci_run(); 3343 // avoid event to higher layer 3344 return; 3345 } 3346 conn->role = HCI_ROLE_SLAVE; 3347 conn->state = RECEIVED_CONNECTION_REQUEST; 3348 // store info about eSCO 3349 if (link_type == HCI_LINK_TYPE_ESCO){ 3350 conn->remote_supported_features[0] |= 1; 3351 } 3352 hci_run(); 3353 break; 3354 3355 case HCI_EVENT_CONNECTION_COMPLETE: 3356 // Connection management 3357 reverse_bd_addr(&packet[5], addr); 3358 log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 3359 addr_type = BD_ADDR_TYPE_ACL; 3360 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3361 if (conn) { 3362 if (!packet[2]){ 3363 conn->state = OPEN; 3364 conn->con_handle = little_endian_read_16(packet, 3); 3365 3366 // trigger write supervision timeout if we're master 3367 if ((hci_stack->link_supervision_timeout != HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT) && (conn->role == HCI_ROLE_MASTER)){ 3368 conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT; 3369 } 3370 3371 // trigger write automatic flush timeout 3372 if (hci_stack->automatic_flush_timeout != 0){ 3373 conn->gap_connection_tasks |= GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT; 3374 } 3375 3376 // restart timer 3377 btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 3378 btstack_run_loop_add_timer(&conn->timeout); 3379 3380 // trigger remote features for dedicated bonding 3381 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){ 3382 hci_trigger_remote_features_for_connection(conn); 3383 } 3384 3385 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 3386 3387 hci_emit_nr_connections_changed(); 3388 } else { 3389 // connection failed 3390 hci_handle_connection_failed(conn, packet[2]); 3391 } 3392 } 3393 break; 3394 3395 case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE: 3396 reverse_bd_addr(&packet[5], addr); 3397 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 3398 log_info("Synchronous Connection Complete for %p (status=%u) %s", conn, packet[2], bd_addr_to_str(addr)); 3399 if (packet[2]){ 3400 // connection failed 3401 if (conn){ 3402 hci_handle_connection_failed(conn, packet[2]); 3403 } 3404 break; 3405 } 3406 if (!conn) { 3407 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 3408 } 3409 if (!conn) { 3410 break; 3411 } 3412 conn->state = OPEN; 3413 conn->con_handle = little_endian_read_16(packet, 3); 3414 3415 #ifdef ENABLE_SCO_OVER_HCI 3416 // update SCO 3417 if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){ 3418 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections()); 3419 } 3420 // trigger can send now 3421 if (hci_have_usb_transport()){ 3422 hci_stack->sco_can_send_now = true; 3423 } 3424 #endif 3425 #ifdef HAVE_SCO_TRANSPORT 3426 // configure sco transport 3427 if (hci_stack->sco_transport != NULL){ 3428 sco_format_t sco_format = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? SCO_FORMAT_8_BIT : SCO_FORMAT_16_BIT; 3429 hci_stack->sco_transport->open(conn->con_handle, sco_format); 3430 } 3431 #endif 3432 break; 3433 3434 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 3435 handle = little_endian_read_16(packet, 3); 3436 conn = hci_connection_for_handle(handle); 3437 if (!conn) break; 3438 if (!packet[2]){ 3439 const uint8_t * features = &packet[5]; 3440 hci_handle_remote_features_page_0(conn, features); 3441 3442 // read extended features if possible 3443 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_REMOTE_EXTENDED_FEATURES) 3444 && ((conn->remote_supported_features[0] & 2) != 0)) { 3445 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_1; 3446 break; 3447 } 3448 } 3449 hci_handle_remote_features_received(conn); 3450 break; 3451 3452 case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE: 3453 handle = little_endian_read_16(packet, 3); 3454 conn = hci_connection_for_handle(handle); 3455 if (!conn) break; 3456 // status = ok, page = 1 3457 if (!packet[2]) { 3458 uint8_t page_number = packet[5]; 3459 uint8_t maximum_page_number = packet[6]; 3460 const uint8_t * features = &packet[7]; 3461 bool done = false; 3462 switch (page_number){ 3463 case 1: 3464 hci_handle_remote_features_page_1(conn, features); 3465 if (maximum_page_number >= 2){ 3466 // get Secure Connections (Controller) from Page 2 if available 3467 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES_PAGE_2; 3468 } else { 3469 // otherwise, assume SC (Controller) == SC (Host) 3470 if ((conn->bonding_flags & BONDING_REMOTE_SUPPORTS_SC_HOST) != 0){ 3471 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 3472 } 3473 done = true; 3474 } 3475 break; 3476 case 2: 3477 hci_handle_remote_features_page_2(conn, features); 3478 done = true; 3479 break; 3480 default: 3481 break; 3482 } 3483 if (!done) break; 3484 } 3485 hci_handle_remote_features_received(conn); 3486 break; 3487 3488 case HCI_EVENT_LINK_KEY_REQUEST: 3489 #ifndef ENABLE_EXPLICIT_LINK_KEY_REPLY 3490 hci_event_link_key_request_get_bd_addr(packet, addr); 3491 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3492 if (!conn) break; 3493 3494 // lookup link key in db if not cached 3495 if ((conn->link_key_type == INVALID_LINK_KEY) && (hci_stack->link_key_db != NULL)){ 3496 hci_stack->link_key_db->get_link_key(conn->address, conn->link_key, &conn->link_key_type); 3497 } 3498 3499 // response sent by hci_run() 3500 conn->authentication_flags |= AUTH_FLAG_HANDLE_LINK_KEY_REQUEST; 3501 #endif 3502 break; 3503 3504 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 3505 hci_event_link_key_request_get_bd_addr(packet, addr); 3506 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3507 if (!conn) break; 3508 3509 hci_pairing_complete(conn, ERROR_CODE_SUCCESS); 3510 3511 // CVE-2020-26555: ignore NULL link key 3512 // default link_key_type = INVALID_LINK_KEY asserts that NULL key won't be used for encryption 3513 if (btstack_is_null(&packet[8], 16)) break; 3514 3515 link_key_type_t link_key_type = (link_key_type_t)packet[24]; 3516 // Change Connection Encryption keeps link key type 3517 if (link_key_type != CHANGED_COMBINATION_KEY){ 3518 conn->link_key_type = link_key_type; 3519 } 3520 3521 // cache link key. link keys stored in little-endian format for legacy reasons 3522 memcpy(&conn->link_key, &packet[8], 16); 3523 3524 // only store link key: 3525 // - if bondable enabled 3526 if (hci_stack->bondable == false) break; 3527 // - if security level sufficient 3528 if (gap_security_level_for_link_key_type(link_key_type) < conn->requested_security_level) break; 3529 // - for SSP, also check if remote side requested bonding as well 3530 if (conn->link_key_type != COMBINATION_KEY){ 3531 bool remote_bonding = conn->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 3532 if (!remote_bonding){ 3533 break; 3534 } 3535 } 3536 gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type); 3537 break; 3538 } 3539 3540 case HCI_EVENT_PIN_CODE_REQUEST: 3541 hci_event_pin_code_request_get_bd_addr(packet, addr); 3542 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3543 if (!conn) break; 3544 3545 hci_pairing_started(conn, false); 3546 // abort pairing if: non-bondable mode (pin code request is not forwarded to app) 3547 if (!hci_stack->bondable ){ 3548 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST; 3549 hci_pairing_complete(conn, ERROR_CODE_PAIRING_NOT_ALLOWED); 3550 hci_run(); 3551 return; 3552 } 3553 // abort pairing if: LEVEL_4 required (pin code request is not forwarded to app) 3554 if ((hci_stack->gap_secure_connections_only_mode) || (conn->requested_security_level == LEVEL_4)){ 3555 log_info("Level 4 required, but SC not supported -> abort"); 3556 conn->authentication_flags |= AUTH_FLAG_DENY_PIN_CODE_REQUEST; 3557 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3558 hci_run(); 3559 return; 3560 } 3561 break; 3562 3563 case HCI_EVENT_IO_CAPABILITY_RESPONSE: 3564 hci_event_io_capability_response_get_bd_addr(packet, addr); 3565 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3566 if (!conn) break; 3567 3568 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE); 3569 hci_pairing_started(conn, true); 3570 conn->io_cap_response_auth_req = hci_event_io_capability_response_get_authentication_requirements(packet); 3571 conn->io_cap_response_io = hci_event_io_capability_response_get_io_capability(packet); 3572 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3573 conn->io_cap_response_oob_data = hci_event_io_capability_response_get_oob_data_present(packet); 3574 #endif 3575 break; 3576 3577 case HCI_EVENT_IO_CAPABILITY_REQUEST: 3578 hci_event_io_capability_response_get_bd_addr(packet, addr); 3579 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3580 if (!conn) break; 3581 3582 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST); 3583 hci_connection_timestamp(conn); 3584 hci_pairing_started(conn, true); 3585 break; 3586 3587 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3588 case HCI_EVENT_REMOTE_OOB_DATA_REQUEST: 3589 hci_event_remote_oob_data_request_get_bd_addr(packet, addr); 3590 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3591 if (!conn) break; 3592 3593 hci_connection_timestamp(conn); 3594 3595 hci_pairing_started(conn, true); 3596 3597 connectionSetAuthenticationFlags(conn, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY); 3598 break; 3599 #endif 3600 3601 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 3602 hci_event_user_confirmation_request_get_bd_addr(packet, addr); 3603 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3604 if (!conn) break; 3605 if (hci_ssp_security_level_possible_for_io_cap(conn->requested_security_level, hci_stack->ssp_io_capability, conn->io_cap_response_io)) { 3606 if (hci_stack->ssp_auto_accept){ 3607 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_REPLY); 3608 }; 3609 } else { 3610 hci_pairing_complete(conn, ERROR_CODE_INSUFFICIENT_SECURITY); 3611 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY); 3612 // don't forward event to app 3613 hci_run(); 3614 return; 3615 } 3616 break; 3617 3618 case HCI_EVENT_USER_PASSKEY_REQUEST: 3619 // Pairing using Passkey results in MITM protection. If Level 4 is required, support for SC is validated on IO Cap Request 3620 if (hci_stack->ssp_auto_accept){ 3621 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], AUTH_FLAG_SEND_USER_PASSKEY_REPLY); 3622 }; 3623 break; 3624 3625 case HCI_EVENT_MODE_CHANGE: 3626 handle = hci_event_mode_change_get_handle(packet); 3627 conn = hci_connection_for_handle(handle); 3628 if (!conn) break; 3629 conn->connection_mode = hci_event_mode_change_get_mode(packet); 3630 log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode); 3631 break; 3632 #endif 3633 3634 case HCI_EVENT_ENCRYPTION_CHANGE: 3635 case HCI_EVENT_ENCRYPTION_CHANGE_V2: 3636 handle = hci_event_encryption_change_get_connection_handle(packet); 3637 conn = hci_connection_for_handle(handle); 3638 if (!conn) break; 3639 if (hci_event_encryption_change_get_status(packet) == 0u) { 3640 uint8_t encryption_enabled = hci_event_encryption_change_get_encryption_enabled(packet); 3641 if (encryption_enabled){ 3642 if (hci_is_le_connection(conn)){ 3643 // For LE, we accept connection as encrypted 3644 conn->authentication_flags |= AUTH_FLAG_CONNECTION_ENCRYPTED; 3645 } 3646 #ifdef ENABLE_CLASSIC 3647 else { 3648 3649 // Detect Secure Connection -> Legacy Connection Downgrade Attack (BIAS) 3650 bool sc_used_during_pairing = gap_secure_connection_for_link_key_type(conn->link_key_type); 3651 bool connected_uses_aes_ccm = encryption_enabled == 2; 3652 if (hci_stack->secure_connections_active && sc_used_during_pairing && !connected_uses_aes_ccm){ 3653 log_info("SC during pairing, but only E0 now -> abort"); 3654 conn->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 3655 break; 3656 } 3657 3658 // if AES-CCM is used, authentication used SC -> authentication was mutual and we can skip explicit authentication 3659 if (connected_uses_aes_ccm){ 3660 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3661 } 3662 3663 #ifdef ENABLE_TESTING_SUPPORT 3664 // work around for issue with PTS dongle 3665 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3666 #endif 3667 // validate encryption key size 3668 if (hci_event_packet_get_type(packet) == HCI_EVENT_ENCRYPTION_CHANGE_V2) { 3669 uint8_t encryption_key_size = hci_event_encryption_change_v2_get_encryption_key_size(packet); 3670 // already got encryption key size 3671 hci_handle_read_encryption_key_size_complete(conn, encryption_key_size); 3672 } else { 3673 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_ENCRYPTION_KEY_SIZE)) { 3674 // For Classic, we need to validate encryption key size first, if possible (== supported by Controller) 3675 conn->bonding_flags |= BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 3676 } else { 3677 // if not, pretend everything is perfect 3678 hci_handle_read_encryption_key_size_complete(conn, 16); 3679 } 3680 } 3681 } 3682 #endif 3683 } else { 3684 conn->authentication_flags &= ~AUTH_FLAG_CONNECTION_ENCRYPTED; 3685 } 3686 } else { 3687 uint8_t status = hci_event_encryption_change_get_status(packet); 3688 if ((conn->bonding_flags & BONDING_DEDICATED) != 0){ 3689 conn->bonding_flags &= ~BONDING_DEDICATED; 3690 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 3691 conn->bonding_status = status; 3692 } 3693 } 3694 3695 break; 3696 3697 #ifdef ENABLE_CLASSIC 3698 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 3699 handle = hci_event_authentication_complete_get_connection_handle(packet); 3700 conn = hci_connection_for_handle(handle); 3701 if (!conn) break; 3702 3703 // clear authentication active flag 3704 conn->bonding_flags &= ~BONDING_SENT_AUTHENTICATE_REQUEST; 3705 hci_pairing_complete(conn, hci_event_authentication_complete_get_status(packet)); 3706 3707 // authenticated only if auth status == 0 3708 if (hci_event_authentication_complete_get_status(packet) == 0){ 3709 // authenticated 3710 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3711 3712 // If not already encrypted, start encryption 3713 if ((conn->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0){ 3714 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 3715 break; 3716 } 3717 } 3718 3719 // emit updated security level 3720 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 3721 break; 3722 3723 case HCI_EVENT_SIMPLE_PAIRING_COMPLETE: 3724 hci_event_simple_pairing_complete_get_bd_addr(packet, addr); 3725 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 3726 if (!conn) break; 3727 3728 // treat successfully paired connection as authenticated 3729 if (hci_event_simple_pairing_complete_get_status(packet) == ERROR_CODE_SUCCESS){ 3730 conn->authentication_flags |= AUTH_FLAG_CONNECTION_AUTHENTICATED; 3731 } 3732 3733 hci_pairing_complete(conn, hci_event_simple_pairing_complete_get_status(packet)); 3734 break; 3735 #endif 3736 3737 // HCI_EVENT_DISCONNECTION_COMPLETE 3738 // has been split, to first notify stack before shutting connection down 3739 // see end of function, too. 3740 case HCI_EVENT_DISCONNECTION_COMPLETE: 3741 if (packet[2]) break; // status != 0 3742 handle = little_endian_read_16(packet, 3); 3743 // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active 3744 if (hci_stack->acl_fragmentation_total_size > 0u) { 3745 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){ 3746 int release_buffer = hci_stack->acl_fragmentation_tx_active == 0u; 3747 log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer); 3748 hci_stack->acl_fragmentation_total_size = 0; 3749 hci_stack->acl_fragmentation_pos = 0; 3750 if (release_buffer){ 3751 hci_release_packet_buffer(); 3752 } 3753 } 3754 } 3755 3756 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3757 // drop outgoing ISO fragments if it is for closed connection and release buffer if tx not active 3758 if (hci_stack->iso_fragmentation_total_size > 0u) { 3759 if (handle == READ_ISO_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){ 3760 int release_buffer = hci_stack->iso_fragmentation_tx_active == 0u; 3761 log_info("drop fragmented ISO data for closed connection, release buffer %u", release_buffer); 3762 hci_stack->iso_fragmentation_total_size = 0; 3763 hci_stack->iso_fragmentation_pos = 0; 3764 if (release_buffer){ 3765 hci_release_packet_buffer(); 3766 } 3767 } 3768 } 3769 3770 // finalize iso stream if handle matches 3771 iso_stream = hci_iso_stream_for_con_handle(handle); 3772 if (iso_stream != NULL){ 3773 hci_iso_stream_finalize(iso_stream); 3774 break; 3775 } 3776 #endif 3777 3778 conn = hci_connection_for_handle(handle); 3779 if (!conn) break; 3780 #ifdef ENABLE_CLASSIC 3781 // pairing failed if it was ongoing 3782 hci_pairing_complete(conn, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 3783 #endif 3784 3785 // emit dedicatd bonding event 3786 if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){ 3787 hci_emit_dedicated_bonding_result(conn->address, conn->bonding_status); 3788 } 3789 3790 // mark connection for shutdown, stop timers, reset state 3791 conn->state = RECEIVED_DISCONNECTION_COMPLETE; 3792 hci_connection_stop_timer(conn); 3793 hci_connection_init(conn); 3794 3795 #ifdef ENABLE_BLE 3796 #ifdef ENABLE_LE_PERIPHERAL 3797 // re-enable advertisements for le connections if active 3798 if (hci_is_le_connection(conn)){ 3799 hci_update_advertisements_enabled_for_current_roles(); 3800 } 3801 #endif 3802 #endif 3803 break; 3804 3805 case HCI_EVENT_HARDWARE_ERROR: 3806 log_error("Hardware Error: 0x%02x", packet[2]); 3807 if (hci_stack->hardware_error_callback){ 3808 (*hci_stack->hardware_error_callback)(packet[2]); 3809 } else { 3810 // if no special requests, just reboot stack 3811 hci_power_control_off(); 3812 hci_power_control_on(); 3813 } 3814 break; 3815 3816 #ifdef ENABLE_CLASSIC 3817 case HCI_EVENT_ROLE_CHANGE: 3818 if (packet[2]) break; // status != 0 3819 reverse_bd_addr(&packet[3], addr); 3820 addr_type = BD_ADDR_TYPE_ACL; 3821 conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 3822 if (!conn) break; 3823 conn->role = packet[9]; 3824 break; 3825 #endif 3826 3827 case HCI_EVENT_TRANSPORT_PACKET_SENT: 3828 // release packet buffer only for asynchronous transport and if there are not further fragments 3829 if (hci_transport_synchronous()) { 3830 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT"); 3831 return; // instead of break: to avoid re-entering hci_run() 3832 } 3833 hci_stack->acl_fragmentation_tx_active = 0; 3834 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3835 hci_stack->iso_fragmentation_tx_active = 0; 3836 if (hci_stack->iso_fragmentation_total_size) break; 3837 #endif 3838 if (hci_stack->acl_fragmentation_total_size) break; 3839 hci_release_packet_buffer(); 3840 3841 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3842 hci_iso_notify_can_send_now(); 3843 #endif 3844 // L2CAP receives this event via the hci_emit_event below 3845 3846 #ifdef ENABLE_CLASSIC 3847 // For SCO, we do the can_send_now_check here 3848 hci_notify_if_sco_can_send_now(); 3849 #endif 3850 break; 3851 3852 #ifdef ENABLE_CLASSIC 3853 case HCI_EVENT_SCO_CAN_SEND_NOW: 3854 // For SCO, we do the can_send_now_check here 3855 hci_stack->sco_can_send_now = true; 3856 hci_notify_if_sco_can_send_now(); 3857 return; 3858 3859 // explode inquriy results for easier consumption 3860 case HCI_EVENT_INQUIRY_RESULT: 3861 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 3862 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 3863 gap_inquiry_explode(packet, size); 3864 break; 3865 #endif 3866 3867 #ifdef ENABLE_BLE 3868 case HCI_EVENT_LE_META: 3869 switch (packet[2]){ 3870 #ifdef ENABLE_LE_CENTRAL 3871 case HCI_SUBEVENT_LE_ADVERTISING_REPORT: 3872 if (!hci_stack->le_scanning_enabled) break; 3873 le_handle_advertisement_report(packet, size); 3874 break; 3875 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 3876 case HCI_SUBEVENT_LE_EXTENDED_ADVERTISING_REPORT: 3877 if (!hci_stack->le_scanning_enabled) break; 3878 le_handle_extended_advertisement_report(packet, size); 3879 break; 3880 case HCI_SUBEVENT_LE_PERIODIC_ADVERTISING_SYNC_ESTABLISHMENT: 3881 hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE; 3882 hci_stack->le_periodic_sync_state = LE_CONNECTING_IDLE; 3883 break; 3884 #endif 3885 #endif 3886 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 3887 event_handle_le_connection_complete(packet); 3888 break; 3889 3890 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]); 3891 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE: 3892 handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet); 3893 conn = hci_connection_for_handle(handle); 3894 if (!conn) break; 3895 conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet); 3896 break; 3897 3898 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST: 3899 // connection 3900 handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet); 3901 conn = hci_connection_for_handle(handle); 3902 if (conn) { 3903 // read arguments 3904 uint16_t le_conn_interval_min = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet); 3905 uint16_t le_conn_interval_max = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet); 3906 uint16_t le_conn_latency = hci_subevent_le_remote_connection_parameter_request_get_latency(packet); 3907 uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet); 3908 3909 // validate against current connection parameter range 3910 le_connection_parameter_range_t existing_range; 3911 gap_get_connection_parameter_range(&existing_range); 3912 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout); 3913 if (update_parameter){ 3914 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY; 3915 conn->le_conn_interval_min = le_conn_interval_min; 3916 conn->le_conn_interval_max = le_conn_interval_max; 3917 conn->le_conn_latency = le_conn_latency; 3918 conn->le_supervision_timeout = le_supervision_timeout; 3919 } else { 3920 conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NEGATIVE_REPLY; 3921 } 3922 } 3923 break; 3924 #ifdef ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS 3925 case HCI_SUBEVENT_LE_DATA_LENGTH_CHANGE: 3926 handle = hci_subevent_le_data_length_change_get_connection_handle(packet); 3927 conn = hci_connection_for_handle(handle); 3928 if (conn) { 3929 conn->le_max_tx_octets = hci_subevent_le_data_length_change_get_max_tx_octets(packet); 3930 } 3931 break; 3932 #endif 3933 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 3934 case HCI_SUBEVENT_LE_CIS_ESTABLISHED: 3935 handle = hci_subevent_le_cis_established_get_connection_handle(packet); 3936 iso_stream = hci_iso_stream_for_con_handle(handle); 3937 if (iso_stream){ 3938 uint8_t status = hci_subevent_le_cis_established_get_status(packet); 3939 if (status == ERROR_CODE_SUCCESS){ 3940 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED; 3941 } else { 3942 hci_iso_stream_finalize(iso_stream); 3943 } 3944 } 3945 break; 3946 case HCI_SUBEVENT_LE_CREATE_BIG_COMPLETE: 3947 big = hci_big_for_handle(packet[4]); 3948 if (big != NULL){ 3949 uint8_t status = packet[3]; 3950 if (status == ERROR_CODE_SUCCESS){ 3951 // store bis_con_handles and trigger iso path setup 3952 uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[20]); 3953 uint8_t i; 3954 for (i=0;i<num_bis;i++){ 3955 hci_con_handle_t bis_handle = (hci_con_handle_t) little_endian_read_16(packet, 21 + (2 * i)); 3956 big->bis_con_handles[i] = bis_handle; 3957 // assign bis handle 3958 btstack_linked_list_iterator_t it; 3959 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 3960 while (btstack_linked_list_iterator_has_next(&it)){ 3961 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 3962 if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) && 3963 (iso_stream->big_handle == big->big_handle)){ 3964 iso_stream->con_handle = bis_handle; 3965 iso_stream->state = HCI_ISO_STREAM_STATE_ESTABLISHED; 3966 break; 3967 } 3968 } 3969 } 3970 if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) { 3971 big->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 3972 big->state_vars.next_bis = 0; 3973 } 3974 } else { 3975 // create BIG failed or has been stopped by us 3976 hci_iso_stream_requested_finalize(big->big_handle); 3977 btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 3978 if (big->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED){ 3979 hci_emit_big_created(big, status); 3980 } else { 3981 hci_emit_big_terminated(big); 3982 } 3983 } 3984 } 3985 break; 3986 case HCI_SUBEVENT_LE_TERMINATE_BIG_COMPLETE: 3987 big = hci_big_for_handle(hci_subevent_le_terminate_big_complete_get_big_handle(packet)); 3988 if (big != NULL){ 3989 // finalize associated ISO streams 3990 btstack_linked_list_iterator_t it; 3991 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 3992 while (btstack_linked_list_iterator_has_next(&it)){ 3993 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 3994 if (iso_stream->big_handle == big->big_handle){ 3995 log_info("BIG Terminated, big_handle 0x%02x, con handle 0x%04x", iso_stream->big_handle, iso_stream->con_handle); 3996 btstack_linked_list_iterator_remove(&it); 3997 btstack_memory_hci_iso_stream_free(iso_stream); 3998 } 3999 } 4000 btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 4001 switch (big->state){ 4002 case LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED: 4003 hci_emit_big_created(big, big->state_vars.status); 4004 break; 4005 default: 4006 hci_emit_big_terminated(big); 4007 break; 4008 } 4009 } 4010 break; 4011 case HCI_SUBEVENT_LE_BIG_SYNC_ESTABLISHED: 4012 big_sync = hci_big_sync_for_handle(packet[4]); 4013 if (big_sync != NULL){ 4014 uint8_t status = packet[3]; 4015 uint8_t big_handle = packet[4]; 4016 if (status == ERROR_CODE_SUCCESS){ 4017 // store bis_con_handles and trigger iso path setup 4018 uint8_t num_bis = btstack_min(MAX_NR_BIS, packet[16]); 4019 uint8_t i; 4020 for (i=0;i<num_bis;i++){ 4021 big_sync->bis_con_handles[i] = little_endian_read_16(packet, 17 + (2 * i)); 4022 } 4023 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) { 4024 // trigger iso path setup 4025 big_sync->state = LE_AUDIO_BIG_STATE_SETUP_ISO_PATH; 4026 big_sync->state_vars.next_bis = 0; 4027 } 4028 } else { 4029 // create BIG Sync failed or has been stopped by us 4030 btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 4031 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_ESTABLISHED) { 4032 hci_emit_big_sync_created(big_sync, status); 4033 } else { 4034 hci_emit_big_sync_stopped(big_handle); 4035 } 4036 } 4037 } 4038 break; 4039 case HCI_SUBEVENT_LE_BIG_SYNC_LOST: 4040 big_sync = hci_big_sync_for_handle(packet[4]); 4041 if (big_sync != NULL){ 4042 uint8_t big_handle = packet[4]; 4043 btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 4044 hci_emit_big_sync_stopped(big_handle); 4045 } 4046 break; 4047 #endif 4048 default: 4049 break; 4050 } 4051 break; 4052 #endif 4053 case HCI_EVENT_VENDOR_SPECIFIC: 4054 // Vendor specific commands often create vendor specific event instead of num completed packets 4055 // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour 4056 switch (hci_stack->manufacturer){ 4057 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO: 4058 hci_stack->num_cmd_packets = 1; 4059 break; 4060 default: 4061 break; 4062 } 4063 break; 4064 default: 4065 break; 4066 } 4067 4068 handle_event_for_current_stack_state(packet, size); 4069 4070 // notify upper stack 4071 hci_emit_event(packet, size, 0); // don't dump, already happened in packet handler 4072 4073 // moved here to give upper stack a chance to close down everything with hci_connection_t intact 4074 if ((hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE) && (packet[2] == 0)){ 4075 handle = little_endian_read_16(packet, 3); 4076 hci_connection_t * aConn = hci_connection_for_handle(handle); 4077 // discard connection if app did not trigger a reconnect in the event handler 4078 if (aConn && aConn->state == RECEIVED_DISCONNECTION_COMPLETE){ 4079 hci_shutdown_connection(aConn); 4080 } 4081 #ifdef ENABLE_CONTROLLER_DUMP_PACKETS 4082 hci_controller_dump_packets(); 4083 #endif 4084 } 4085 4086 // execute main loop 4087 hci_run(); 4088 } 4089 4090 #ifdef ENABLE_CLASSIC 4091 4092 #ifdef ENABLE_SCO_OVER_HCI 4093 static void sco_tx_timeout_handler(btstack_timer_source_t * ts); 4094 static void sco_schedule_tx(hci_connection_t * conn); 4095 4096 static void sco_tx_timeout_handler(btstack_timer_source_t * ts){ 4097 log_debug("SCO TX Timeout"); 4098 hci_con_handle_t con_handle = (hci_con_handle_t) (uintptr_t) btstack_run_loop_get_timer_context(ts); 4099 hci_connection_t * conn = hci_connection_for_handle(con_handle); 4100 if (!conn) return; 4101 4102 // trigger send 4103 conn->sco_tx_ready = 1; 4104 // extra packet if CVSD but SCO buffer is too short 4105 if (((hci_stack->sco_voice_setting_active & 0x03) != 0x03) && (hci_stack->sco_data_packet_length < 123)){ 4106 conn->sco_tx_ready++; 4107 } 4108 hci_notify_if_sco_can_send_now(); 4109 } 4110 4111 4112 #define SCO_TX_AFTER_RX_MS (6) 4113 4114 static void sco_schedule_tx(hci_connection_t * conn){ 4115 4116 uint32_t now = btstack_run_loop_get_time_ms(); 4117 uint32_t sco_tx_ms = conn->sco_rx_ms + SCO_TX_AFTER_RX_MS; 4118 int time_delta_ms = sco_tx_ms - now; 4119 4120 btstack_timer_source_t * timer = (conn->sco_rx_count & 1) ? &conn->timeout : &conn->timeout_sco; 4121 4122 // log_error("SCO TX at %u in %u", (int) sco_tx_ms, time_delta_ms); 4123 btstack_run_loop_remove_timer(timer); 4124 btstack_run_loop_set_timer(timer, time_delta_ms); 4125 btstack_run_loop_set_timer_context(timer, (void *) (uintptr_t) conn->con_handle); 4126 btstack_run_loop_set_timer_handler(timer, &sco_tx_timeout_handler); 4127 btstack_run_loop_add_timer(timer); 4128 } 4129 #endif 4130 4131 static void sco_handler(uint8_t * packet, uint16_t size){ 4132 // lookup connection struct 4133 hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet); 4134 hci_connection_t * conn = hci_connection_for_handle(con_handle); 4135 if (!conn) return; 4136 4137 #ifdef ENABLE_SCO_OVER_HCI 4138 // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes 4139 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){ 4140 if ((size == 83) && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){ 4141 packet[2] = 0x3c; 4142 memmove(&packet[3], &packet[23], 63); 4143 size = 63; 4144 } 4145 } 4146 4147 if (hci_have_usb_transport()){ 4148 // Nothing to do 4149 } else { 4150 // log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent); 4151 if (hci_stack->synchronous_flow_control_enabled == 0){ 4152 uint32_t now = btstack_run_loop_get_time_ms(); 4153 4154 if (!conn->sco_rx_valid){ 4155 // ignore first 10 packets 4156 conn->sco_rx_count++; 4157 // log_debug("sco rx count %u", conn->sco_rx_count); 4158 if (conn->sco_rx_count == 10) { 4159 // use first timestamp as is and pretent it just started 4160 conn->sco_rx_ms = now; 4161 conn->sco_rx_valid = 1; 4162 conn->sco_rx_count = 0; 4163 sco_schedule_tx(conn); 4164 } 4165 } else { 4166 // track expected arrival timme 4167 conn->sco_rx_count++; 4168 conn->sco_rx_ms += 7; 4169 int delta = (int32_t) (now - conn->sco_rx_ms); 4170 if (delta > 0){ 4171 conn->sco_rx_ms++; 4172 } 4173 // log_debug("sco rx %u", conn->sco_rx_ms); 4174 sco_schedule_tx(conn); 4175 } 4176 } 4177 } 4178 #endif 4179 4180 // deliver to app 4181 if (hci_stack->sco_packet_handler) { 4182 hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size); 4183 } 4184 4185 #ifdef HAVE_SCO_TRANSPORT 4186 // We can send one packet for each received packet 4187 conn->sco_tx_ready++; 4188 hci_notify_if_sco_can_send_now(); 4189 #endif 4190 4191 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 4192 conn->num_packets_completed++; 4193 hci_stack->host_completed_packets = 1; 4194 hci_run(); 4195 #endif 4196 } 4197 #endif 4198 4199 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 4200 hci_dump_packet(packet_type, 1, packet, size); 4201 switch (packet_type) { 4202 case HCI_EVENT_PACKET: 4203 event_handler(packet, size); 4204 break; 4205 case HCI_ACL_DATA_PACKET: 4206 acl_handler(packet, size); 4207 break; 4208 #ifdef ENABLE_CLASSIC 4209 case HCI_SCO_DATA_PACKET: 4210 sco_handler(packet, size); 4211 break; 4212 #endif 4213 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4214 case HCI_ISO_DATA_PACKET: 4215 hci_iso_packet_handler(packet, size); 4216 break; 4217 #endif 4218 default: 4219 break; 4220 } 4221 } 4222 4223 /** 4224 * @brief Add event packet handler. 4225 */ 4226 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4227 btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler); 4228 } 4229 4230 /** 4231 * @brief Remove event packet handler. 4232 */ 4233 void hci_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){ 4234 btstack_linked_list_remove(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler); 4235 } 4236 4237 /** Register HCI packet handlers */ 4238 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){ 4239 hci_stack->acl_packet_handler = handler; 4240 } 4241 4242 #ifdef ENABLE_CLASSIC 4243 /** 4244 * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles. 4245 */ 4246 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){ 4247 hci_stack->sco_packet_handler = handler; 4248 } 4249 #endif 4250 4251 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4252 void hci_register_iso_packet_handler(btstack_packet_handler_t handler){ 4253 hci_stack->iso_packet_handler = handler; 4254 } 4255 #endif 4256 4257 static void hci_state_reset(void){ 4258 // no connections yet 4259 hci_stack->connections = NULL; 4260 4261 // keep discoverable/connectable as this has been requested by the client(s) 4262 // hci_stack->discoverable = 0; 4263 // hci_stack->connectable = 0; 4264 // hci_stack->bondable = 1; 4265 // hci_stack->own_addr_type = 0; 4266 4267 // buffer is free 4268 hci_stack->hci_packet_buffer_reserved = false; 4269 4270 // no pending cmds 4271 hci_stack->decline_reason = 0; 4272 4273 hci_stack->secure_connections_active = false; 4274 4275 #ifdef ENABLE_CLASSIC 4276 hci_stack->inquiry_lap = GAP_IAC_GENERAL_INQUIRY; 4277 hci_stack->page_timeout = 0x6000; // ca. 15 sec 4278 4279 hci_stack->gap_tasks_classic = 4280 GAP_TASK_SET_DEFAULT_LINK_POLICY | 4281 GAP_TASK_SET_CLASS_OF_DEVICE | 4282 GAP_TASK_SET_LOCAL_NAME | 4283 GAP_TASK_SET_EIR_DATA | 4284 GAP_TASK_WRITE_SCAN_ENABLE | 4285 GAP_TASK_WRITE_PAGE_TIMEOUT; 4286 #endif 4287 4288 #ifdef ENABLE_CLASSIC_PAIRING_OOB 4289 hci_stack->classic_read_local_oob_data = false; 4290 hci_stack->classic_oob_con_handle = HCI_CON_HANDLE_INVALID; 4291 #endif 4292 4293 // LE 4294 #ifdef ENABLE_BLE 4295 memset(hci_stack->le_random_address, 0, 6); 4296 hci_stack->le_random_address_set = 0; 4297 #endif 4298 #ifdef ENABLE_LE_CENTRAL 4299 hci_stack->le_scanning_active = false; 4300 hci_stack->le_scanning_param_update = true; 4301 hci_stack->le_connecting_state = LE_CONNECTING_IDLE; 4302 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 4303 hci_stack->le_whitelist_capacity = 0; 4304 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 4305 hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID; 4306 #endif 4307 #endif 4308 #ifdef ENABLE_LE_PERIPHERAL 4309 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 4310 if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_PARAMS_SET) != 0){ 4311 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 4312 } 4313 if (hci_stack->le_advertisements_data != NULL){ 4314 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 4315 } 4316 #endif 4317 } 4318 4319 #ifdef ENABLE_CLASSIC 4320 /** 4321 * @brief Configure Bluetooth hardware control. Has to be called before power on. 4322 */ 4323 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){ 4324 // store and open remote device db 4325 hci_stack->link_key_db = link_key_db; 4326 if (hci_stack->link_key_db) { 4327 hci_stack->link_key_db->open(); 4328 } 4329 } 4330 #endif 4331 4332 void hci_init(const hci_transport_t *transport, const void *config){ 4333 4334 #ifdef HAVE_MALLOC 4335 if (!hci_stack) { 4336 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 4337 } 4338 #else 4339 hci_stack = &hci_stack_static; 4340 #endif 4341 memset(hci_stack, 0, sizeof(hci_stack_t)); 4342 4343 // reference to use transport layer implementation 4344 hci_stack->hci_transport = transport; 4345 4346 // reference to used config 4347 hci_stack->config = config; 4348 4349 // setup pointer for outgoing packet buffer 4350 hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE]; 4351 4352 // max acl payload size defined in config.h 4353 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 4354 4355 // register packet handlers with transport 4356 transport->register_packet_handler(&packet_handler); 4357 4358 hci_stack->state = HCI_STATE_OFF; 4359 4360 // class of device 4361 hci_stack->class_of_device = 0x007a020c; // Smartphone 4362 4363 // bondable by default 4364 hci_stack->bondable = 1; 4365 4366 #ifdef ENABLE_CLASSIC 4367 // classic name 4368 hci_stack->local_name = default_classic_name; 4369 4370 // Master slave policy 4371 hci_stack->master_slave_policy = 1; 4372 4373 // Allow Role Switch 4374 hci_stack->allow_role_switch = 1; 4375 4376 // Default / minimum security level = 2 4377 hci_stack->gap_security_level = LEVEL_2; 4378 4379 // Default Security Mode 4 4380 hci_stack->gap_security_mode = GAP_SECURITY_MODE_4; 4381 4382 // Errata-11838 mandates 7 bytes for GAP Security Level 1-3 4383 hci_stack->gap_required_encyrption_key_size = 7; 4384 4385 // Link Supervision Timeout 4386 hci_stack->link_supervision_timeout = HCI_LINK_SUPERVISION_TIMEOUT_DEFAULT; 4387 4388 #endif 4389 4390 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 4391 hci_stack->ssp_enable = 1; 4392 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 4393 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 4394 hci_stack->ssp_auto_accept = 1; 4395 4396 // Secure Connections: enable (requires support from Controller) 4397 hci_stack->secure_connections_enable = true; 4398 4399 // voice setting - signed 16 bit pcm data with CVSD over the air 4400 hci_stack->sco_voice_setting = 0x60; 4401 4402 #ifdef ENABLE_LE_CENTRAL 4403 // connection parameter to use for outgoing connections 4404 hci_stack->le_connection_scan_interval = 0x0060; // 60ms 4405 hci_stack->le_connection_scan_window = 0x0030; // 30ms 4406 hci_stack->le_connection_interval_min = 0x0008; // 10 ms 4407 hci_stack->le_connection_interval_max = 0x0018; // 30 ms 4408 hci_stack->le_connection_latency = 4; // 4 4409 hci_stack->le_supervision_timeout = 0x0048; // 720 ms 4410 hci_stack->le_minimum_ce_length = 2; // 1.25 ms 4411 hci_stack->le_maximum_ce_length = 0x0030; // 30 ms 4412 4413 // default LE Scanning 4414 hci_stack->le_scan_type = 0x1; // active 4415 hci_stack->le_scan_interval = 0x1e0; // 300 ms 4416 hci_stack->le_scan_window = 0x30; // 30 ms 4417 #endif 4418 4419 #ifdef ENABLE_LE_PERIPHERAL 4420 hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral 4421 #endif 4422 4423 // connection parameter range used to answer connection parameter update requests in l2cap 4424 hci_stack->le_connection_parameter_range.le_conn_interval_min = 6; 4425 hci_stack->le_connection_parameter_range.le_conn_interval_max = 3200; 4426 hci_stack->le_connection_parameter_range.le_conn_latency_min = 0; 4427 hci_stack->le_connection_parameter_range.le_conn_latency_max = 500; 4428 hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 10; 4429 hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200; 4430 4431 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4432 hci_stack->iso_packets_to_queue = 1; 4433 #endif 4434 4435 hci_state_reset(); 4436 } 4437 4438 void hci_deinit(void){ 4439 btstack_run_loop_remove_timer(&hci_stack->timeout); 4440 #ifdef HAVE_MALLOC 4441 if (hci_stack) { 4442 free(hci_stack); 4443 } 4444 #endif 4445 hci_stack = NULL; 4446 4447 #ifdef ENABLE_CLASSIC 4448 disable_l2cap_timeouts = 0; 4449 #endif 4450 } 4451 4452 /** 4453 * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information 4454 */ 4455 void hci_set_chipset(const btstack_chipset_t *chipset_driver){ 4456 hci_stack->chipset = chipset_driver; 4457 4458 // reset chipset driver - init is also called on power_up 4459 if (hci_stack->chipset && hci_stack->chipset->init){ 4460 hci_stack->chipset->init(hci_stack->config); 4461 } 4462 } 4463 4464 /** 4465 * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on. 4466 */ 4467 void hci_set_control(const btstack_control_t *hardware_control){ 4468 // references to used control implementation 4469 hci_stack->control = hardware_control; 4470 // init with transport config 4471 hardware_control->init(hci_stack->config); 4472 } 4473 4474 static void hci_discard_connections(void){ 4475 btstack_linked_list_iterator_t it; 4476 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 4477 while (btstack_linked_list_iterator_has_next(&it)){ 4478 // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection 4479 hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 4480 hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host 4481 hci_shutdown_connection(connection); 4482 } 4483 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 4484 while (hci_stack->iso_streams != NULL){ 4485 hci_iso_stream_finalize((hci_iso_stream_t *) hci_stack->iso_streams); 4486 } 4487 #endif 4488 } 4489 4490 void hci_close(void){ 4491 4492 #ifdef ENABLE_CLASSIC 4493 // close remote device db 4494 if (hci_stack->link_key_db) { 4495 hci_stack->link_key_db->close(); 4496 } 4497 #endif 4498 4499 hci_discard_connections(); 4500 4501 hci_power_control(HCI_POWER_OFF); 4502 4503 #ifdef HAVE_MALLOC 4504 free(hci_stack); 4505 #endif 4506 hci_stack = NULL; 4507 } 4508 4509 #ifdef HAVE_SCO_TRANSPORT 4510 void hci_set_sco_transport(const btstack_sco_transport_t *sco_transport){ 4511 hci_stack->sco_transport = sco_transport; 4512 sco_transport->register_packet_handler(&packet_handler); 4513 } 4514 #endif 4515 4516 #ifdef ENABLE_CLASSIC 4517 void gap_set_required_encryption_key_size(uint8_t encryption_key_size){ 4518 // validate ranage and set 4519 if (encryption_key_size < 7) return; 4520 if (encryption_key_size > 16) return; 4521 hci_stack->gap_required_encyrption_key_size = encryption_key_size; 4522 } 4523 4524 uint8_t gap_set_security_mode(gap_security_mode_t security_mode){ 4525 if ((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)){ 4526 hci_stack->gap_security_mode = security_mode; 4527 return ERROR_CODE_SUCCESS; 4528 } else { 4529 return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; 4530 } 4531 } 4532 4533 gap_security_mode_t gap_get_security_mode(void){ 4534 return hci_stack->gap_security_mode; 4535 } 4536 4537 void gap_set_security_level(gap_security_level_t security_level){ 4538 hci_stack->gap_security_level = security_level; 4539 } 4540 4541 gap_security_level_t gap_get_security_level(void){ 4542 if (hci_stack->gap_secure_connections_only_mode){ 4543 return LEVEL_4; 4544 } 4545 return hci_stack->gap_security_level; 4546 } 4547 4548 void gap_set_minimal_service_security_level(gap_security_level_t security_level){ 4549 hci_stack->gap_minimal_service_security_level = security_level; 4550 } 4551 4552 void gap_set_secure_connections_only_mode(bool enable){ 4553 hci_stack->gap_secure_connections_only_mode = enable; 4554 } 4555 4556 bool gap_get_secure_connections_only_mode(void){ 4557 return hci_stack->gap_secure_connections_only_mode; 4558 } 4559 #endif 4560 4561 #ifdef ENABLE_CLASSIC 4562 void gap_set_class_of_device(uint32_t class_of_device){ 4563 hci_stack->class_of_device = class_of_device; 4564 hci_stack->gap_tasks_classic |= GAP_TASK_SET_CLASS_OF_DEVICE; 4565 hci_run(); 4566 } 4567 4568 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){ 4569 hci_stack->default_link_policy_settings = default_link_policy_settings; 4570 hci_stack->gap_tasks_classic |= GAP_TASK_SET_DEFAULT_LINK_POLICY; 4571 hci_run(); 4572 } 4573 4574 void gap_set_allow_role_switch(bool allow_role_switch){ 4575 hci_stack->allow_role_switch = allow_role_switch ? 1 : 0; 4576 } 4577 4578 uint8_t hci_get_allow_role_switch(void){ 4579 return hci_stack->allow_role_switch; 4580 } 4581 4582 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){ 4583 hci_stack->link_supervision_timeout = link_supervision_timeout; 4584 } 4585 4586 void gap_enable_link_watchdog(uint16_t timeout_ms){ 4587 hci_stack->automatic_flush_timeout = btstack_min(timeout_ms, 1280) * 8 / 5; // divide by 0.625 4588 } 4589 4590 uint16_t hci_automatic_flush_timeout(void){ 4591 return hci_stack->automatic_flush_timeout; 4592 } 4593 4594 void hci_disable_l2cap_timeout_check(void){ 4595 disable_l2cap_timeouts = 1; 4596 } 4597 #endif 4598 4599 #ifndef HAVE_HOST_CONTROLLER_API 4600 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h 4601 void hci_set_bd_addr(bd_addr_t addr){ 4602 (void)memcpy(hci_stack->custom_bd_addr, addr, 6); 4603 hci_stack->custom_bd_addr_set = 1; 4604 } 4605 #endif 4606 4607 // State-Module-Driver overview 4608 // state module low-level 4609 // HCI_STATE_OFF off close 4610 // HCI_STATE_INITIALIZING, on open 4611 // HCI_STATE_WORKING, on open 4612 // HCI_STATE_HALTING, on open 4613 // HCI_STATE_SLEEPING, off/sleep close 4614 // HCI_STATE_FALLING_ASLEEP on open 4615 4616 static int hci_power_control_on(void){ 4617 4618 // power on 4619 int err = 0; 4620 if (hci_stack->control && hci_stack->control->on){ 4621 err = (*hci_stack->control->on)(); 4622 } 4623 if (err){ 4624 log_error( "POWER_ON failed"); 4625 hci_emit_hci_open_failed(); 4626 return err; 4627 } 4628 4629 // int chipset driver 4630 if (hci_stack->chipset && hci_stack->chipset->init){ 4631 hci_stack->chipset->init(hci_stack->config); 4632 } 4633 4634 // init transport 4635 if (hci_stack->hci_transport->init){ 4636 hci_stack->hci_transport->init(hci_stack->config); 4637 } 4638 4639 // open transport 4640 err = hci_stack->hci_transport->open(); 4641 if (err){ 4642 log_error( "HCI_INIT failed, turning Bluetooth off again"); 4643 if (hci_stack->control && hci_stack->control->off){ 4644 (*hci_stack->control->off)(); 4645 } 4646 hci_emit_hci_open_failed(); 4647 return err; 4648 } 4649 return 0; 4650 } 4651 4652 static void hci_power_control_off(void){ 4653 4654 log_info("hci_power_control_off"); 4655 4656 // close low-level device 4657 hci_stack->hci_transport->close(); 4658 4659 log_info("hci_power_control_off - hci_transport closed"); 4660 4661 // power off 4662 if (hci_stack->control && hci_stack->control->off){ 4663 (*hci_stack->control->off)(); 4664 } 4665 4666 log_info("hci_power_control_off - control closed"); 4667 4668 hci_stack->state = HCI_STATE_OFF; 4669 } 4670 4671 static void hci_power_control_sleep(void){ 4672 4673 log_info("hci_power_control_sleep"); 4674 4675 #if 0 4676 // don't close serial port during sleep 4677 4678 // close low-level device 4679 hci_stack->hci_transport->close(hci_stack->config); 4680 #endif 4681 4682 // sleep mode 4683 if (hci_stack->control && hci_stack->control->sleep){ 4684 (*hci_stack->control->sleep)(); 4685 } 4686 4687 hci_stack->state = HCI_STATE_SLEEPING; 4688 } 4689 4690 static int hci_power_control_wake(void){ 4691 4692 log_info("hci_power_control_wake"); 4693 4694 // wake on 4695 if (hci_stack->control && hci_stack->control->wake){ 4696 (*hci_stack->control->wake)(); 4697 } 4698 4699 #if 0 4700 // open low-level device 4701 int err = hci_stack->hci_transport->open(hci_stack->config); 4702 if (err){ 4703 log_error( "HCI_INIT failed, turning Bluetooth off again"); 4704 if (hci_stack->control && hci_stack->control->off){ 4705 (*hci_stack->control->off)(); 4706 } 4707 hci_emit_hci_open_failed(); 4708 return err; 4709 } 4710 #endif 4711 4712 return 0; 4713 } 4714 4715 static void hci_power_enter_initializing_state(void){ 4716 // set up state machine 4717 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 4718 hci_stack->hci_packet_buffer_reserved = false; 4719 hci_stack->state = HCI_STATE_INITIALIZING; 4720 hci_stack->substate = HCI_INIT_SEND_RESET; 4721 } 4722 4723 static void hci_power_enter_halting_state(void){ 4724 #ifdef ENABLE_BLE 4725 hci_whitelist_free(); 4726 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 4727 hci_periodic_advertiser_list_free(); 4728 #endif 4729 #endif 4730 // see hci_run 4731 hci_stack->state = HCI_STATE_HALTING; 4732 hci_stack->substate = HCI_HALTING_CLASSIC_STOP; 4733 // setup watchdog timer for disconnect - only triggers if Controller does not respond anymore 4734 btstack_run_loop_set_timer(&hci_stack->timeout, 1000); 4735 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler); 4736 btstack_run_loop_add_timer(&hci_stack->timeout); 4737 } 4738 4739 // returns error 4740 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){ 4741 int err; 4742 switch (power_mode){ 4743 case HCI_POWER_ON: 4744 err = hci_power_control_on(); 4745 if (err != 0) { 4746 log_error("hci_power_control_on() error %d", err); 4747 return err; 4748 } 4749 hci_power_enter_initializing_state(); 4750 break; 4751 case HCI_POWER_OFF: 4752 // do nothing 4753 break; 4754 case HCI_POWER_SLEEP: 4755 // do nothing (with SLEEP == OFF) 4756 break; 4757 default: 4758 btstack_assert(false); 4759 break; 4760 } 4761 return ERROR_CODE_SUCCESS; 4762 } 4763 4764 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){ 4765 switch (power_mode){ 4766 case HCI_POWER_ON: 4767 // do nothing 4768 break; 4769 case HCI_POWER_OFF: 4770 // no connections yet, just turn it off 4771 hci_power_control_off(); 4772 break; 4773 case HCI_POWER_SLEEP: 4774 // no connections yet, just turn it off 4775 hci_power_control_sleep(); 4776 break; 4777 default: 4778 btstack_assert(false); 4779 break; 4780 } 4781 return ERROR_CODE_SUCCESS; 4782 } 4783 4784 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) { 4785 switch (power_mode){ 4786 case HCI_POWER_ON: 4787 // do nothing 4788 break; 4789 case HCI_POWER_OFF: 4790 hci_power_enter_halting_state(); 4791 break; 4792 case HCI_POWER_SLEEP: 4793 // see hci_run 4794 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 4795 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 4796 break; 4797 default: 4798 btstack_assert(false); 4799 break; 4800 } 4801 return ERROR_CODE_SUCCESS; 4802 } 4803 4804 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) { 4805 switch (power_mode){ 4806 case HCI_POWER_ON: 4807 hci_power_enter_initializing_state(); 4808 break; 4809 case HCI_POWER_OFF: 4810 // do nothing 4811 break; 4812 case HCI_POWER_SLEEP: 4813 // see hci_run 4814 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 4815 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 4816 break; 4817 default: 4818 btstack_assert(false); 4819 break; 4820 } 4821 return ERROR_CODE_SUCCESS; 4822 } 4823 4824 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) { 4825 switch (power_mode){ 4826 case HCI_POWER_ON: 4827 hci_power_enter_initializing_state(); 4828 break; 4829 case HCI_POWER_OFF: 4830 hci_power_enter_halting_state(); 4831 break; 4832 case HCI_POWER_SLEEP: 4833 // do nothing 4834 break; 4835 default: 4836 btstack_assert(false); 4837 break; 4838 } 4839 return ERROR_CODE_SUCCESS; 4840 } 4841 4842 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) { 4843 int err; 4844 switch (power_mode){ 4845 case HCI_POWER_ON: 4846 err = hci_power_control_wake(); 4847 if (err) return err; 4848 hci_power_enter_initializing_state(); 4849 break; 4850 case HCI_POWER_OFF: 4851 hci_power_enter_halting_state(); 4852 break; 4853 case HCI_POWER_SLEEP: 4854 // do nothing 4855 break; 4856 default: 4857 btstack_assert(false); 4858 break; 4859 } 4860 return ERROR_CODE_SUCCESS; 4861 } 4862 4863 int hci_power_control(HCI_POWER_MODE power_mode){ 4864 log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state); 4865 int err = 0; 4866 switch (hci_stack->state){ 4867 case HCI_STATE_OFF: 4868 err = hci_power_control_state_off(power_mode); 4869 break; 4870 case HCI_STATE_INITIALIZING: 4871 err = hci_power_control_state_initializing(power_mode); 4872 break; 4873 case HCI_STATE_WORKING: 4874 err = hci_power_control_state_working(power_mode); 4875 break; 4876 case HCI_STATE_HALTING: 4877 err = hci_power_control_state_halting(power_mode); 4878 break; 4879 case HCI_STATE_FALLING_ASLEEP: 4880 err = hci_power_control_state_falling_asleep(power_mode); 4881 break; 4882 case HCI_STATE_SLEEPING: 4883 err = hci_power_control_state_sleeping(power_mode); 4884 break; 4885 default: 4886 btstack_assert(false); 4887 break; 4888 } 4889 if (err != 0){ 4890 return err; 4891 } 4892 4893 // create internal event 4894 hci_emit_state(); 4895 4896 // trigger next/first action 4897 hci_run(); 4898 4899 return 0; 4900 } 4901 4902 4903 static void hci_halting_run(void) { 4904 4905 log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate); 4906 4907 hci_connection_t *connection; 4908 #ifdef ENABLE_BLE 4909 #ifdef ENABLE_LE_PERIPHERAL 4910 bool stop_advertismenets; 4911 #endif 4912 #endif 4913 4914 switch (hci_stack->substate) { 4915 case HCI_HALTING_CLASSIC_STOP: 4916 #ifdef ENABLE_CLASSIC 4917 if (!hci_can_send_command_packet_now()) return; 4918 4919 if (hci_stack->connectable || hci_stack->discoverable){ 4920 hci_stack->substate = HCI_HALTING_LE_ADV_STOP; 4921 hci_send_cmd(&hci_write_scan_enable, 0); 4922 return; 4923 } 4924 #endif 4925 /* fall through */ 4926 4927 case HCI_HALTING_LE_ADV_STOP: 4928 hci_stack->substate = HCI_HALTING_LE_ADV_STOP; 4929 4930 #ifdef ENABLE_BLE 4931 #ifdef ENABLE_LE_PERIPHERAL 4932 if (!hci_can_send_command_packet_now()) return; 4933 4934 stop_advertismenets = (hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0; 4935 4936 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 4937 if (hci_extended_advertising_supported()){ 4938 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 4939 btstack_linked_list_iterator_t it; 4940 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 4941 // stop all periodic advertisements and check if an extended set is active 4942 while (btstack_linked_list_iterator_has_next(&it)){ 4943 le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it); 4944 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) { 4945 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE; 4946 hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_set->advertising_handle); 4947 return; 4948 } 4949 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) { 4950 stop_advertismenets = true; 4951 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 4952 } 4953 } 4954 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 4955 if (stop_advertismenets){ 4956 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 4957 hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 0, NULL, NULL, NULL); 4958 return; 4959 } 4960 } 4961 else 4962 #else /* ENABLE_LE_PERIPHERAL */ 4963 { 4964 if (stop_advertismenets) { 4965 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 4966 hci_send_cmd(&hci_le_set_advertise_enable, 0); 4967 return; 4968 } 4969 } 4970 #endif /* ENABLE_LE_EXTENDED_ADVERTISING*/ 4971 #endif /* ENABLE_LE_PERIPHERAL */ 4972 #endif /* ENABLE_BLE */ 4973 4974 /* fall through */ 4975 4976 case HCI_HALTING_LE_SCAN_STOP: 4977 hci_stack->substate = HCI_HALTING_LE_SCAN_STOP; 4978 if (!hci_can_send_command_packet_now()) return; 4979 4980 #ifdef ENABLE_BLE 4981 #ifdef ENABLE_LE_CENTRAL 4982 if (hci_stack->le_scanning_active){ 4983 hci_le_scan_stop(); 4984 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL; 4985 return; 4986 } 4987 #endif 4988 #endif 4989 4990 /* fall through */ 4991 4992 case HCI_HALTING_DISCONNECT_ALL: 4993 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL; 4994 if (!hci_can_send_command_packet_now()) return; 4995 4996 // close all open connections 4997 connection = (hci_connection_t *) hci_stack->connections; 4998 if (connection) { 4999 hci_con_handle_t con_handle = (uint16_t) connection->con_handle; 5000 5001 // check state 5002 if (connection->state == SENT_DISCONNECT) return; 5003 connection->state = SENT_DISCONNECT; 5004 5005 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle); 5006 5007 // finally, send the disconnect command 5008 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 5009 return; 5010 } 5011 5012 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 5013 // stop BIGs and BIG Syncs 5014 if (hci_stack->le_audio_bigs != NULL){ 5015 le_audio_big_t * big = (le_audio_big_t*) hci_stack->le_audio_bigs; 5016 if (big->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return; 5017 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 5018 hci_send_cmd(&hci_le_terminate_big, big->big_handle); 5019 return; 5020 } 5021 if (hci_stack->le_audio_big_syncs != NULL){ 5022 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t*) hci_stack->le_audio_big_syncs; 5023 if (big_sync->state == LE_AUDIO_BIG_STATE_W4_TERMINATED) return; 5024 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 5025 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle); 5026 return; 5027 } 5028 #endif 5029 5030 btstack_run_loop_remove_timer(&hci_stack->timeout); 5031 5032 // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event 5033 log_info("HCI_STATE_HALTING: wait 50 ms"); 5034 hci_stack->substate = HCI_HALTING_W4_CLOSE_TIMER; 5035 btstack_run_loop_set_timer(&hci_stack->timeout, 50); 5036 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler); 5037 btstack_run_loop_add_timer(&hci_stack->timeout); 5038 break; 5039 5040 case HCI_HALTING_CLOSE: 5041 // close left over connections (that had not been properly closed before) 5042 hci_discard_connections(); 5043 5044 log_info("HCI_STATE_HALTING, calling off"); 5045 5046 // switch mode 5047 hci_power_control_off(); 5048 5049 log_info("HCI_STATE_HALTING, emitting state"); 5050 hci_emit_state(); 5051 log_info("HCI_STATE_HALTING, done"); 5052 break; 5053 5054 case HCI_HALTING_W4_CLOSE_TIMER: 5055 // keep waiting 5056 5057 break; 5058 default: 5059 break; 5060 } 5061 }; 5062 5063 static void hci_falling_asleep_run(void){ 5064 hci_connection_t * connection; 5065 switch(hci_stack->substate) { 5066 case HCI_FALLING_ASLEEP_DISCONNECT: 5067 log_info("HCI_STATE_FALLING_ASLEEP"); 5068 // close all open connections 5069 connection = (hci_connection_t *) hci_stack->connections; 5070 if (connection){ 5071 5072 // send disconnect 5073 if (!hci_can_send_command_packet_now()) return; 5074 5075 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 5076 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 5077 5078 // send disconnected event right away - causes higher layer connections to get closed, too. 5079 hci_shutdown_connection(connection); 5080 return; 5081 } 5082 5083 if (hci_classic_supported()){ 5084 // disable page and inquiry scan 5085 if (!hci_can_send_command_packet_now()) return; 5086 5087 log_info("HCI_STATE_HALTING, disabling inq scans"); 5088 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 5089 5090 // continue in next sub state 5091 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE; 5092 break; 5093 } 5094 5095 /* fall through */ 5096 5097 case HCI_FALLING_ASLEEP_COMPLETE: 5098 log_info("HCI_STATE_HALTING, calling sleep"); 5099 // switch mode 5100 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 5101 hci_emit_state(); 5102 break; 5103 5104 default: 5105 break; 5106 } 5107 } 5108 5109 #ifdef ENABLE_CLASSIC 5110 5111 static void hci_update_scan_enable(void){ 5112 // 2 = page scan, 1 = inq scan 5113 hci_stack->new_scan_enable_value = (hci_stack->connectable << 1) | hci_stack->discoverable; 5114 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_SCAN_ENABLE; 5115 hci_run(); 5116 } 5117 5118 void gap_discoverable_control(uint8_t enable){ 5119 if (enable) enable = 1; // normalize argument 5120 5121 if (hci_stack->discoverable == enable){ 5122 hci_emit_scan_mode_changed(hci_stack->discoverable, hci_stack->connectable); 5123 return; 5124 } 5125 5126 hci_stack->discoverable = enable; 5127 hci_update_scan_enable(); 5128 } 5129 5130 void gap_connectable_control(uint8_t enable){ 5131 if (enable) enable = 1; // normalize argument 5132 5133 // don't emit event 5134 if (hci_stack->connectable == enable) return; 5135 5136 hci_stack->connectable = enable; 5137 hci_update_scan_enable(); 5138 } 5139 #endif 5140 5141 void gap_local_bd_addr(bd_addr_t address_buffer){ 5142 (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6); 5143 } 5144 5145 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 5146 static void hci_host_num_completed_packets(void){ 5147 5148 // create packet manually as arrays are not supported and num_commands should not get reduced 5149 hci_reserve_packet_buffer(); 5150 uint8_t * packet = hci_get_outgoing_packet_buffer(); 5151 5152 uint16_t size = 0; 5153 uint16_t num_handles = 0; 5154 packet[size++] = 0x35; 5155 packet[size++] = 0x0c; 5156 size++; // skip param len 5157 size++; // skip num handles 5158 5159 // add { handle, packets } entries 5160 btstack_linked_item_t * it; 5161 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 5162 hci_connection_t * connection = (hci_connection_t *) it; 5163 if (connection->num_packets_completed){ 5164 little_endian_store_16(packet, size, connection->con_handle); 5165 size += 2; 5166 little_endian_store_16(packet, size, connection->num_packets_completed); 5167 size += 2; 5168 // 5169 num_handles++; 5170 connection->num_packets_completed = 0; 5171 } 5172 } 5173 5174 packet[2] = size - 3; 5175 packet[3] = num_handles; 5176 5177 hci_stack->host_completed_packets = 0; 5178 5179 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 5180 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 5181 5182 // release packet buffer for synchronous transport implementations 5183 if (hci_transport_synchronous()){ 5184 hci_release_packet_buffer(); 5185 hci_emit_transport_packet_sent(); 5186 } 5187 } 5188 #endif 5189 5190 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){ 5191 UNUSED(ds); 5192 hci_stack->substate = HCI_HALTING_CLOSE; 5193 // allow packet handlers to defer final shutdown 5194 hci_emit_state(); 5195 hci_run(); 5196 } 5197 5198 static bool hci_run_acl_fragments(void){ 5199 if (hci_stack->acl_fragmentation_total_size > 0u) { 5200 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer); 5201 hci_connection_t *connection = hci_connection_for_handle(con_handle); 5202 if (connection) { 5203 if (hci_can_send_prepared_acl_packet_now(con_handle)){ 5204 hci_send_acl_packet_fragments(connection); 5205 return true; 5206 } 5207 } else { 5208 // connection gone -> discard further fragments 5209 log_info("hci_run: fragmented ACL packet no connection -> discard fragment"); 5210 hci_stack->acl_fragmentation_total_size = 0; 5211 hci_stack->acl_fragmentation_pos = 0; 5212 } 5213 } 5214 return false; 5215 } 5216 5217 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 5218 static bool hci_run_iso_fragments(void){ 5219 if (hci_stack->iso_fragmentation_total_size > 0u) { 5220 // TODO: flow control 5221 if (hci_transport_can_send_prepared_packet_now(HCI_ISO_DATA_PACKET)){ 5222 hci_send_iso_packet_fragments(); 5223 return true; 5224 } 5225 } 5226 return false; 5227 } 5228 #endif 5229 5230 #ifdef ENABLE_CLASSIC 5231 5232 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 5233 static bool hci_classic_operation_active(void) { 5234 if (hci_stack->inquiry_state >= GAP_INQUIRY_STATE_W4_ACTIVE){ 5235 return true; 5236 } 5237 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){ 5238 return true; 5239 } 5240 btstack_linked_item_t * it; 5241 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next) { 5242 hci_connection_t *connection = (hci_connection_t *) it; 5243 switch (connection->state) { 5244 case SENT_CREATE_CONNECTION: 5245 case SENT_CANCEL_CONNECTION: 5246 case SENT_DISCONNECT: 5247 return true; 5248 default: 5249 break; 5250 } 5251 } 5252 return false; 5253 } 5254 #endif 5255 5256 static bool hci_run_general_gap_classic(void){ 5257 5258 // assert stack is working and classic is active 5259 if (hci_classic_supported() == false) return false; 5260 if (hci_stack->state != HCI_STATE_WORKING) return false; 5261 5262 // decline incoming connections 5263 if (hci_stack->decline_reason){ 5264 uint8_t reason = hci_stack->decline_reason; 5265 hci_stack->decline_reason = 0; 5266 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 5267 return true; 5268 } 5269 5270 if (hci_stack->gap_tasks_classic != 0){ 5271 hci_run_gap_tasks_classic(); 5272 return true; 5273 } 5274 5275 // start/stop inquiry 5276 if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){ 5277 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 5278 if (hci_classic_operation_active() == false) 5279 #endif 5280 { 5281 uint8_t duration = hci_stack->inquiry_state; 5282 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE; 5283 if (hci_stack->inquiry_max_period_length != 0){ 5284 hci_send_cmd(&hci_periodic_inquiry_mode, hci_stack->inquiry_max_period_length, hci_stack->inquiry_min_period_length, hci_stack->inquiry_lap, duration, 0); 5285 } else { 5286 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0); 5287 } 5288 return true; 5289 } 5290 } 5291 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){ 5292 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED; 5293 hci_send_cmd(&hci_inquiry_cancel); 5294 return true; 5295 } 5296 5297 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_EXIT_PERIODIC){ 5298 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED; 5299 hci_send_cmd(&hci_exit_periodic_inquiry_mode); 5300 return true; 5301 } 5302 5303 // remote name request 5304 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){ 5305 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 5306 if (hci_classic_operation_active() == false) 5307 #endif 5308 { 5309 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE; 5310 hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr, 5311 hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset); 5312 return true; 5313 } 5314 } 5315 #ifdef ENABLE_CLASSIC_PAIRING_OOB 5316 // Local OOB data 5317 if (hci_stack->classic_read_local_oob_data){ 5318 hci_stack->classic_read_local_oob_data = false; 5319 if (hci_command_supported(SUPPORTED_HCI_COMMAND_READ_LOCAL_OOB_EXTENDED_DATA_COMMAND)){ 5320 hci_send_cmd(&hci_read_local_extended_oob_data); 5321 } else { 5322 hci_send_cmd(&hci_read_local_oob_data); 5323 } 5324 } 5325 #endif 5326 // pairing 5327 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){ 5328 uint8_t state = hci_stack->gap_pairing_state; 5329 uint8_t pin_code[16]; 5330 switch (state){ 5331 case GAP_PAIRING_STATE_SEND_PIN: 5332 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 5333 memset(pin_code, 0, 16); 5334 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len); 5335 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code); 5336 break; 5337 case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE: 5338 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE; 5339 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr); 5340 break; 5341 case GAP_PAIRING_STATE_SEND_PASSKEY: 5342 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 5343 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey); 5344 break; 5345 case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE: 5346 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE; 5347 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr); 5348 break; 5349 case GAP_PAIRING_STATE_SEND_CONFIRMATION: 5350 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 5351 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr); 5352 break; 5353 case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE: 5354 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_WAIT_FOR_COMMAND_COMPLETE; 5355 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr); 5356 break; 5357 default: 5358 break; 5359 } 5360 return true; 5361 } 5362 return false; 5363 } 5364 #endif 5365 5366 #ifdef ENABLE_BLE 5367 5368 #ifdef ENABLE_LE_CENTRAL 5369 static void hci_le_scan_stop(void){ 5370 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5371 if (hci_extended_advertising_supported()) { 5372 hci_send_cmd(&hci_le_set_extended_scan_enable, 0, 0, 0, 0); 5373 } else 5374 #endif 5375 { 5376 hci_send_cmd(&hci_le_set_scan_enable, 0, 0); 5377 } 5378 } 5379 #endif 5380 5381 #ifdef ENABLE_LE_PERIPHERAL 5382 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5383 uint8_t hci_le_extended_advertising_operation_for_chunk(uint16_t pos, uint16_t len){ 5384 uint8_t operation = 0; 5385 if (pos == 0){ 5386 // first fragment or complete data 5387 operation |= 1; 5388 } 5389 if (pos + LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN >= len){ 5390 // last fragment or complete data 5391 operation |= 2; 5392 } 5393 return operation; 5394 } 5395 #endif 5396 #endif 5397 5398 static bool hci_run_general_gap_le(void){ 5399 5400 btstack_linked_list_iterator_t lit; 5401 5402 // Phase 1: collect what to stop 5403 5404 #ifdef ENABLE_LE_CENTRAL 5405 bool scanning_stop = false; 5406 bool connecting_stop = false; 5407 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5408 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5409 bool periodic_sync_stop = false; 5410 #endif 5411 #endif 5412 #endif 5413 5414 #ifdef ENABLE_LE_PERIPHERAL 5415 bool advertising_stop = false; 5416 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5417 le_advertising_set_t * advertising_stop_set = NULL; 5418 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5419 bool periodic_advertising_stop = false; 5420 #endif 5421 #endif 5422 #endif 5423 5424 // check if own address changes 5425 bool random_address_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0; 5426 5427 // check if whitelist needs modification 5428 bool whitelist_modification_pending = false; 5429 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 5430 while (btstack_linked_list_iterator_has_next(&lit)){ 5431 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 5432 if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){ 5433 whitelist_modification_pending = true; 5434 break; 5435 } 5436 } 5437 5438 // check if resolving list needs modification 5439 bool resolving_list_modification_pending = false; 5440 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 5441 bool resolving_list_supported = hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE); 5442 if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){ 5443 resolving_list_modification_pending = true; 5444 } 5445 #endif 5446 5447 #ifdef ENABLE_LE_CENTRAL 5448 5449 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5450 // check if periodic advertiser list needs modification 5451 bool periodic_list_modification_pending = false; 5452 btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list); 5453 while (btstack_linked_list_iterator_has_next(&lit)){ 5454 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit); 5455 if (entry->state & (LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER | LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER)){ 5456 periodic_list_modification_pending = true; 5457 break; 5458 } 5459 } 5460 #endif 5461 5462 // scanning control 5463 if (hci_stack->le_scanning_active) { 5464 // stop if: 5465 // - parameter change required 5466 // - it's disabled 5467 // - whitelist change required but used for scanning 5468 // - resolving list modified 5469 // - own address changes 5470 bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1; 5471 if ((hci_stack->le_scanning_param_update) || 5472 !hci_stack->le_scanning_enabled || 5473 (scanning_uses_whitelist && whitelist_modification_pending) || 5474 resolving_list_modification_pending || 5475 random_address_change){ 5476 5477 scanning_stop = true; 5478 } 5479 } 5480 5481 // connecting control 5482 bool connecting_with_whitelist; 5483 switch (hci_stack->le_connecting_state){ 5484 case LE_CONNECTING_DIRECT: 5485 case LE_CONNECTING_WHITELIST: 5486 // stop connecting if: 5487 // - connecting uses white and whitelist modification pending 5488 // - if it got disabled 5489 // - resolving list modified 5490 // - own address changes 5491 connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST; 5492 if ((connecting_with_whitelist && whitelist_modification_pending) || 5493 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) || 5494 resolving_list_modification_pending || 5495 random_address_change) { 5496 5497 connecting_stop = true; 5498 } 5499 break; 5500 default: 5501 break; 5502 } 5503 5504 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5505 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5506 // periodic sync control 5507 bool sync_with_advertiser_list; 5508 switch(hci_stack->le_periodic_sync_state){ 5509 case LE_CONNECTING_DIRECT: 5510 case LE_CONNECTING_WHITELIST: 5511 // stop sync if: 5512 // - sync with advertiser list and advertiser list modification pending 5513 // - if it got disabled 5514 sync_with_advertiser_list = hci_stack->le_periodic_sync_state == LE_CONNECTING_WHITELIST; 5515 if ((sync_with_advertiser_list && periodic_list_modification_pending) || 5516 (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE)){ 5517 periodic_sync_stop = true; 5518 } 5519 break; 5520 default: 5521 break; 5522 } 5523 #endif 5524 #endif 5525 5526 #endif /* ENABLE_LE_CENTRAL */ 5527 5528 #ifdef ENABLE_LE_PERIPHERAL 5529 // le advertisement control 5530 if ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0){ 5531 // stop if: 5532 // - parameter change required 5533 // - random address used in advertising and changes 5534 // - it's disabled 5535 // - whitelist change required but used for advertisement filter policy 5536 // - resolving list modified 5537 // - own address changes 5538 bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0; 5539 bool advertising_uses_random_address = hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC; 5540 bool advertising_change = (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0; 5541 if (advertising_change || 5542 (advertising_uses_random_address && random_address_change) || 5543 (hci_stack->le_advertisements_enabled_for_current_roles == 0) || 5544 (advertising_uses_whitelist && whitelist_modification_pending) || 5545 resolving_list_modification_pending || 5546 random_address_change) { 5547 5548 advertising_stop = true; 5549 } 5550 } 5551 5552 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5553 if (hci_extended_advertising_supported() && (advertising_stop == false)){ 5554 btstack_linked_list_iterator_t it; 5555 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 5556 while (btstack_linked_list_iterator_has_next(&it)){ 5557 le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it); 5558 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) != 0) { 5559 // stop if: 5560 // - parameter change required 5561 // - random address used in connectable advertising and changes 5562 // - it's disabled 5563 // - whitelist change required but used for advertisement filter policy 5564 // - resolving list modified 5565 // - own address changes 5566 // - advertisement set will be removed 5567 bool advertising_uses_whitelist = advertising_set->extended_params.advertising_filter_policy != 0; 5568 bool advertising_connectable = (advertising_set->extended_params.advertising_event_properties & 1) != 0; 5569 bool advertising_uses_random_address = 5570 (advertising_set->extended_params.own_address_type != BD_ADDR_TYPE_LE_PUBLIC) && 5571 advertising_connectable; 5572 bool advertising_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0; 5573 bool advertising_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0; 5574 bool advertising_set_random_address_change = 5575 (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0; 5576 bool advertising_set_will_be_removed = 5577 (advertising_set->state & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0; 5578 if (advertising_parameter_change || 5579 (advertising_uses_random_address && advertising_set_random_address_change) || 5580 (advertising_enabled == false) || 5581 (advertising_uses_whitelist && whitelist_modification_pending) || 5582 resolving_list_modification_pending || 5583 advertising_set_will_be_removed) { 5584 5585 advertising_stop = true; 5586 advertising_stop_set = advertising_set; 5587 break; 5588 } 5589 } 5590 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5591 if ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) != 0) { 5592 // stop if: 5593 // - it's disabled 5594 // - parameter change required 5595 bool periodic_enabled = (advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0; 5596 bool periodic_parameter_change = (advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0; 5597 if ((periodic_enabled == false) || periodic_parameter_change){ 5598 periodic_advertising_stop = true; 5599 advertising_stop_set = advertising_set; 5600 } 5601 } 5602 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5603 } 5604 } 5605 #endif 5606 5607 #endif 5608 5609 5610 // Phase 2: stop everything that should be off during modifications 5611 5612 5613 // 2.1 Outgoing connection 5614 #ifdef ENABLE_LE_CENTRAL 5615 if (connecting_stop){ 5616 hci_send_cmd(&hci_le_create_connection_cancel); 5617 return true; 5618 } 5619 #endif 5620 5621 // 2.2 Scanning 5622 #ifdef ENABLE_LE_CENTRAL 5623 if (scanning_stop){ 5624 hci_stack->le_scanning_active = false; 5625 hci_le_scan_stop(); 5626 return true; 5627 } 5628 5629 // 2.3 Periodic Sync 5630 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5631 if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){ 5632 uint16_t sync_handle = hci_stack->le_periodic_terminate_sync_handle; 5633 hci_stack->le_periodic_terminate_sync_handle = HCI_CON_HANDLE_INVALID; 5634 hci_send_cmd(&hci_le_periodic_advertising_terminate_sync, sync_handle); 5635 return true; 5636 } 5637 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5638 if (periodic_sync_stop){ 5639 hci_stack->le_periodic_sync_state = LE_CONNECTING_CANCEL; 5640 hci_send_cmd(&hci_le_periodic_advertising_create_sync_cancel); 5641 return true; 5642 } 5643 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5644 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */ 5645 #endif /* ENABLE_LE_CENTRAL */ 5646 5647 // 2.4 Advertising: legacy, extended, periodic 5648 #ifdef ENABLE_LE_PERIPHERAL 5649 if (advertising_stop){ 5650 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5651 if (hci_extended_advertising_supported()) { 5652 uint8_t advertising_stop_handle; 5653 if (advertising_stop_set != NULL){ 5654 advertising_stop_handle = advertising_stop_set->advertising_handle; 5655 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5656 } else { 5657 advertising_stop_handle = 0; 5658 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5659 } 5660 const uint8_t advertising_handles[] = { advertising_stop_handle }; 5661 const uint16_t durations[] = { 0 }; 5662 const uint16_t max_events[] = { 0 }; 5663 hci_send_cmd(&hci_le_set_extended_advertising_enable, 0, 1, advertising_handles, durations, max_events); 5664 } else 5665 #endif 5666 { 5667 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ACTIVE; 5668 hci_send_cmd(&hci_le_set_advertise_enable, 0); 5669 } 5670 return true; 5671 } 5672 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5673 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5674 if (periodic_advertising_stop){ 5675 advertising_stop_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE; 5676 hci_send_cmd(&hci_le_set_periodic_advertising_enable, 0, advertising_stop_set->advertising_handle); 5677 return true; 5678 } 5679 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5680 #endif /* ENABLE_LE_EXTENDED_ADVERTISING */ 5681 #endif /* ENABLE_LE_PERIPHERAL */ 5682 5683 5684 // Phase 3: modify 5685 5686 if (random_address_change){ 5687 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 5688 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5689 if (hci_extended_advertising_supported()) { 5690 hci_send_cmd(&hci_le_set_advertising_set_random_address, 0, hci_stack->le_random_address); 5691 } 5692 #endif 5693 { 5694 hci_send_cmd(&hci_le_set_random_address, hci_stack->le_random_address); 5695 } 5696 return true; 5697 } 5698 5699 #ifdef ENABLE_LE_CENTRAL 5700 if (hci_stack->le_scanning_param_update){ 5701 hci_stack->le_scanning_param_update = false; 5702 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5703 if (hci_extended_advertising_supported()){ 5704 // prepare arrays for all PHYs 5705 uint8_t scan_types[1] = { hci_stack->le_scan_type }; 5706 uint16_t scan_intervals[1] = { hci_stack->le_scan_interval }; 5707 uint16_t scan_windows[1] = { hci_stack->le_scan_window }; 5708 uint8_t scanning_phys = 1; // LE 1M PHY 5709 hci_send_cmd(&hci_le_set_extended_scan_parameters, hci_stack->le_own_addr_type, 5710 hci_stack->le_scan_filter_policy, scanning_phys, scan_types, scan_intervals, scan_windows); 5711 } else 5712 #endif 5713 { 5714 hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, 5715 hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy); 5716 } 5717 return true; 5718 } 5719 #endif 5720 5721 #ifdef ENABLE_LE_PERIPHERAL 5722 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){ 5723 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 5724 hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type; 5725 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5726 if (hci_extended_advertising_supported()){ 5727 // map advertisment type to advertising event properties 5728 uint16_t adv_event_properties = 0; 5729 const uint16_t mapping[] = { 0b00010011, 0b00010101, 0b00011101, 0b00010010, 0b00010000}; 5730 if (hci_stack->le_advertisements_type < (sizeof(mapping)/sizeof(uint16_t))){ 5731 adv_event_properties = mapping[hci_stack->le_advertisements_type]; 5732 } 5733 hci_stack->le_advertising_set_in_current_command = 0; 5734 hci_send_cmd(&hci_le_set_extended_advertising_parameters, 5735 0, 5736 adv_event_properties, 5737 hci_stack->le_advertisements_interval_min, 5738 hci_stack->le_advertisements_interval_max, 5739 hci_stack->le_advertisements_channel_map, 5740 hci_stack->le_advertisements_own_addr_type, 5741 hci_stack->le_advertisements_direct_address_type, 5742 hci_stack->le_advertisements_direct_address, 5743 hci_stack->le_advertisements_filter_policy, 5744 0x7f, // tx power: no preference 5745 0x01, // primary adv phy: LE 1M 5746 0, // secondary adv max skip 5747 0, // secondary adv phy 5748 0, // adv sid 5749 0 // scan request notification 5750 ); 5751 } 5752 #endif 5753 { 5754 hci_send_cmd(&hci_le_set_advertising_parameters, 5755 hci_stack->le_advertisements_interval_min, 5756 hci_stack->le_advertisements_interval_max, 5757 hci_stack->le_advertisements_type, 5758 hci_stack->le_advertisements_own_addr_type, 5759 hci_stack->le_advertisements_direct_address_type, 5760 hci_stack->le_advertisements_direct_address, 5761 hci_stack->le_advertisements_channel_map, 5762 hci_stack->le_advertisements_filter_policy); 5763 } 5764 return true; 5765 } 5766 5767 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){ 5768 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 5769 uint8_t adv_data_clean[31]; 5770 memset(adv_data_clean, 0, sizeof(adv_data_clean)); 5771 (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data, 5772 hci_stack->le_advertisements_data_len); 5773 btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr); 5774 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5775 if (hci_extended_advertising_supported()){ 5776 hci_stack->le_advertising_set_in_current_command = 0; 5777 hci_send_cmd(&hci_le_set_extended_advertising_data, 0, 0x03, 0x01, hci_stack->le_advertisements_data_len, adv_data_clean); 5778 } else 5779 #endif 5780 { 5781 hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean); 5782 } 5783 return true; 5784 } 5785 5786 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){ 5787 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 5788 uint8_t scan_data_clean[31]; 5789 memset(scan_data_clean, 0, sizeof(scan_data_clean)); 5790 (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data, 5791 hci_stack->le_scan_response_data_len); 5792 btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr); 5793 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5794 if (hci_extended_advertising_supported()){ 5795 hci_stack->le_advertising_set_in_current_command = 0; 5796 hci_send_cmd(&hci_le_set_extended_scan_response_data, 0, 0x03, 0x01, hci_stack->le_scan_response_data_len, scan_data_clean); 5797 } else 5798 #endif 5799 { 5800 hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean); 5801 } 5802 return true; 5803 } 5804 5805 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5806 if (hci_extended_advertising_supported()) { 5807 btstack_linked_list_iterator_t it; 5808 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 5809 while (btstack_linked_list_iterator_has_next(&it)){ 5810 le_advertising_set_t * advertising_set = (le_advertising_set_t*) btstack_linked_list_iterator_next(&it); 5811 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_REMOVE_SET) != 0) { 5812 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_REMOVE_SET; 5813 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5814 hci_send_cmd(&hci_le_remove_advertising_set, advertising_set->advertising_handle); 5815 return true; 5816 } 5817 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADDRESS) != 0){ 5818 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 5819 hci_send_cmd(&hci_le_set_advertising_set_random_address, advertising_set->advertising_handle, advertising_set->random_address); 5820 return true; 5821 } 5822 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PARAMS) != 0){ 5823 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 5824 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5825 hci_send_cmd(&hci_le_set_extended_advertising_parameters, 5826 advertising_set->advertising_handle, 5827 advertising_set->extended_params.advertising_event_properties, 5828 advertising_set->extended_params.primary_advertising_interval_min, 5829 advertising_set->extended_params.primary_advertising_interval_max, 5830 advertising_set->extended_params.primary_advertising_channel_map, 5831 advertising_set->extended_params.own_address_type, 5832 advertising_set->extended_params.peer_address_type, 5833 advertising_set->extended_params.peer_address, 5834 advertising_set->extended_params.advertising_filter_policy, 5835 advertising_set->extended_params.advertising_tx_power, 5836 advertising_set->extended_params.primary_advertising_phy, 5837 advertising_set->extended_params.secondary_advertising_max_skip, 5838 advertising_set->extended_params.secondary_advertising_phy, 5839 advertising_set->extended_params.advertising_sid, 5840 advertising_set->extended_params.scan_request_notification_enable 5841 ); 5842 return true; 5843 } 5844 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA) != 0) { 5845 uint16_t pos = advertising_set->adv_data_pos; 5846 uint8_t operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->adv_data_len); 5847 uint16_t data_to_upload = btstack_min(advertising_set->adv_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN); 5848 if ((operation & 0x02) != 0){ 5849 // last fragment or complete data 5850 operation |= 2; 5851 advertising_set->adv_data_pos = 0; 5852 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 5853 } else { 5854 advertising_set->adv_data_pos += data_to_upload; 5855 } 5856 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5857 hci_send_cmd(&hci_le_set_extended_advertising_data, advertising_set->advertising_handle, operation, 0x01, data_to_upload, &advertising_set->adv_data[pos]); 5858 return true; 5859 } 5860 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA) != 0) { 5861 uint16_t pos = advertising_set->scan_data_pos; 5862 uint8_t operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->scan_data_len); 5863 uint16_t data_to_upload = btstack_min(advertising_set->scan_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN); 5864 if ((operation & 0x02) != 0){ 5865 advertising_set->scan_data_pos = 0; 5866 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 5867 } else { 5868 advertising_set->scan_data_pos += data_to_upload; 5869 } 5870 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5871 hci_send_cmd(&hci_le_set_extended_scan_response_data, operation, 0x03, 0x01, data_to_upload, &advertising_set->scan_data[pos]); 5872 return true; 5873 } 5874 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 5875 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS) != 0){ 5876 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS; 5877 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5878 hci_send_cmd(&hci_le_set_periodic_advertising_parameters, 5879 advertising_set->advertising_handle, 5880 advertising_set->periodic_params.periodic_advertising_interval_min, 5881 advertising_set->periodic_params.periodic_advertising_interval_max, 5882 advertising_set->periodic_params.periodic_advertising_properties); 5883 return true; 5884 } 5885 if ((advertising_set->tasks & LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA) != 0) { 5886 uint16_t pos = advertising_set->periodic_data_pos; 5887 uint8_t operation = hci_le_extended_advertising_operation_for_chunk(pos, advertising_set->periodic_data_len); 5888 uint16_t data_to_upload = btstack_min(advertising_set->periodic_data_len - pos, LE_EXTENDED_ADVERTISING_MAX_CHUNK_LEN); 5889 if ((operation & 0x02) != 0){ 5890 // last fragment or complete data 5891 operation |= 2; 5892 advertising_set->periodic_data_pos = 0; 5893 advertising_set->tasks &= ~LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA; 5894 } else { 5895 advertising_set->periodic_data_pos += data_to_upload; 5896 } 5897 hci_stack->le_advertising_set_in_current_command = advertising_set->advertising_handle; 5898 hci_send_cmd(&hci_le_set_periodic_advertising_data, advertising_set->advertising_handle, operation, data_to_upload, &advertising_set->periodic_data[pos]); 5899 return true; 5900 } 5901 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 5902 } 5903 } 5904 #endif 5905 5906 #endif 5907 5908 #ifdef ENABLE_LE_CENTRAL 5909 // if connect with whitelist was active and is not cancelled yet, wait until next time 5910 if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false; 5911 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 5912 // if periodic sync with advertiser list was active and is not cancelled yet, wait until next time 5913 if (hci_stack->le_periodic_sync_state == LE_CONNECTING_CANCEL) return false; 5914 #endif 5915 #endif 5916 5917 // LE Whitelist Management 5918 if (whitelist_modification_pending){ 5919 // add/remove entries 5920 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 5921 while (btstack_linked_list_iterator_has_next(&lit)){ 5922 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 5923 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){ 5924 entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER; 5925 hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address); 5926 return true; 5927 } 5928 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){ 5929 entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER; 5930 entry->state |= LE_WHITELIST_ON_CONTROLLER; 5931 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address); 5932 return true; 5933 } 5934 if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){ 5935 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 5936 btstack_memory_whitelist_entry_free(entry); 5937 } 5938 } 5939 } 5940 5941 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 5942 // LE Resolving List Management 5943 if (resolving_list_supported) { 5944 uint16_t i; 5945 switch (hci_stack->le_resolving_list_state) { 5946 case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION: 5947 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE; 5948 hci_send_cmd(&hci_le_set_address_resolution_enabled, 1); 5949 return true; 5950 case LE_RESOLVING_LIST_READ_SIZE: 5951 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR; 5952 hci_send_cmd(&hci_le_read_resolving_list_size); 5953 return true; 5954 case LE_RESOLVING_LIST_SEND_CLEAR: 5955 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 5956 (void) memset(hci_stack->le_resolving_list_add_entries, 0xff, 5957 sizeof(hci_stack->le_resolving_list_add_entries)); 5958 (void) memset(hci_stack->le_resolving_list_remove_entries, 0, 5959 sizeof(hci_stack->le_resolving_list_remove_entries)); 5960 hci_send_cmd(&hci_le_clear_resolving_list); 5961 return true; 5962 case LE_RESOLVING_LIST_REMOVE_ENTRIES: 5963 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) { 5964 uint8_t offset = i >> 3; 5965 uint8_t mask = 1 << (i & 7); 5966 if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue; 5967 hci_stack->le_resolving_list_remove_entries[offset] &= ~mask; 5968 bd_addr_t peer_identity_addreses; 5969 int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN; 5970 sm_key_t peer_irk; 5971 le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk); 5972 if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue; 5973 5974 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE 5975 // trigger whitelist entry 'update' (work around for controller bug) 5976 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 5977 while (btstack_linked_list_iterator_has_next(&lit)) { 5978 whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit); 5979 if (entry->address_type != peer_identity_addr_type) continue; 5980 if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue; 5981 log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses)); 5982 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER; 5983 } 5984 #endif 5985 5986 hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type, 5987 peer_identity_addreses); 5988 return true; 5989 } 5990 5991 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES; 5992 5993 /* fall through */ 5994 5995 case LE_RESOLVING_LIST_ADD_ENTRIES: 5996 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) { 5997 uint8_t offset = i >> 3; 5998 uint8_t mask = 1 << (i & 7); 5999 if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue; 6000 hci_stack->le_resolving_list_add_entries[offset] &= ~mask; 6001 bd_addr_t peer_identity_addreses; 6002 int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN; 6003 sm_key_t peer_irk; 6004 le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk); 6005 if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue; 6006 if (btstack_is_null(peer_irk, 16)) continue; 6007 const uint8_t *local_irk = gap_get_persistent_irk(); 6008 // command uses format specifier 'P' that stores 16-byte value without flip 6009 uint8_t local_irk_flipped[16]; 6010 uint8_t peer_irk_flipped[16]; 6011 reverse_128(local_irk, local_irk_flipped); 6012 reverse_128(peer_irk, peer_irk_flipped); 6013 hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses, 6014 peer_irk_flipped, local_irk_flipped); 6015 return true; 6016 } 6017 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE; 6018 break; 6019 6020 default: 6021 break; 6022 } 6023 } 6024 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE; 6025 #endif 6026 6027 #ifdef ENABLE_LE_CENTRAL 6028 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6029 // LE Whitelist Management 6030 if (periodic_list_modification_pending){ 6031 // add/remove entries 6032 btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list); 6033 while (btstack_linked_list_iterator_has_next(&lit)){ 6034 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit); 6035 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER){ 6036 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER; 6037 hci_send_cmd(&hci_le_remove_device_from_periodic_advertiser_list, entry->address_type, entry->address); 6038 return true; 6039 } 6040 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER){ 6041 entry->state &= ~LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER; 6042 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER; 6043 hci_send_cmd(&hci_le_add_device_to_periodic_advertiser_list, entry->address_type, entry->address, entry->sid); 6044 return true; 6045 } 6046 if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER) == 0){ 6047 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry); 6048 btstack_memory_periodic_advertiser_list_entry_free(entry); 6049 } 6050 } 6051 } 6052 #endif 6053 #endif 6054 6055 // post-pone all actions until stack is fully working 6056 if (hci_stack->state != HCI_STATE_WORKING) return false; 6057 6058 // advertisements, active scanning, and creating connections requires random address to be set if using private address 6059 if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false; 6060 6061 // Phase 4: restore state 6062 6063 #ifdef ENABLE_LE_CENTRAL 6064 // re-start scanning 6065 if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){ 6066 hci_stack->le_scanning_active = true; 6067 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6068 if (hci_extended_advertising_supported()){ 6069 hci_send_cmd(&hci_le_set_extended_scan_enable, 1, 0, 0, 0); 6070 } else 6071 #endif 6072 { 6073 hci_send_cmd(&hci_le_set_scan_enable, 1, 0); 6074 } 6075 return true; 6076 } 6077 #endif 6078 6079 #ifdef ENABLE_LE_CENTRAL 6080 // re-start connecting 6081 if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){ 6082 bd_addr_t null_addr; 6083 memset(null_addr, 0, 6); 6084 hci_stack->le_connection_own_addr_type = hci_stack->le_own_addr_type; 6085 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address); 6086 hci_send_cmd(&hci_le_create_connection, 6087 hci_stack->le_connection_scan_interval, // scan interval: 60 ms 6088 hci_stack->le_connection_scan_window, // scan interval: 30 ms 6089 1, // use whitelist 6090 0, // peer address type 6091 null_addr, // peer bd addr 6092 hci_stack->le_connection_own_addr_type, // our addr type: 6093 hci_stack->le_connection_interval_min, // conn interval min 6094 hci_stack->le_connection_interval_max, // conn interval max 6095 hci_stack->le_connection_latency, // conn latency 6096 hci_stack->le_supervision_timeout, // conn latency 6097 hci_stack->le_minimum_ce_length, // min ce length 6098 hci_stack->le_maximum_ce_length // max ce length 6099 ); 6100 return true; 6101 } 6102 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6103 if (hci_stack->le_periodic_sync_state == LE_CONNECTING_IDLE){ 6104 switch(hci_stack->le_periodic_sync_request){ 6105 case LE_CONNECTING_DIRECT: 6106 case LE_CONNECTING_WHITELIST: 6107 hci_stack->le_periodic_sync_state = ((hci_stack->le_periodic_sync_options & 1) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT; 6108 hci_send_cmd(&hci_le_periodic_advertising_create_sync, 6109 hci_stack->le_periodic_sync_options, 6110 hci_stack->le_periodic_sync_advertising_sid, 6111 hci_stack->le_periodic_sync_advertiser_address_type, 6112 hci_stack->le_periodic_sync_advertiser_address, 6113 hci_stack->le_periodic_sync_skip, 6114 hci_stack->le_periodic_sync_timeout, 6115 hci_stack->le_periodic_sync_cte_type); 6116 return true; 6117 default: 6118 break; 6119 } 6120 } 6121 #endif 6122 #endif 6123 6124 #ifdef ENABLE_LE_PERIPHERAL 6125 // re-start advertising 6126 if (hci_stack->le_advertisements_enabled_for_current_roles && ((hci_stack->le_advertisements_state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){ 6127 // check if advertisements should be enabled given 6128 hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ACTIVE; 6129 hci_get_own_address_for_addr_type(hci_stack->le_advertisements_own_addr_type, hci_stack->le_advertisements_own_address); 6130 6131 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6132 if (hci_extended_advertising_supported()){ 6133 const uint8_t advertising_handles[] = { 0 }; 6134 const uint16_t durations[] = { 0 }; 6135 const uint16_t max_events[] = { 0 }; 6136 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events); 6137 } else 6138 #endif 6139 { 6140 hci_send_cmd(&hci_le_set_advertise_enable, 1); 6141 } 6142 return true; 6143 } 6144 6145 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6146 if (hci_extended_advertising_supported()) { 6147 btstack_linked_list_iterator_t it; 6148 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 6149 while (btstack_linked_list_iterator_has_next(&it)) { 6150 le_advertising_set_t *advertising_set = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it); 6151 if (((advertising_set->state & LE_ADVERTISEMENT_STATE_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_ACTIVE) == 0)){ 6152 advertising_set->state |= LE_ADVERTISEMENT_STATE_ACTIVE; 6153 const uint8_t advertising_handles[] = { advertising_set->advertising_handle }; 6154 const uint16_t durations[] = { advertising_set->enable_timeout }; 6155 const uint16_t max_events[] = { advertising_set->enable_max_scan_events }; 6156 hci_send_cmd(&hci_le_set_extended_advertising_enable, 1, 1, advertising_handles, durations, max_events); 6157 return true; 6158 } 6159 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 6160 if (((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED) != 0) && ((advertising_set->state & LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE) == 0)){ 6161 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ACTIVE; 6162 uint8_t enable = 1; 6163 if (advertising_set->periodic_include_adi){ 6164 enable |= 2; 6165 } 6166 hci_send_cmd(&hci_le_set_periodic_advertising_enable, enable, advertising_set->advertising_handle); 6167 return true; 6168 } 6169 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 6170 } 6171 } 6172 #endif 6173 #endif 6174 6175 return false; 6176 } 6177 6178 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6179 static bool hci_run_iso_tasks(void){ 6180 btstack_linked_list_iterator_t it; 6181 6182 // BIG 6183 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 6184 while (btstack_linked_list_iterator_has_next(&it)){ 6185 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 6186 switch (big->state){ 6187 case LE_AUDIO_BIG_STATE_CREATE: 6188 big->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED; 6189 hci_send_cmd(&hci_le_create_big, 6190 big->params->big_handle, 6191 big->params->advertising_handle, 6192 big->params->num_bis, 6193 big->params->sdu_interval_us, 6194 big->params->max_sdu, 6195 big->params->max_transport_latency_ms, 6196 big->params->rtn, 6197 big->params->phy, 6198 big->params->packing, 6199 big->params->framing, 6200 big->params->encryption, 6201 big->params->broadcast_code); 6202 return true; 6203 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 6204 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH; 6205 hci_send_cmd(&hci_le_setup_iso_data_path, big->bis_con_handles[big->state_vars.next_bis], 0, 0, 0, 0, 0, 0, 0, NULL); 6206 return true; 6207 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED: 6208 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED; 6209 hci_send_cmd(&hci_le_terminate_big, big->big_handle, big->state_vars.status); 6210 return true; 6211 case LE_AUDIO_BIG_STATE_TERMINATE: 6212 big->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 6213 hci_send_cmd(&hci_le_terminate_big, big->big_handle, ERROR_CODE_SUCCESS); 6214 return true; 6215 default: 6216 break; 6217 } 6218 } 6219 6220 // BIG Sync 6221 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 6222 while (btstack_linked_list_iterator_has_next(&it)){ 6223 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 6224 switch (big_sync->state){ 6225 case LE_AUDIO_BIG_STATE_CREATE: 6226 big_sync->state = LE_AUDIO_BIG_STATE_W4_ESTABLISHED; 6227 hci_send_cmd(&hci_le_big_create_sync, 6228 big_sync->params->big_handle, 6229 big_sync->params->sync_handle, 6230 big_sync->params->encryption, 6231 big_sync->params->broadcast_code, 6232 big_sync->params->mse, 6233 big_sync->params->big_sync_timeout_10ms, 6234 big_sync->params->num_bis, 6235 big_sync->params->bis_indices); 6236 return true; 6237 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 6238 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH; 6239 hci_send_cmd(&hci_le_setup_iso_data_path, big_sync->bis_con_handles[big_sync->state_vars.next_bis], 1, 0, 0, 0, 0, 0, 0, NULL); 6240 return true; 6241 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATHS_FAILED: 6242 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED_AFTER_SETUP_FAILED; 6243 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle); 6244 return true; 6245 case LE_AUDIO_BIG_STATE_TERMINATE: 6246 big_sync->state = LE_AUDIO_BIG_STATE_W4_TERMINATED; 6247 hci_send_cmd(&hci_le_big_terminate_sync, big_sync->big_handle); 6248 return true; 6249 default: 6250 break; 6251 } 6252 } 6253 6254 return false; 6255 } 6256 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 6257 #endif 6258 6259 static bool hci_run_general_pending_commands(void){ 6260 btstack_linked_item_t * it; 6261 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 6262 hci_connection_t * connection = (hci_connection_t *) it; 6263 6264 switch(connection->state){ 6265 case SEND_CREATE_CONNECTION: 6266 switch(connection->address_type){ 6267 #ifdef ENABLE_CLASSIC 6268 case BD_ADDR_TYPE_ACL: 6269 log_info("sending hci_create_connection"); 6270 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch); 6271 break; 6272 #endif 6273 default: 6274 #ifdef ENABLE_BLE 6275 #ifdef ENABLE_LE_CENTRAL 6276 log_info("sending hci_le_create_connection"); 6277 hci_stack->le_connection_own_addr_type = hci_stack->le_own_addr_type; 6278 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address); 6279 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 6280 if (hci_extended_advertising_supported()) { 6281 uint16_t le_connection_scan_interval[1] = { hci_stack->le_connection_scan_interval }; 6282 uint16_t le_connection_scan_window[1] = { hci_stack->le_connection_scan_window }; 6283 uint16_t le_connection_interval_min[1] = { hci_stack->le_connection_interval_min }; 6284 uint16_t le_connection_interval_max[1] = { hci_stack->le_connection_interval_max }; 6285 uint16_t le_connection_latency[1] = { hci_stack->le_connection_latency }; 6286 uint16_t le_supervision_timeout[1] = { hci_stack->le_supervision_timeout }; 6287 uint16_t le_minimum_ce_length[1] = { hci_stack->le_minimum_ce_length }; 6288 uint16_t le_maximum_ce_length[1] = { hci_stack->le_maximum_ce_length }; 6289 hci_send_cmd(&hci_le_extended_create_connection, 6290 0, // don't use whitelist 6291 hci_stack->le_connection_own_addr_type, // our addr type: 6292 connection->address_type, // peer address type 6293 connection->address, // peer bd addr 6294 1, // initiating PHY - 1M 6295 le_connection_scan_interval, // conn scan interval 6296 le_connection_scan_window, // conn scan windows 6297 le_connection_interval_min, // conn interval min 6298 le_connection_interval_max, // conn interval max 6299 le_connection_latency, // conn latency 6300 le_supervision_timeout, // conn latency 6301 le_minimum_ce_length, // min ce length 6302 le_maximum_ce_length // max ce length 6303 ); } 6304 else 6305 #endif 6306 { 6307 hci_send_cmd(&hci_le_create_connection, 6308 hci_stack->le_connection_scan_interval, // conn scan interval 6309 hci_stack->le_connection_scan_window, // conn scan windows 6310 0, // don't use whitelist 6311 connection->address_type, // peer address type 6312 connection->address, // peer bd addr 6313 hci_stack->le_connection_own_addr_type, // our addr type: 6314 hci_stack->le_connection_interval_min, // conn interval min 6315 hci_stack->le_connection_interval_max, // conn interval max 6316 hci_stack->le_connection_latency, // conn latency 6317 hci_stack->le_supervision_timeout, // conn latency 6318 hci_stack->le_minimum_ce_length, // min ce length 6319 hci_stack->le_maximum_ce_length // max ce length 6320 ); 6321 } 6322 connection->state = SENT_CREATE_CONNECTION; 6323 #endif 6324 #endif 6325 break; 6326 } 6327 return true; 6328 6329 #ifdef ENABLE_CLASSIC 6330 case RECEIVED_CONNECTION_REQUEST: 6331 connection->role = HCI_ROLE_SLAVE; 6332 if (connection->address_type == BD_ADDR_TYPE_ACL){ 6333 log_info("sending hci_accept_connection_request"); 6334 connection->state = ACCEPTED_CONNECTION_REQUEST; 6335 hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy); 6336 return true; 6337 } 6338 break; 6339 #endif 6340 case SEND_DISCONNECT: 6341 connection->state = SENT_DISCONNECT; 6342 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 6343 return true; 6344 6345 default: 6346 break; 6347 } 6348 6349 // no further commands if connection is about to get shut down 6350 if (connection->state == SENT_DISCONNECT) continue; 6351 6352 #ifdef ENABLE_CLASSIC 6353 6354 // Handling link key request requires remote supported features 6355 if (((connection->authentication_flags & AUTH_FLAG_HANDLE_LINK_KEY_REQUEST) != 0)){ 6356 log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL); 6357 connectionClearAuthenticationFlags(connection, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST); 6358 6359 bool have_link_key = connection->link_key_type != INVALID_LINK_KEY; 6360 bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level); 6361 if (have_link_key && security_level_sufficient){ 6362 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key); 6363 } else { 6364 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 6365 } 6366 return true; 6367 } 6368 6369 if (connection->authentication_flags & AUTH_FLAG_DENY_PIN_CODE_REQUEST){ 6370 log_info("denying to pin request"); 6371 connectionClearAuthenticationFlags(connection, AUTH_FLAG_DENY_PIN_CODE_REQUEST); 6372 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 6373 return true; 6374 } 6375 6376 // security assessment requires remote features 6377 if ((connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST) != 0){ 6378 connectionClearAuthenticationFlags(connection, AUTH_FLAG_RECV_IO_CAPABILITIES_REQUEST); 6379 hci_ssp_assess_security_on_io_cap_request(connection); 6380 // no return here as hci_ssp_assess_security_on_io_cap_request only sets AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY or AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY 6381 } 6382 6383 if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY){ 6384 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY); 6385 // set authentication requirements: 6386 // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic) 6387 // - BONDING MODE: dedicated if requested, bondable otherwise. Drop bondable if not set for remote 6388 uint8_t authreq = hci_stack->ssp_authentication_requirement & 1; 6389 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 6390 authreq |= 1; 6391 } 6392 bool bonding = hci_stack->bondable; 6393 if (connection->authentication_flags & AUTH_FLAG_RECV_IO_CAPABILITIES_RESPONSE){ 6394 // if we have received IO Cap Response, we're in responder role 6395 bool remote_bonding = connection->io_cap_response_auth_req >= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 6396 if (bonding && !remote_bonding){ 6397 log_info("Remote not bonding, dropping local flag"); 6398 bonding = false; 6399 } 6400 } 6401 if (bonding){ 6402 if (connection->bonding_flags & BONDING_DEDICATED){ 6403 authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 6404 } else { 6405 authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 6406 } 6407 } 6408 uint8_t have_oob_data = 0; 6409 #ifdef ENABLE_CLASSIC_PAIRING_OOB 6410 if (connection->classic_oob_c_192 != NULL){ 6411 have_oob_data |= 1; 6412 } 6413 if (connection->classic_oob_c_256 != NULL){ 6414 have_oob_data |= 2; 6415 } 6416 #endif 6417 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq); 6418 return true; 6419 } 6420 6421 if (connection->authentication_flags & AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY) { 6422 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 6423 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 6424 return true; 6425 } 6426 6427 #ifdef ENABLE_CLASSIC_PAIRING_OOB 6428 if (connection->authentication_flags & AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY){ 6429 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_REMOTE_OOB_DATA_REPLY); 6430 const uint8_t zero[16] = { 0 }; 6431 const uint8_t * r_192 = zero; 6432 const uint8_t * c_192 = zero; 6433 const uint8_t * r_256 = zero; 6434 const uint8_t * c_256 = zero; 6435 // verify P-256 OOB 6436 if ((connection->classic_oob_c_256 != NULL) && hci_command_supported(SUPPORTED_HCI_COMMAND_REMOTE_OOB_EXTENDED_DATA_REQUEST_REPLY)) { 6437 c_256 = connection->classic_oob_c_256; 6438 if (connection->classic_oob_r_256 != NULL) { 6439 r_256 = connection->classic_oob_r_256; 6440 } 6441 } 6442 // verify P-192 OOB 6443 if ((connection->classic_oob_c_192 != NULL)) { 6444 c_192 = connection->classic_oob_c_192; 6445 if (connection->classic_oob_r_192 != NULL) { 6446 r_192 = connection->classic_oob_r_192; 6447 } 6448 } 6449 6450 // assess security 6451 bool need_level_4 = hci_stack->gap_secure_connections_only_mode || (connection->requested_security_level == LEVEL_4); 6452 bool can_reach_level_4 = hci_remote_sc_enabled(connection) && (c_256 != NULL); 6453 if (need_level_4 && !can_reach_level_4){ 6454 log_info("Level 4 required, but not possible -> abort"); 6455 hci_pairing_complete(connection, ERROR_CODE_INSUFFICIENT_SECURITY); 6456 // send oob negative reply 6457 c_256 = NULL; 6458 c_192 = NULL; 6459 } 6460 6461 // Reply 6462 if (c_256 != zero) { 6463 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256); 6464 } else if (c_192 != zero){ 6465 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192); 6466 } else { 6467 hci_stack->classic_oob_con_handle = connection->con_handle; 6468 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address); 6469 } 6470 return true; 6471 } 6472 #endif 6473 6474 if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_REPLY){ 6475 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_REPLY); 6476 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 6477 return true; 6478 } 6479 6480 if (connection->authentication_flags & AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY){ 6481 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_CONFIRM_NEGATIVE_REPLY); 6482 hci_send_cmd(&hci_user_confirmation_request_negative_reply, &connection->address); 6483 return true; 6484 } 6485 6486 if (connection->authentication_flags & AUTH_FLAG_SEND_USER_PASSKEY_REPLY){ 6487 connectionClearAuthenticationFlags(connection, AUTH_FLAG_SEND_USER_PASSKEY_REPLY); 6488 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 6489 return true; 6490 } 6491 6492 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 6493 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 6494 connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT; 6495 connection->state = SENT_DISCONNECT; 6496 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 6497 return true; 6498 } 6499 6500 if ((connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){ 6501 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 6502 connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST; 6503 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 6504 return true; 6505 } 6506 6507 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 6508 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 6509 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 6510 return true; 6511 } 6512 6513 if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){ 6514 connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 6515 hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1); 6516 return true; 6517 } 6518 6519 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){ 6520 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0; 6521 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 6522 return true; 6523 } 6524 6525 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){ 6526 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1; 6527 hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1); 6528 return true; 6529 } 6530 6531 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){ 6532 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2; 6533 hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2); 6534 return true; 6535 } 6536 #endif 6537 6538 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 6539 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 6540 #ifdef ENABLE_CLASSIC 6541 hci_pairing_complete(connection, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_SECURITY_REASONS); 6542 #endif 6543 if (connection->state != SENT_DISCONNECT){ 6544 connection->state = SENT_DISCONNECT; 6545 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE); 6546 return true; 6547 } 6548 } 6549 6550 #ifdef ENABLE_CLASSIC 6551 uint16_t sniff_min_interval; 6552 switch (connection->sniff_min_interval){ 6553 case 0: 6554 break; 6555 case 0xffff: 6556 connection->sniff_min_interval = 0; 6557 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle); 6558 return true; 6559 default: 6560 sniff_min_interval = connection->sniff_min_interval; 6561 connection->sniff_min_interval = 0; 6562 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout); 6563 return true; 6564 } 6565 6566 if (connection->sniff_subrating_max_latency != 0xffff){ 6567 uint16_t max_latency = connection->sniff_subrating_max_latency; 6568 connection->sniff_subrating_max_latency = 0; 6569 hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout); 6570 return true; 6571 } 6572 6573 if (connection->qos_service_type != HCI_SERVICE_TYPE_INVALID){ 6574 uint8_t service_type = (uint8_t) connection->qos_service_type; 6575 connection->qos_service_type = HCI_SERVICE_TYPE_INVALID; 6576 hci_send_cmd(&hci_qos_setup, connection->con_handle, 0, service_type, connection->qos_token_rate, connection->qos_peak_bandwidth, connection->qos_latency, connection->qos_delay_variation); 6577 return true; 6578 } 6579 6580 if (connection->request_role != HCI_ROLE_INVALID){ 6581 hci_role_t role = connection->request_role; 6582 connection->request_role = HCI_ROLE_INVALID; 6583 hci_send_cmd(&hci_switch_role_command, connection->address, role); 6584 return true; 6585 } 6586 #endif 6587 6588 if (connection->gap_connection_tasks != 0){ 6589 #ifdef ENABLE_CLASSIC 6590 if ((connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT) != 0){ 6591 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_AUTOMATIC_FLUSH_TIMEOUT; 6592 hci_send_cmd(&hci_write_automatic_flush_timeout, connection->con_handle, hci_stack->automatic_flush_timeout); 6593 return true; 6594 } 6595 if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT){ 6596 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_WRITE_SUPERVISION_TIMEOUT; 6597 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout); 6598 return true; 6599 } 6600 #endif 6601 if (connection->gap_connection_tasks & GAP_CONNECTION_TASK_READ_RSSI){ 6602 connection->gap_connection_tasks &= ~GAP_CONNECTION_TASK_READ_RSSI; 6603 hci_send_cmd(&hci_read_rssi, connection->con_handle); 6604 return true; 6605 } 6606 } 6607 6608 #ifdef ENABLE_BLE 6609 switch (connection->le_con_parameter_update_state){ 6610 // response to L2CAP CON PARAMETER UPDATE REQUEST 6611 case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS: 6612 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 6613 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min, 6614 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 6615 0x0000, 0xffff); 6616 return true; 6617 case CON_PARAMETER_UPDATE_REPLY: 6618 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 6619 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min, 6620 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 6621 0x0000, 0xffff); 6622 return true; 6623 case CON_PARAMETER_UPDATE_NEGATIVE_REPLY: 6624 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 6625 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, connection->con_handle, 6626 ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS); 6627 return true; 6628 default: 6629 break; 6630 } 6631 if (connection->le_phy_update_all_phys != 0xffu){ 6632 uint8_t all_phys = connection->le_phy_update_all_phys; 6633 connection->le_phy_update_all_phys = 0xff; 6634 hci_send_cmd(&hci_le_set_phy, connection->con_handle, all_phys, connection->le_phy_update_tx_phys, connection->le_phy_update_rx_phys, connection->le_phy_update_phy_options); 6635 return true; 6636 } 6637 #endif 6638 } 6639 return false; 6640 } 6641 6642 static void hci_run(void){ 6643 6644 // stack state sub statemachines 6645 switch (hci_stack->state) { 6646 case HCI_STATE_INITIALIZING: 6647 hci_initializing_run(); 6648 break; 6649 case HCI_STATE_HALTING: 6650 hci_halting_run(); 6651 break; 6652 case HCI_STATE_FALLING_ASLEEP: 6653 hci_falling_asleep_run(); 6654 break; 6655 default: 6656 break; 6657 } 6658 6659 // allow to run after initialization to working transition 6660 if (hci_stack->state != HCI_STATE_WORKING){ 6661 return; 6662 } 6663 6664 bool done; 6665 6666 // send continuation fragments first, as they block the prepared packet buffer 6667 done = hci_run_acl_fragments(); 6668 if (done) return; 6669 6670 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6671 done = hci_run_iso_fragments(); 6672 if (done) return; 6673 #endif 6674 6675 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 6676 // send host num completed packets next as they don't require num_cmd_packets > 0 6677 if (!hci_can_send_comand_packet_transport()) return; 6678 if (hci_stack->host_completed_packets){ 6679 hci_host_num_completed_packets(); 6680 return; 6681 } 6682 #endif 6683 6684 if (!hci_can_send_command_packet_now()) return; 6685 6686 // global/non-connection oriented commands 6687 6688 6689 #ifdef ENABLE_CLASSIC 6690 // general gap classic 6691 done = hci_run_general_gap_classic(); 6692 if (done) return; 6693 #endif 6694 6695 #ifdef ENABLE_BLE 6696 // general gap le 6697 done = hci_run_general_gap_le(); 6698 if (done) return; 6699 6700 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6701 // ISO related tasks, e.g. BIG create/terminate/sync 6702 done = hci_run_iso_tasks(); 6703 if (done) return; 6704 #endif 6705 #endif 6706 6707 // send pending HCI commands 6708 hci_run_general_pending_commands(); 6709 } 6710 6711 uint8_t hci_send_cmd_packet(uint8_t *packet, int size){ 6712 // house-keeping 6713 6714 #ifdef ENABLE_CLASSIC 6715 bd_addr_t addr; 6716 hci_connection_t * conn; 6717 #endif 6718 #ifdef ENABLE_LE_CENTRAL 6719 uint8_t initiator_filter_policy; 6720 #endif 6721 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6722 uint8_t i; 6723 uint8_t num_cis; 6724 hci_con_handle_t cis_handle; 6725 uint8_t status; 6726 #endif 6727 6728 uint16_t opcode = little_endian_read_16(packet, 0); 6729 switch (opcode) { 6730 case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE: 6731 hci_stack->loopback_mode = packet[3]; 6732 break; 6733 6734 #ifdef ENABLE_CLASSIC 6735 case HCI_OPCODE_HCI_CREATE_CONNECTION: 6736 reverse_bd_addr(&packet[3], addr); 6737 log_info("Create_connection to %s", bd_addr_to_str(addr)); 6738 6739 // CVE-2020-26555: reject outgoing connection to device with same BD ADDR 6740 if (memcmp(hci_stack->local_bd_addr, addr, 6) == 0) { 6741 hci_emit_connection_complete(addr, 0, ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR); 6742 return ERROR_CODE_CONNECTION_REJECTED_DUE_TO_UNACCEPTABLE_BD_ADDR; 6743 } 6744 6745 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 6746 if (!conn) { 6747 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 6748 if (!conn) { 6749 // notify client that alloc failed 6750 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 6751 return BTSTACK_MEMORY_ALLOC_FAILED; // packet not sent to controller 6752 } 6753 conn->state = SEND_CREATE_CONNECTION; 6754 conn->role = HCI_ROLE_MASTER; 6755 } 6756 6757 log_info("conn state %u", conn->state); 6758 // TODO: L2CAP should not send create connection command, instead a (new) gap function should be used 6759 switch (conn->state) { 6760 // if connection active exists 6761 case OPEN: 6762 // and OPEN, emit connection complete command 6763 hci_emit_connection_complete(addr, conn->con_handle, ERROR_CODE_SUCCESS); 6764 // packet not sent to controller 6765 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 6766 case RECEIVED_DISCONNECTION_COMPLETE: 6767 // create connection triggered in disconnect complete event, let's do it now 6768 break; 6769 case SEND_CREATE_CONNECTION: 6770 #ifdef ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS 6771 if (hci_classic_operation_active()){ 6772 return ERROR_CODE_SUCCESS; 6773 } 6774 #endif 6775 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now 6776 break; 6777 default: 6778 // otherwise, just ignore as it is already in the open process 6779 // packet not sent to controller 6780 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 6781 } 6782 conn->state = SENT_CREATE_CONNECTION; 6783 6784 // track outgoing connection 6785 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL; 6786 (void) memcpy(hci_stack->outgoing_addr, addr, 6); 6787 break; 6788 6789 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT) 6790 case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION: 6791 // setup_synchronous_connection? Voice setting at offset 22 6792 // TODO: compare to current setting if sco connection already active 6793 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15); 6794 break; 6795 case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION: 6796 // accept_synchronous_connection? Voice setting at offset 18 6797 // TODO: compare to current setting if sco connection already active 6798 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19); 6799 // track outgoing connection 6800 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_SCO; 6801 reverse_bd_addr(&packet[3], hci_stack->outgoing_addr); 6802 break; 6803 #endif 6804 #endif 6805 6806 #ifdef ENABLE_BLE 6807 #ifdef ENABLE_LE_CENTRAL 6808 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION: 6809 // white list used? 6810 initiator_filter_policy = packet[7]; 6811 switch (initiator_filter_policy) { 6812 case 0: 6813 // whitelist not used 6814 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT; 6815 break; 6816 case 1: 6817 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST; 6818 break; 6819 default: 6820 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy); 6821 break; 6822 } 6823 // track outgoing connection 6824 hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type 6825 reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address 6826 break; 6827 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL: 6828 hci_stack->le_connecting_state = LE_CONNECTING_CANCEL; 6829 break; 6830 #endif 6831 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 6832 #ifdef ENABLE_LE_CENTRAL 6833 case HCI_OPCODE_HCI_LE_CREATE_CIS: 6834 status = ERROR_CODE_SUCCESS; 6835 num_cis = packet[3]; 6836 // setup hci_iso_streams 6837 for (i=0;i<num_cis;i++){ 6838 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 4 + (4 * i)); 6839 status = hci_iso_stream_create(cis_handle, 0xff); 6840 if (status != ERROR_CODE_SUCCESS) { 6841 break; 6842 } 6843 } 6844 // free structs on error 6845 if (status != ERROR_CODE_SUCCESS){ 6846 hci_iso_stream_requested_finalize(0xff); 6847 return status; 6848 } 6849 break; 6850 #endif /* ENABLE_LE_CENTRAL */ 6851 #ifdef ENABLE_LE_PERIPHERAL 6852 case HCI_OPCODE_HCI_LE_ACCEPT_CIS_REQUEST: 6853 cis_handle = (hci_con_handle_t) little_endian_read_16(packet, 3); 6854 status = hci_iso_stream_create(cis_handle, 0xff); 6855 if (status != ERROR_CODE_SUCCESS){ 6856 return status; 6857 } 6858 break; 6859 #endif /* ENABLE_LE_PERIPHERAL */ 6860 #endif /* ENABLE_LE_ISOCHRONOUS_STREAMS */ 6861 #endif /* ENABLE_BLE */ 6862 default: 6863 break; 6864 } 6865 6866 hci_stack->num_cmd_packets--; 6867 6868 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 6869 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 6870 if (err != 0){ 6871 return ERROR_CODE_HARDWARE_FAILURE; 6872 } 6873 return ERROR_CODE_SUCCESS; 6874 } 6875 6876 // disconnect because of security block 6877 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 6878 hci_connection_t * connection = hci_connection_for_handle(con_handle); 6879 if (!connection) return; 6880 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 6881 } 6882 6883 6884 // Configure Secure Simple Pairing 6885 6886 #ifdef ENABLE_CLASSIC 6887 6888 // enable will enable SSP during init 6889 void gap_ssp_set_enable(int enable){ 6890 hci_stack->ssp_enable = enable; 6891 } 6892 6893 static int hci_local_ssp_activated(void){ 6894 return gap_ssp_supported() && hci_stack->ssp_enable; 6895 } 6896 6897 // if set, BTstack will respond to io capability request using authentication requirement 6898 void gap_ssp_set_io_capability(int io_capability){ 6899 hci_stack->ssp_io_capability = io_capability; 6900 } 6901 void gap_ssp_set_authentication_requirement(int authentication_requirement){ 6902 hci_stack->ssp_authentication_requirement = authentication_requirement; 6903 } 6904 6905 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 6906 void gap_ssp_set_auto_accept(int auto_accept){ 6907 hci_stack->ssp_auto_accept = auto_accept; 6908 } 6909 6910 void gap_secure_connections_enable(bool enable){ 6911 hci_stack->secure_connections_enable = enable; 6912 } 6913 bool gap_secure_connections_active(void){ 6914 return hci_stack->secure_connections_active; 6915 } 6916 6917 #endif 6918 6919 // va_list part of hci_send_cmd 6920 uint8_t hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){ 6921 if (!hci_can_send_command_packet_now()){ 6922 log_error("hci_send_cmd called but cannot send packet now"); 6923 return ERROR_CODE_COMMAND_DISALLOWED; 6924 } 6925 6926 // for HCI INITIALIZATION 6927 // log_info("hci_send_cmd: opcode %04x", cmd->opcode); 6928 hci_stack->last_cmd_opcode = cmd->opcode; 6929 6930 hci_reserve_packet_buffer(); 6931 uint8_t * packet = hci_stack->hci_packet_buffer; 6932 uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr); 6933 uint8_t status = hci_send_cmd_packet(packet, size); 6934 6935 // release packet buffer on error or for synchronous transport implementations 6936 if ((status != ERROR_CODE_SUCCESS) || hci_transport_synchronous()){ 6937 hci_release_packet_buffer(); 6938 hci_emit_transport_packet_sent(); 6939 } 6940 6941 return status; 6942 } 6943 6944 /** 6945 * pre: numcmds >= 0 - it's allowed to send a command to the controller 6946 */ 6947 uint8_t hci_send_cmd(const hci_cmd_t * cmd, ...){ 6948 va_list argptr; 6949 va_start(argptr, cmd); 6950 uint8_t status = hci_send_cmd_va_arg(cmd, argptr); 6951 va_end(argptr); 6952 return status; 6953 } 6954 6955 // Create various non-HCI events. 6956 // TODO: generalize, use table similar to hci_create_command 6957 6958 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){ 6959 // dump packet 6960 if (dump) { 6961 hci_dump_packet( HCI_EVENT_PACKET, 1, event, size); 6962 } 6963 6964 // dispatch to all event handlers 6965 btstack_linked_list_iterator_t it; 6966 btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers); 6967 while (btstack_linked_list_iterator_has_next(&it)){ 6968 btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it); 6969 entry->callback(HCI_EVENT_PACKET, 0, event, size); 6970 } 6971 } 6972 6973 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){ 6974 if (!hci_stack->acl_packet_handler) return; 6975 hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size); 6976 } 6977 6978 #ifdef ENABLE_CLASSIC 6979 static void hci_notify_if_sco_can_send_now(void){ 6980 // notify SCO sender if waiting 6981 if (!hci_stack->sco_waiting_for_can_send_now) return; 6982 if (hci_can_send_sco_packet_now()){ 6983 hci_stack->sco_waiting_for_can_send_now = 0; 6984 uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 }; 6985 hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event)); 6986 hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event)); 6987 } 6988 } 6989 6990 // parsing end emitting has been merged to reduce code size 6991 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) { 6992 uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN]; 6993 6994 uint8_t * eir_data; 6995 ad_context_t context; 6996 const uint8_t * name; 6997 uint8_t name_len; 6998 6999 if (size < 3) return; 7000 7001 int event_type = hci_event_packet_get_type(packet); 7002 int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1; // 2 for old event, 1 otherwise 7003 int num_responses = hci_event_inquiry_result_get_num_responses(packet); 7004 7005 switch (event_type){ 7006 case HCI_EVENT_INQUIRY_RESULT: 7007 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 7008 if (size != (3 + (num_responses * 14))) return; 7009 break; 7010 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 7011 if (size != 257) return; 7012 if (num_responses != 1) return; 7013 break; 7014 default: 7015 return; 7016 } 7017 7018 // event[1] is set at the end 7019 int i; 7020 for (i=0; i<num_responses;i++){ 7021 memset(event, 0, sizeof(event)); 7022 event[0] = GAP_EVENT_INQUIRY_RESULT; 7023 uint8_t event_size = 27; // if name is not set by EIR 7024 7025 (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr 7026 event[8] = packet[3 + (num_responses*(6)) + (i*1)]; // page_scan_repetition_mode 7027 (void)memcpy(&event[9], 7028 &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)], 7029 3); // class of device 7030 (void)memcpy(&event[12], 7031 &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)], 7032 2); // clock offset 7033 7034 switch (event_type){ 7035 case HCI_EVENT_INQUIRY_RESULT: 7036 // 14,15,16,17 = 0, size 18 7037 break; 7038 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 7039 event[14] = 1; 7040 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi 7041 // 16,17 = 0, size 18 7042 break; 7043 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 7044 event[14] = 1; 7045 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi 7046 // EIR packets only contain a single inquiry response 7047 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)]; 7048 name = NULL; 7049 // Iterate over EIR data 7050 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){ 7051 uint8_t data_type = ad_iterator_get_data_type(&context); 7052 uint8_t data_size = ad_iterator_get_data_len(&context); 7053 const uint8_t * data = ad_iterator_get_data(&context); 7054 // Prefer Complete Local Name over Shortened Local Name 7055 switch (data_type){ 7056 case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME: 7057 if (name) continue; 7058 /* fall through */ 7059 case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME: 7060 name = data; 7061 name_len = data_size; 7062 break; 7063 case BLUETOOTH_DATA_TYPE_DEVICE_ID: 7064 if (data_size != 8) break; 7065 event[16] = 1; 7066 memcpy(&event[17], data, 8); 7067 break; 7068 default: 7069 break; 7070 } 7071 } 7072 if (name){ 7073 event[25] = 1; 7074 // truncate name if needed 7075 int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN); 7076 event[26] = len; 7077 (void)memcpy(&event[27], name, len); 7078 event_size += len; 7079 } 7080 break; 7081 default: 7082 return; 7083 } 7084 event[1] = event_size - 2; 7085 hci_emit_event(event, event_size, 1); 7086 } 7087 } 7088 #endif 7089 7090 void hci_emit_state(void){ 7091 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 7092 uint8_t event[3]; 7093 event[0] = BTSTACK_EVENT_STATE; 7094 event[1] = sizeof(event) - 2u; 7095 event[2] = hci_stack->state; 7096 hci_emit_event(event, sizeof(event), 1); 7097 } 7098 7099 #ifdef ENABLE_CLASSIC 7100 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 7101 uint8_t event[13]; 7102 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 7103 event[1] = sizeof(event) - 2; 7104 event[2] = status; 7105 little_endian_store_16(event, 3, con_handle); 7106 reverse_bd_addr(address, &event[5]); 7107 event[11] = 1; // ACL connection 7108 event[12] = 0; // encryption disabled 7109 hci_emit_event(event, sizeof(event), 1); 7110 } 7111 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 7112 if (disable_l2cap_timeouts) return; 7113 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 7114 uint8_t event[4]; 7115 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 7116 event[1] = sizeof(event) - 2; 7117 little_endian_store_16(event, 2, conn->con_handle); 7118 hci_emit_event(event, sizeof(event), 1); 7119 } 7120 #endif 7121 7122 #ifdef ENABLE_BLE 7123 #ifdef ENABLE_LE_CENTRAL 7124 static void hci_emit_le_connection_complete(uint8_t address_type, const bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 7125 uint8_t event[21]; 7126 event[0] = HCI_EVENT_LE_META; 7127 event[1] = sizeof(event) - 2u; 7128 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 7129 event[3] = status; 7130 little_endian_store_16(event, 4, con_handle); 7131 event[6] = 0; // TODO: role 7132 event[7] = address_type; 7133 reverse_bd_addr(address, &event[8]); 7134 little_endian_store_16(event, 14, 0); // interval 7135 little_endian_store_16(event, 16, 0); // latency 7136 little_endian_store_16(event, 18, 0); // supervision timeout 7137 event[20] = 0; // master clock accuracy 7138 hci_emit_event(event, sizeof(event), 1); 7139 } 7140 #endif 7141 #endif 7142 7143 static void hci_emit_transport_packet_sent(void){ 7144 // notify upper stack that it might be possible to send again 7145 uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0}; 7146 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 7147 } 7148 7149 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){ 7150 uint8_t event[6]; 7151 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 7152 event[1] = sizeof(event) - 2u; 7153 event[2] = 0; // status = OK 7154 little_endian_store_16(event, 3, con_handle); 7155 event[5] = reason; 7156 hci_emit_event(event, sizeof(event), 1); 7157 } 7158 7159 static void hci_emit_nr_connections_changed(void){ 7160 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 7161 uint8_t event[3]; 7162 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 7163 event[1] = sizeof(event) - 2u; 7164 event[2] = nr_hci_connections(); 7165 hci_emit_event(event, sizeof(event), 1); 7166 } 7167 7168 static void hci_emit_hci_open_failed(void){ 7169 log_info("BTSTACK_EVENT_POWERON_FAILED"); 7170 uint8_t event[2]; 7171 event[0] = BTSTACK_EVENT_POWERON_FAILED; 7172 event[1] = sizeof(event) - 2u; 7173 hci_emit_event(event, sizeof(event), 1); 7174 } 7175 7176 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){ 7177 log_info("hci_emit_dedicated_bonding_result %u ", status); 7178 uint8_t event[9]; 7179 int pos = 0; 7180 event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED; 7181 event[pos++] = sizeof(event) - 2u; 7182 event[pos++] = status; 7183 reverse_bd_addr(address, &event[pos]); 7184 hci_emit_event(event, sizeof(event), 1); 7185 } 7186 7187 7188 #ifdef ENABLE_CLASSIC 7189 7190 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 7191 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 7192 uint8_t event[5]; 7193 int pos = 0; 7194 event[pos++] = GAP_EVENT_SECURITY_LEVEL; 7195 event[pos++] = sizeof(event) - 2; 7196 little_endian_store_16(event, 2, con_handle); 7197 pos += 2; 7198 event[pos++] = level; 7199 hci_emit_event(event, sizeof(event), 1); 7200 } 7201 7202 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 7203 if (!connection) return LEVEL_0; 7204 if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 7205 // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key 7206 if ((connection->authentication_flags & AUTH_FLAG_CONNECTION_AUTHENTICATED) == 0) return LEVEL_0; 7207 if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0; 7208 gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type); 7209 // LEVEL 4 always requires 128 bit encrytion key size 7210 if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){ 7211 security_level = LEVEL_3; 7212 } 7213 return security_level; 7214 } 7215 7216 static void hci_emit_scan_mode_changed(uint8_t discoverable, uint8_t connectable){ 7217 uint8_t event[4]; 7218 event[0] = BTSTACK_EVENT_SCAN_MODE_CHANGED; 7219 event[1] = sizeof(event) - 2; 7220 event[2] = discoverable; 7221 event[3] = connectable; 7222 hci_emit_event(event, sizeof(event), 1); 7223 } 7224 7225 // query if remote side supports eSCO 7226 bool hci_remote_esco_supported(hci_con_handle_t con_handle){ 7227 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7228 if (!connection) return false; 7229 return (connection->remote_supported_features[0] & 1) != 0; 7230 } 7231 7232 static bool hci_ssp_supported(hci_connection_t * connection){ 7233 const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST; 7234 return (connection->bonding_flags & mask) == mask; 7235 } 7236 7237 // query if remote side supports SSP 7238 bool hci_remote_ssp_supported(hci_con_handle_t con_handle){ 7239 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7240 if (!connection) return false; 7241 return hci_ssp_supported(connection) ? 1 : 0; 7242 } 7243 7244 bool gap_ssp_supported_on_both_sides(hci_con_handle_t handle){ 7245 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 7246 } 7247 7248 /** 7249 * Check if remote supported features query has completed 7250 */ 7251 bool hci_remote_features_available(hci_con_handle_t handle){ 7252 hci_connection_t * connection = hci_connection_for_handle(handle); 7253 if (!connection) return false; 7254 return (connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0; 7255 } 7256 7257 /** 7258 * Trigger remote supported features query 7259 */ 7260 7261 static void hci_trigger_remote_features_for_connection(hci_connection_t * connection){ 7262 if ((connection->bonding_flags & (BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_RECEIVED_REMOTE_FEATURES)) == 0){ 7263 connection->bonding_flags |= BONDING_REMOTE_FEATURES_QUERY_ACTIVE | BONDING_REQUEST_REMOTE_FEATURES_PAGE_0; 7264 } 7265 } 7266 7267 void hci_remote_features_query(hci_con_handle_t con_handle){ 7268 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7269 if (!connection) return; 7270 hci_trigger_remote_features_for_connection(connection); 7271 hci_run(); 7272 } 7273 7274 // GAP API 7275 /** 7276 * @bbrief enable/disable bonding. default is enabled 7277 * @praram enabled 7278 */ 7279 void gap_set_bondable_mode(int enable){ 7280 hci_stack->bondable = enable ? 1 : 0; 7281 } 7282 /** 7283 * @brief Get bondable mode. 7284 * @return 1 if bondable 7285 */ 7286 int gap_get_bondable_mode(void){ 7287 return hci_stack->bondable; 7288 } 7289 7290 /** 7291 * @brief map link keys to security levels 7292 */ 7293 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 7294 switch (link_key_type){ 7295 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7296 return LEVEL_4; 7297 case COMBINATION_KEY: 7298 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 7299 return LEVEL_3; 7300 default: 7301 return LEVEL_2; 7302 } 7303 } 7304 7305 /** 7306 * @brief map link keys to secure connection yes/no 7307 */ 7308 bool gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){ 7309 switch (link_key_type){ 7310 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7311 case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7312 return true; 7313 default: 7314 return false; 7315 } 7316 } 7317 7318 /** 7319 * @brief map link keys to authenticated 7320 */ 7321 bool gap_authenticated_for_link_key_type(link_key_type_t link_key_type){ 7322 switch (link_key_type){ 7323 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 7324 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 7325 return true; 7326 default: 7327 return false; 7328 } 7329 } 7330 7331 bool gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 7332 log_info("gap_mitm_protection_required_for_security_level %u", level); 7333 return level > LEVEL_2; 7334 } 7335 7336 /** 7337 * @brief get current security level 7338 */ 7339 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 7340 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7341 if (!connection) return LEVEL_0; 7342 return gap_security_level_for_connection(connection); 7343 } 7344 7345 /** 7346 * @brief request connection to device to 7347 * @result GAP_AUTHENTICATION_RESULT 7348 */ 7349 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 7350 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7351 if (!connection){ 7352 hci_emit_security_level(con_handle, LEVEL_0); 7353 return; 7354 } 7355 7356 btstack_assert(hci_is_le_connection(connection) == false); 7357 7358 // Core Spec 5.2, GAP 5.2.2: "When in Secure Connections Only mode, all services (except those allowed to have Security Mode 4, Level 0) 7359 // available on the BR/EDR physical transport require Security Mode 4, Level 4 " 7360 if (hci_stack->gap_secure_connections_only_mode && (requested_level != LEVEL_0)){ 7361 requested_level = LEVEL_4; 7362 } 7363 7364 gap_security_level_t current_level = gap_security_level(con_handle); 7365 log_info("gap_request_security_level requested level %u, planned level %u, current level %u", 7366 requested_level, connection->requested_security_level, current_level); 7367 7368 // authentication active if authentication request was sent or planned level > 0 7369 bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0); 7370 if (authentication_active){ 7371 // authentication already active 7372 if (connection->requested_security_level < requested_level){ 7373 // increase requested level as new level is higher 7374 // TODO: handle re-authentication when done 7375 connection->requested_security_level = requested_level; 7376 } 7377 } else { 7378 // no request active, notify if security sufficient 7379 if (requested_level <= current_level){ 7380 hci_emit_security_level(con_handle, current_level); 7381 return; 7382 } 7383 7384 // store request 7385 connection->requested_security_level = requested_level; 7386 7387 // start to authenticate connection 7388 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 7389 7390 // request remote features if not already active, also trigger hci_run 7391 hci_remote_features_query(con_handle); 7392 } 7393 } 7394 7395 /** 7396 * @brief start dedicated bonding with device. disconnect after bonding 7397 * @param device 7398 * @param request MITM protection 7399 * @result GAP_DEDICATED_BONDING_COMPLETE 7400 */ 7401 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 7402 7403 // create connection state machine 7404 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL); 7405 7406 if (!connection){ 7407 return BTSTACK_MEMORY_ALLOC_FAILED; 7408 } 7409 7410 // delete linkn key 7411 gap_drop_link_key_for_bd_addr(device); 7412 7413 // configure LEVEL_2/3, dedicated bonding 7414 connection->state = SEND_CREATE_CONNECTION; 7415 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 7416 log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level); 7417 connection->bonding_flags = BONDING_DEDICATED; 7418 7419 // wait for GAP Security Result and send GAP Dedicated Bonding complete 7420 7421 // handle: connnection failure (connection complete != ok) 7422 // handle: authentication failure 7423 // handle: disconnect on done 7424 7425 hci_run(); 7426 7427 return 0; 7428 } 7429 7430 void gap_set_local_name(const char * local_name){ 7431 hci_stack->local_name = local_name; 7432 hci_stack->gap_tasks_classic |= GAP_TASK_SET_LOCAL_NAME; 7433 // also update EIR if not set by user 7434 if (hci_stack->eir_data == NULL){ 7435 hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA; 7436 } 7437 hci_run(); 7438 } 7439 #endif 7440 7441 7442 #ifdef ENABLE_BLE 7443 7444 #ifdef ENABLE_LE_CENTRAL 7445 void gap_start_scan(void){ 7446 hci_stack->le_scanning_enabled = true; 7447 hci_run(); 7448 } 7449 7450 void gap_stop_scan(void){ 7451 hci_stack->le_scanning_enabled = false; 7452 hci_run(); 7453 } 7454 7455 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){ 7456 hci_stack->le_scan_type = scan_type; 7457 hci_stack->le_scan_filter_policy = scanning_filter_policy; 7458 hci_stack->le_scan_interval = scan_interval; 7459 hci_stack->le_scan_window = scan_window; 7460 hci_stack->le_scanning_param_update = true; 7461 hci_run(); 7462 } 7463 7464 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 7465 gap_set_scan_params(scan_type, scan_interval, scan_window, 0); 7466 } 7467 7468 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){ 7469 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 7470 if (!conn){ 7471 // disallow if le connection is already outgoing 7472 if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){ 7473 log_error("le connection already active"); 7474 return ERROR_CODE_COMMAND_DISALLOWED; 7475 } 7476 7477 log_info("gap_connect: no connection exists yet, creating context"); 7478 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 7479 if (!conn){ 7480 // notify client that alloc failed 7481 hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 7482 log_info("gap_connect: failed to alloc hci_connection_t"); 7483 return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller 7484 } 7485 7486 // set le connecting state 7487 if (hci_is_le_connection_type(addr_type)){ 7488 hci_stack->le_connecting_request = LE_CONNECTING_DIRECT; 7489 } 7490 7491 conn->state = SEND_CREATE_CONNECTION; 7492 log_info("gap_connect: send create connection next"); 7493 hci_run(); 7494 return ERROR_CODE_SUCCESS; 7495 } 7496 7497 if (!hci_is_le_connection(conn) || 7498 (conn->state == SEND_CREATE_CONNECTION) || 7499 (conn->state == SENT_CREATE_CONNECTION)) { 7500 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED); 7501 log_error("gap_connect: classic connection or connect is already being created"); 7502 return GATT_CLIENT_IN_WRONG_STATE; 7503 } 7504 7505 // check if connection was just disconnected 7506 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 7507 log_info("gap_connect: send create connection (again)"); 7508 conn->state = SEND_CREATE_CONNECTION; 7509 hci_run(); 7510 return ERROR_CODE_SUCCESS; 7511 } 7512 7513 log_info("gap_connect: context exists with state %u", conn->state); 7514 hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS); 7515 hci_run(); 7516 return ERROR_CODE_SUCCESS; 7517 } 7518 7519 // @assumption: only a single outgoing LE Connection exists 7520 static hci_connection_t * gap_get_outgoing_connection(void){ 7521 btstack_linked_item_t *it; 7522 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 7523 hci_connection_t * conn = (hci_connection_t *) it; 7524 if (!hci_is_le_connection(conn)) continue; 7525 switch (conn->state){ 7526 case SEND_CREATE_CONNECTION: 7527 case SENT_CREATE_CONNECTION: 7528 return conn; 7529 default: 7530 break; 7531 }; 7532 } 7533 return NULL; 7534 } 7535 7536 uint8_t gap_connect_cancel(void){ 7537 hci_connection_t * conn; 7538 switch (hci_stack->le_connecting_request){ 7539 case LE_CONNECTING_IDLE: 7540 break; 7541 case LE_CONNECTING_WHITELIST: 7542 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 7543 hci_run(); 7544 break; 7545 case LE_CONNECTING_DIRECT: 7546 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 7547 conn = gap_get_outgoing_connection(); 7548 if (conn == NULL){ 7549 hci_run(); 7550 } else { 7551 switch (conn->state){ 7552 case SEND_CREATE_CONNECTION: 7553 // skip sending create connection and emit event instead 7554 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 7555 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 7556 btstack_memory_hci_connection_free( conn ); 7557 break; 7558 case SENT_CREATE_CONNECTION: 7559 // let hci_run_general_gap_le cancel outgoing connection 7560 hci_run(); 7561 break; 7562 default: 7563 break; 7564 } 7565 } 7566 break; 7567 default: 7568 btstack_unreachable(); 7569 break; 7570 } 7571 return ERROR_CODE_SUCCESS; 7572 } 7573 7574 /** 7575 * @brief Set connection parameters for outgoing connections 7576 * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms 7577 * @param conn_scan_window (unit: 0.625 msec), default: 30 ms 7578 * @param conn_interval_min (unit: 1.25ms), default: 10 ms 7579 * @param conn_interval_max (unit: 1.25ms), default: 30 ms 7580 * @param conn_latency, default: 4 7581 * @param supervision_timeout (unit: 10ms), default: 720 ms 7582 * @param min_ce_length (unit: 0.625ms), default: 10 ms 7583 * @param max_ce_length (unit: 0.625ms), default: 30 ms 7584 */ 7585 7586 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window, 7587 uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, 7588 uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){ 7589 hci_stack->le_connection_scan_interval = conn_scan_interval; 7590 hci_stack->le_connection_scan_window = conn_scan_window; 7591 hci_stack->le_connection_interval_min = conn_interval_min; 7592 hci_stack->le_connection_interval_max = conn_interval_max; 7593 hci_stack->le_connection_latency = conn_latency; 7594 hci_stack->le_supervision_timeout = supervision_timeout; 7595 hci_stack->le_minimum_ce_length = min_ce_length; 7596 hci_stack->le_maximum_ce_length = max_ce_length; 7597 } 7598 #endif 7599 7600 /** 7601 * @brief Updates the connection parameters for a given LE connection 7602 * @param handle 7603 * @param conn_interval_min (unit: 1.25ms) 7604 * @param conn_interval_max (unit: 1.25ms) 7605 * @param conn_latency 7606 * @param supervision_timeout (unit: 10ms) 7607 * @return 0 if ok 7608 */ 7609 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min, 7610 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 7611 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7612 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7613 connection->le_conn_interval_min = conn_interval_min; 7614 connection->le_conn_interval_max = conn_interval_max; 7615 connection->le_conn_latency = conn_latency; 7616 connection->le_supervision_timeout = supervision_timeout; 7617 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 7618 hci_run(); 7619 return 0; 7620 } 7621 7622 /** 7623 * @brief Request an update of the connection parameter for a given LE connection 7624 * @param handle 7625 * @param conn_interval_min (unit: 1.25ms) 7626 * @param conn_interval_max (unit: 1.25ms) 7627 * @param conn_latency 7628 * @param supervision_timeout (unit: 10ms) 7629 * @return 0 if ok 7630 */ 7631 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min, 7632 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 7633 hci_connection_t * connection = hci_connection_for_handle(con_handle); 7634 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7635 connection->le_conn_interval_min = conn_interval_min; 7636 connection->le_conn_interval_max = conn_interval_max; 7637 connection->le_conn_latency = conn_latency; 7638 connection->le_supervision_timeout = supervision_timeout; 7639 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST; 7640 uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0}; 7641 hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0); 7642 return 0; 7643 } 7644 7645 #ifdef ENABLE_LE_PERIPHERAL 7646 7647 /** 7648 * @brief Set Advertisement Data 7649 * @param advertising_data_length 7650 * @param advertising_data (max 31 octets) 7651 * @note data is not copied, pointer has to stay valid 7652 */ 7653 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){ 7654 hci_stack->le_advertisements_data_len = advertising_data_length; 7655 hci_stack->le_advertisements_data = advertising_data; 7656 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 7657 hci_run(); 7658 } 7659 7660 /** 7661 * @brief Set Scan Response Data 7662 * @param advertising_data_length 7663 * @param advertising_data (max 31 octets) 7664 * @note data is not copied, pointer has to stay valid 7665 */ 7666 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){ 7667 hci_stack->le_scan_response_data_len = scan_response_data_length; 7668 hci_stack->le_scan_response_data = scan_response_data; 7669 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 7670 hci_run(); 7671 } 7672 7673 /** 7674 * @brief Set Advertisement Parameters 7675 * @param adv_int_min 7676 * @param adv_int_max 7677 * @param adv_type 7678 * @param direct_address_type 7679 * @param direct_address 7680 * @param channel_map 7681 * @param filter_policy 7682 * 7683 * @note internal use. use gap_advertisements_set_params from gap_le.h instead. 7684 */ 7685 void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 7686 uint8_t direct_address_typ, bd_addr_t direct_address, 7687 uint8_t channel_map, uint8_t filter_policy) { 7688 7689 hci_stack->le_advertisements_interval_min = adv_int_min; 7690 hci_stack->le_advertisements_interval_max = adv_int_max; 7691 hci_stack->le_advertisements_type = adv_type; 7692 hci_stack->le_advertisements_direct_address_type = direct_address_typ; 7693 hci_stack->le_advertisements_channel_map = channel_map; 7694 hci_stack->le_advertisements_filter_policy = filter_policy; 7695 (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address, 7696 6); 7697 7698 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 7699 hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_PARAMS_SET; 7700 hci_run(); 7701 } 7702 7703 /** 7704 * @brief Enable/Disable Advertisements 7705 * @param enabled 7706 */ 7707 void gap_advertisements_enable(int enabled){ 7708 if (enabled == 0){ 7709 hci_stack->le_advertisements_state &= ~LE_ADVERTISEMENT_STATE_ENABLED; 7710 } else { 7711 hci_stack->le_advertisements_state |= LE_ADVERTISEMENT_STATE_ENABLED; 7712 } 7713 hci_update_advertisements_enabled_for_current_roles(); 7714 hci_run(); 7715 } 7716 7717 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 7718 static le_advertising_set_t * hci_advertising_set_for_handle(uint8_t advertising_handle){ 7719 btstack_linked_list_iterator_t it; 7720 btstack_linked_list_iterator_init(&it, &hci_stack->le_advertising_sets); 7721 while (btstack_linked_list_iterator_has_next(&it)){ 7722 le_advertising_set_t * item = (le_advertising_set_t *) btstack_linked_list_iterator_next(&it); 7723 if ( item->advertising_handle == advertising_handle ) { 7724 return item; 7725 } 7726 } 7727 return NULL; 7728 } 7729 7730 uint8_t gap_extended_advertising_setup(le_advertising_set_t * storage, const le_extended_advertising_parameters_t * advertising_parameters, uint8_t * out_advertising_handle){ 7731 // find free advertisement handle 7732 uint8_t advertisement_handle; 7733 for (advertisement_handle = 1; advertisement_handle <= LE_EXTENDED_ADVERTISING_MAX_HANDLE; advertisement_handle++){ 7734 if (hci_advertising_set_for_handle(advertisement_handle) == NULL) break; 7735 } 7736 if (advertisement_handle > LE_EXTENDED_ADVERTISING_MAX_HANDLE) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED; 7737 // clear 7738 memset(storage, 0, sizeof(le_advertising_set_t)); 7739 // copy params 7740 storage->advertising_handle = advertisement_handle; 7741 memcpy(&storage->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t)); 7742 // add to list 7743 bool add_ok = btstack_linked_list_add(&hci_stack->le_advertising_sets, (btstack_linked_item_t *) storage); 7744 if (!add_ok) return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 7745 *out_advertising_handle = advertisement_handle; 7746 // set tasks and start 7747 storage->tasks = LE_ADVERTISEMENT_TASKS_SET_PARAMS; 7748 hci_run(); 7749 return ERROR_CODE_SUCCESS; 7750 } 7751 7752 uint8_t gap_extended_advertising_set_params(uint8_t advertising_handle, const le_extended_advertising_parameters_t * advertising_parameters){ 7753 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7754 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7755 memcpy(&advertising_set->extended_params, advertising_parameters, sizeof(le_extended_advertising_parameters_t)); 7756 // set tasks and start 7757 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 7758 hci_run(); 7759 return ERROR_CODE_SUCCESS; 7760 } 7761 7762 uint8_t gap_extended_advertising_get_params(uint8_t advertising_handle, le_extended_advertising_parameters_t * advertising_parameters){ 7763 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7764 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7765 memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_extended_advertising_parameters_t)); 7766 return ERROR_CODE_SUCCESS; 7767 } 7768 7769 uint8_t gap_extended_advertising_set_random_address(uint8_t advertising_handle, bd_addr_t random_address){ 7770 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7771 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7772 memcpy(advertising_set->random_address, random_address, 6); 7773 // set tasks and start 7774 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 7775 hci_run(); 7776 return ERROR_CODE_SUCCESS; 7777 } 7778 7779 uint8_t gap_extended_advertising_set_adv_data(uint8_t advertising_handle, uint16_t advertising_data_length, const uint8_t * advertising_data){ 7780 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7781 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7782 advertising_set->adv_data = advertising_data; 7783 advertising_set->adv_data_len = advertising_data_length; 7784 // set tasks and start 7785 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 7786 hci_run(); 7787 return ERROR_CODE_SUCCESS; 7788 } 7789 7790 uint8_t gap_extended_advertising_set_scan_response_data(uint8_t advertising_handle, uint16_t scan_response_data_length, const uint8_t * scan_response_data){ 7791 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7792 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7793 advertising_set->scan_data = scan_response_data; 7794 advertising_set->scan_data_len = scan_response_data_length; 7795 // set tasks and start 7796 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 7797 hci_run(); 7798 return ERROR_CODE_SUCCESS; 7799 } 7800 7801 uint8_t gap_extended_advertising_start(uint8_t advertising_handle, uint16_t timeout, uint8_t num_extended_advertising_events){ 7802 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7803 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7804 advertising_set->enable_timeout = timeout; 7805 advertising_set->enable_max_scan_events = num_extended_advertising_events; 7806 // set tasks and start 7807 advertising_set->state |= LE_ADVERTISEMENT_STATE_ENABLED; 7808 hci_run(); 7809 return ERROR_CODE_SUCCESS; 7810 } 7811 7812 uint8_t gap_extended_advertising_stop(uint8_t advertising_handle){ 7813 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7814 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7815 // set tasks and start 7816 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_ENABLED; 7817 hci_run(); 7818 return ERROR_CODE_SUCCESS; 7819 } 7820 7821 uint8_t gap_extended_advertising_remove(uint8_t advertising_handle){ 7822 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7823 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7824 // set tasks and start 7825 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_REMOVE_SET; 7826 hci_run(); 7827 return ERROR_CODE_SUCCESS; 7828 } 7829 7830 #ifdef ENABLE_LE_PERIODIC_ADVERTISING 7831 uint8_t gap_periodic_advertising_set_params(uint8_t advertising_handle, const le_periodic_advertising_parameters_t * advertising_parameters){ 7832 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7833 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7834 // periodic advertising requires neither connectable, scannable, legacy or anonymous 7835 if ((advertising_set->extended_params.advertising_event_properties & 0x1f) != 0) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 7836 memcpy(&advertising_set->periodic_params, advertising_parameters, sizeof(le_periodic_advertising_parameters_t)); 7837 // set tasks and start 7838 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_PARAMS; 7839 hci_run(); 7840 return ERROR_CODE_SUCCESS; 7841 } 7842 7843 uint8_t gap_periodic_advertising_get_params(uint8_t advertising_handle, le_periodic_advertising_parameters_t * advertising_parameters){ 7844 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7845 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7846 memcpy(advertising_parameters, &advertising_set->extended_params, sizeof(le_periodic_advertising_parameters_t)); 7847 return ERROR_CODE_SUCCESS; 7848 } 7849 7850 uint8_t gap_periodic_advertising_set_data(uint8_t advertising_handle, uint16_t periodic_data_length, const uint8_t * periodic_data){ 7851 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7852 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7853 advertising_set->periodic_data = periodic_data; 7854 advertising_set->periodic_data_len = periodic_data_length; 7855 // set tasks and start 7856 advertising_set->tasks |= LE_ADVERTISEMENT_TASKS_SET_PERIODIC_DATA; 7857 hci_run(); 7858 return ERROR_CODE_SUCCESS; 7859 } 7860 7861 uint8_t gap_periodic_advertising_start(uint8_t advertising_handle, bool include_adi){ 7862 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7863 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7864 // set tasks and start 7865 advertising_set->periodic_include_adi = include_adi; 7866 advertising_set->state |= LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED; 7867 hci_run(); 7868 return ERROR_CODE_SUCCESS; 7869 } 7870 7871 uint8_t gap_periodic_advertising_stop(uint8_t advertising_handle){ 7872 le_advertising_set_t * advertising_set = hci_advertising_set_for_handle(advertising_handle); 7873 if (advertising_set == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7874 // set tasks and start 7875 advertising_set->state &= ~LE_ADVERTISEMENT_STATE_PERIODIC_ENABLED; 7876 hci_run(); 7877 return ERROR_CODE_SUCCESS; 7878 } 7879 #endif /* ENABLE_LE_PERIODIC_ADVERTISING */ 7880 7881 #endif 7882 7883 #endif 7884 7885 void hci_le_set_own_address_type(uint8_t own_address_type){ 7886 log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type); 7887 if (own_address_type == hci_stack->le_own_addr_type) return; 7888 hci_stack->le_own_addr_type = own_address_type; 7889 7890 #ifdef ENABLE_LE_PERIPHERAL 7891 // update advertisement parameters, too 7892 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 7893 hci_run(); 7894 #endif 7895 #ifdef ENABLE_LE_CENTRAL 7896 // note: we don't update scan parameters or modify ongoing connection attempts 7897 #endif 7898 } 7899 7900 void hci_le_random_address_set(const bd_addr_t random_address){ 7901 memcpy(hci_stack->le_random_address, random_address, 6); 7902 hci_stack->le_random_address_set = true; 7903 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADDRESS; 7904 hci_run(); 7905 } 7906 7907 #endif 7908 7909 uint8_t gap_disconnect(hci_con_handle_t handle){ 7910 hci_connection_t * conn = hci_connection_for_handle(handle); 7911 if (!conn){ 7912 hci_emit_disconnection_complete(handle, 0); 7913 return 0; 7914 } 7915 // ignore if already disconnected 7916 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 7917 return 0; 7918 } 7919 conn->state = SEND_DISCONNECT; 7920 hci_run(); 7921 return 0; 7922 } 7923 7924 int gap_read_rssi(hci_con_handle_t con_handle){ 7925 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 7926 if (hci_connection == NULL) return 0; 7927 hci_connection->gap_connection_tasks |= GAP_CONNECTION_TASK_READ_RSSI; 7928 hci_run(); 7929 return 1; 7930 } 7931 7932 /** 7933 * @brief Get connection type 7934 * @param con_handle 7935 * @result connection_type 7936 */ 7937 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){ 7938 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 7939 if (!conn) return GAP_CONNECTION_INVALID; 7940 switch (conn->address_type){ 7941 case BD_ADDR_TYPE_LE_PUBLIC: 7942 case BD_ADDR_TYPE_LE_RANDOM: 7943 return GAP_CONNECTION_LE; 7944 case BD_ADDR_TYPE_SCO: 7945 return GAP_CONNECTION_SCO; 7946 case BD_ADDR_TYPE_ACL: 7947 return GAP_CONNECTION_ACL; 7948 default: 7949 return GAP_CONNECTION_INVALID; 7950 } 7951 } 7952 7953 hci_role_t gap_get_role(hci_con_handle_t connection_handle){ 7954 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 7955 if (!conn) return HCI_ROLE_INVALID; 7956 return (hci_role_t) conn->role; 7957 } 7958 7959 7960 #ifdef ENABLE_CLASSIC 7961 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){ 7962 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 7963 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7964 conn->request_role = role; 7965 hci_run(); 7966 return ERROR_CODE_SUCCESS; 7967 } 7968 #endif 7969 7970 #ifdef ENABLE_BLE 7971 7972 uint8_t gap_le_set_phy(hci_con_handle_t con_handle, uint8_t all_phys, uint8_t tx_phys, uint8_t rx_phys, uint8_t phy_options){ 7973 hci_connection_t * conn = hci_connection_for_handle(con_handle); 7974 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 7975 7976 conn->le_phy_update_all_phys = all_phys; 7977 conn->le_phy_update_tx_phys = tx_phys; 7978 conn->le_phy_update_rx_phys = rx_phys; 7979 conn->le_phy_update_phy_options = phy_options; 7980 7981 hci_run(); 7982 7983 return 0; 7984 } 7985 7986 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){ 7987 // check if already in list 7988 btstack_linked_list_iterator_t it; 7989 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 7990 while (btstack_linked_list_iterator_has_next(&it)) { 7991 whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it); 7992 if (entry->address_type != address_type) { 7993 continue; 7994 } 7995 if (memcmp(entry->address, address, 6) != 0) { 7996 continue; 7997 } 7998 // disallow if already scheduled to add 7999 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){ 8000 return ERROR_CODE_COMMAND_DISALLOWED; 8001 } 8002 // still on controller, but scheduled to remove -> re-add 8003 entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER; 8004 return ERROR_CODE_SUCCESS; 8005 } 8006 // alloc and add to list 8007 whitelist_entry_t * entry = btstack_memory_whitelist_entry_get(); 8008 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 8009 entry->address_type = address_type; 8010 (void)memcpy(entry->address, address, 6); 8011 entry->state = LE_WHITELIST_ADD_TO_CONTROLLER; 8012 btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry); 8013 return ERROR_CODE_SUCCESS; 8014 } 8015 8016 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){ 8017 btstack_linked_list_iterator_t it; 8018 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 8019 while (btstack_linked_list_iterator_has_next(&it)){ 8020 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 8021 if (entry->address_type != address_type) { 8022 continue; 8023 } 8024 if (memcmp(entry->address, address, 6) != 0) { 8025 continue; 8026 } 8027 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 8028 // remove from controller if already present 8029 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 8030 } else { 8031 // directly remove entry from whitelist 8032 btstack_linked_list_iterator_remove(&it); 8033 btstack_memory_whitelist_entry_free(entry); 8034 } 8035 return ERROR_CODE_SUCCESS; 8036 } 8037 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8038 } 8039 8040 static void hci_whitelist_clear(void){ 8041 btstack_linked_list_iterator_t it; 8042 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 8043 while (btstack_linked_list_iterator_has_next(&it)){ 8044 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 8045 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 8046 // remove from controller if already present 8047 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 8048 continue; 8049 } 8050 // directly remove entry from whitelist 8051 btstack_linked_list_iterator_remove(&it); 8052 btstack_memory_whitelist_entry_free(entry); 8053 } 8054 } 8055 8056 // free all entries unconditionally 8057 static void hci_whitelist_free(void){ 8058 btstack_linked_list_iterator_t lit; 8059 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 8060 while (btstack_linked_list_iterator_has_next(&lit)){ 8061 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 8062 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 8063 btstack_memory_whitelist_entry_free(entry); 8064 } 8065 } 8066 8067 /** 8068 * @brief Clear Whitelist 8069 * @return 0 if ok 8070 */ 8071 uint8_t gap_whitelist_clear(void){ 8072 hci_whitelist_clear(); 8073 hci_run(); 8074 return ERROR_CODE_SUCCESS; 8075 } 8076 8077 /** 8078 * @brief Add Device to Whitelist 8079 * @param address_typ 8080 * @param address 8081 * @return 0 if ok 8082 */ 8083 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){ 8084 uint8_t status = hci_whitelist_add(address_type, address); 8085 if (status){ 8086 return status; 8087 } 8088 hci_run(); 8089 return ERROR_CODE_SUCCESS; 8090 } 8091 8092 /** 8093 * @brief Remove Device from Whitelist 8094 * @param address_typ 8095 * @param address 8096 * @return 0 if ok 8097 */ 8098 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){ 8099 uint8_t status = hci_whitelist_remove(address_type, address); 8100 if (status){ 8101 return status; 8102 } 8103 hci_run(); 8104 return ERROR_CODE_SUCCESS; 8105 } 8106 8107 #ifdef ENABLE_LE_CENTRAL 8108 /** 8109 * @brief Connect with Whitelist 8110 * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions 8111 * @return - if ok 8112 */ 8113 uint8_t gap_connect_with_whitelist(void){ 8114 if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){ 8115 return ERROR_CODE_COMMAND_DISALLOWED; 8116 } 8117 hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST; 8118 hci_run(); 8119 return ERROR_CODE_SUCCESS; 8120 } 8121 8122 /** 8123 * @brief Auto Connection Establishment - Start Connecting to device 8124 * @param address_typ 8125 * @param address 8126 * @return 0 if ok 8127 */ 8128 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){ 8129 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){ 8130 return ERROR_CODE_COMMAND_DISALLOWED; 8131 } 8132 8133 uint8_t status = hci_whitelist_add(address_type, address); 8134 if (status == BTSTACK_MEMORY_ALLOC_FAILED) { 8135 return status; 8136 } 8137 8138 hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST; 8139 8140 hci_run(); 8141 return ERROR_CODE_SUCCESS; 8142 } 8143 8144 /** 8145 * @brief Auto Connection Establishment - Stop Connecting to device 8146 * @param address_typ 8147 * @param address 8148 * @return 0 if ok 8149 */ 8150 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){ 8151 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){ 8152 return ERROR_CODE_COMMAND_DISALLOWED; 8153 } 8154 8155 hci_whitelist_remove(address_type, address); 8156 if (btstack_linked_list_empty(&hci_stack->le_whitelist)){ 8157 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 8158 } 8159 hci_run(); 8160 return 0; 8161 } 8162 8163 /** 8164 * @brief Auto Connection Establishment - Stop everything 8165 * @note Convenience function to stop all active auto connection attempts 8166 */ 8167 uint8_t gap_auto_connection_stop_all(void){ 8168 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) { 8169 return ERROR_CODE_COMMAND_DISALLOWED; 8170 } 8171 hci_whitelist_clear(); 8172 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 8173 hci_run(); 8174 return ERROR_CODE_SUCCESS; 8175 } 8176 8177 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){ 8178 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8179 if (!conn) return 0; 8180 return conn->le_connection_interval; 8181 } 8182 #endif 8183 #endif 8184 8185 #ifdef ENABLE_CLASSIC 8186 /** 8187 * @brief Set Extended Inquiry Response data 8188 * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup 8189 * @note has to be done before stack starts up 8190 */ 8191 void gap_set_extended_inquiry_response(const uint8_t * data){ 8192 hci_stack->eir_data = data; 8193 hci_stack->gap_tasks_classic |= GAP_TASK_SET_EIR_DATA; 8194 hci_run(); 8195 } 8196 8197 /** 8198 * @brief Start GAP Classic Inquiry 8199 * @param duration in 1.28s units 8200 * @return 0 if ok 8201 * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE 8202 */ 8203 int gap_inquiry_start(uint8_t duration_in_1280ms_units){ 8204 if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED; 8205 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8206 if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){ 8207 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8208 } 8209 hci_stack->inquiry_state = duration_in_1280ms_units; 8210 hci_stack->inquiry_max_period_length = 0; 8211 hci_stack->inquiry_min_period_length = 0; 8212 hci_run(); 8213 return 0; 8214 } 8215 8216 uint8_t gap_inquiry_periodic_start(uint8_t duration, uint16_t max_period_length, uint16_t min_period_length){ 8217 if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED; 8218 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8219 if (duration < GAP_INQUIRY_DURATION_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8220 if (duration > GAP_INQUIRY_DURATION_MAX) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 8221 if (max_period_length < GAP_INQUIRY_MAX_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;; 8222 if (min_period_length < GAP_INQUIRY_MIN_PERIODIC_LEN_MIN) return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;; 8223 8224 hci_stack->inquiry_state = duration; 8225 hci_stack->inquiry_max_period_length = max_period_length; 8226 hci_stack->inquiry_min_period_length = min_period_length; 8227 hci_run(); 8228 return 0; 8229 } 8230 8231 /** 8232 * @brief Stop GAP Classic Inquiry 8233 * @return 0 if ok 8234 */ 8235 int gap_inquiry_stop(void){ 8236 if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) { 8237 // emit inquiry complete event, before it even started 8238 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 8239 hci_emit_event(event, sizeof(event), 1); 8240 return 0; 8241 } 8242 switch (hci_stack->inquiry_state){ 8243 case GAP_INQUIRY_STATE_ACTIVE: 8244 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL; 8245 hci_run(); 8246 return ERROR_CODE_SUCCESS; 8247 case GAP_INQUIRY_STATE_PERIODIC: 8248 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_EXIT_PERIODIC; 8249 hci_run(); 8250 return ERROR_CODE_SUCCESS; 8251 default: 8252 return ERROR_CODE_COMMAND_DISALLOWED; 8253 } 8254 } 8255 8256 void gap_inquiry_set_lap(uint32_t lap){ 8257 hci_stack->inquiry_lap = lap; 8258 } 8259 8260 void gap_inquiry_set_scan_activity(uint16_t inquiry_scan_interval, uint16_t inquiry_scan_window){ 8261 hci_stack->inquiry_scan_interval = inquiry_scan_interval; 8262 hci_stack->inquiry_scan_window = inquiry_scan_window; 8263 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_INQUIRY_SCAN_ACTIVITY; 8264 hci_run(); 8265 } 8266 8267 8268 /** 8269 * @brief Remote Name Request 8270 * @param addr 8271 * @param page_scan_repetition_mode 8272 * @param clock_offset only used when bit 15 is set 8273 * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 8274 */ 8275 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){ 8276 if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8277 (void)memcpy(hci_stack->remote_name_addr, addr, 6); 8278 hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode; 8279 hci_stack->remote_name_clock_offset = clock_offset; 8280 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND; 8281 hci_run(); 8282 return 0; 8283 } 8284 8285 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){ 8286 hci_stack->gap_pairing_state = state; 8287 (void)memcpy(hci_stack->gap_pairing_addr, addr, 6); 8288 hci_run(); 8289 return 0; 8290 } 8291 8292 /** 8293 * @brief Legacy Pairing Pin Code Response for binary data / non-strings 8294 * @param addr 8295 * @param pin_data 8296 * @param pin_len 8297 * @return 0 if ok 8298 */ 8299 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){ 8300 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8301 hci_stack->gap_pairing_input.gap_pairing_pin = pin_data; 8302 hci_stack->gap_pairing_pin_len = pin_len; 8303 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN); 8304 } 8305 8306 /** 8307 * @brief Legacy Pairing Pin Code Response 8308 * @param addr 8309 * @param pin 8310 * @return 0 if ok 8311 */ 8312 int gap_pin_code_response(const bd_addr_t addr, const char * pin){ 8313 return gap_pin_code_response_binary(addr, (const uint8_t*) pin, (uint8_t) strlen(pin)); 8314 } 8315 8316 /** 8317 * @brief Abort Legacy Pairing 8318 * @param addr 8319 * @param pin 8320 * @return 0 if ok 8321 */ 8322 int gap_pin_code_negative(bd_addr_t addr){ 8323 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8324 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE); 8325 } 8326 8327 /** 8328 * @brief SSP Passkey Response 8329 * @param addr 8330 * @param passkey 8331 * @return 0 if ok 8332 */ 8333 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){ 8334 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8335 hci_stack->gap_pairing_input.gap_pairing_passkey = passkey; 8336 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY); 8337 } 8338 8339 /** 8340 * @brief Abort SSP Passkey Entry/Pairing 8341 * @param addr 8342 * @param pin 8343 * @return 0 if ok 8344 */ 8345 int gap_ssp_passkey_negative(const bd_addr_t addr){ 8346 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8347 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE); 8348 } 8349 8350 /** 8351 * @brief Accept SSP Numeric Comparison 8352 * @param addr 8353 * @param passkey 8354 * @return 0 if ok 8355 */ 8356 int gap_ssp_confirmation_response(const bd_addr_t addr){ 8357 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8358 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION); 8359 } 8360 8361 /** 8362 * @brief Abort SSP Numeric Comparison/Pairing 8363 * @param addr 8364 * @param pin 8365 * @return 0 if ok 8366 */ 8367 int gap_ssp_confirmation_negative(const bd_addr_t addr){ 8368 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 8369 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE); 8370 } 8371 8372 #if defined(ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY) || defined(ENABLE_EXPLICIT_LINK_KEY_REPLY) 8373 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){ 8374 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8375 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8376 connectionSetAuthenticationFlags(conn, flag); 8377 hci_run(); 8378 return ERROR_CODE_SUCCESS; 8379 } 8380 #endif 8381 8382 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 8383 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){ 8384 return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_REPLY); 8385 } 8386 8387 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){ 8388 return gap_set_auth_flag_and_run(addr, AUTH_FLAG_SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 8389 } 8390 #endif 8391 8392 #ifdef ENABLE_CLASSIC_PAIRING_OOB 8393 /** 8394 * @brief Report Remote OOB Data 8395 * @param bd_addr 8396 * @param c_192 Simple Pairing Hash C derived from P-192 public key 8397 * @param r_192 Simple Pairing Randomizer derived from P-192 public key 8398 * @param c_256 Simple Pairing Hash C derived from P-256 public key 8399 * @param r_256 Simple Pairing Randomizer derived from P-256 public key 8400 */ 8401 uint8_t gap_ssp_remote_oob_data(const bd_addr_t addr, const uint8_t * c_192, const uint8_t * r_192, const uint8_t * c_256, const uint8_t * r_256){ 8402 hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8403 if (connection == NULL) { 8404 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8405 } 8406 connection->classic_oob_c_192 = c_192; 8407 connection->classic_oob_r_192 = r_192; 8408 8409 // ignore P-256 if not supported by us 8410 if (hci_stack->secure_connections_active){ 8411 connection->classic_oob_c_256 = c_256; 8412 connection->classic_oob_r_256 = r_256; 8413 } 8414 8415 return ERROR_CODE_SUCCESS; 8416 } 8417 /** 8418 * @brief Generate new OOB data 8419 * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures 8420 */ 8421 void gap_ssp_generate_oob_data(void){ 8422 hci_stack->classic_read_local_oob_data = true; 8423 hci_run(); 8424 } 8425 8426 #endif 8427 8428 #ifdef ENABLE_EXPLICIT_LINK_KEY_REPLY 8429 uint8_t gap_send_link_key_response(const bd_addr_t addr, link_key_t link_key, link_key_type_t type){ 8430 hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 8431 if (connection == NULL) { 8432 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8433 } 8434 8435 memcpy(connection->link_key, link_key, sizeof(link_key_t)); 8436 connection->link_key_type = type; 8437 8438 return gap_set_auth_flag_and_run(addr, AUTH_FLAG_HANDLE_LINK_KEY_REQUEST); 8439 } 8440 8441 #endif // ENABLE_EXPLICIT_LINK_KEY_REPLY 8442 /** 8443 * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on. 8444 * @param inquiry_mode see bluetooth_defines.h 8445 */ 8446 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){ 8447 hci_stack->inquiry_mode = inquiry_mode; 8448 } 8449 8450 /** 8451 * @brief Configure Voice Setting for use with SCO data in HSP/HFP 8452 */ 8453 void hci_set_sco_voice_setting(uint16_t voice_setting){ 8454 hci_stack->sco_voice_setting = voice_setting; 8455 } 8456 8457 /** 8458 * @brief Get SCO Voice Setting 8459 * @return current voice setting 8460 */ 8461 uint16_t hci_get_sco_voice_setting(void){ 8462 return hci_stack->sco_voice_setting; 8463 } 8464 8465 static int hci_have_usb_transport(void){ 8466 if (!hci_stack->hci_transport) return 0; 8467 const char * transport_name = hci_stack->hci_transport->name; 8468 if (!transport_name) return 0; 8469 return (transport_name[0] == 'H') && (transport_name[1] == '2'); 8470 } 8471 8472 /** @brief Get SCO packet length for current SCO Voice setting 8473 * @note Using SCO packets of the exact length is required for USB transfer 8474 * @return Length of SCO packets in bytes (not audio frames) 8475 */ 8476 uint16_t hci_get_sco_packet_length(void){ 8477 uint16_t sco_packet_length = 0; 8478 8479 #ifdef ENABLE_SCO_OVER_HCI 8480 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 8481 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 8482 8483 if (hci_have_usb_transport()){ 8484 // see Core Spec for H2 USB Transfer. 8485 // 3 byte SCO header + 24 bytes per connection 8486 int num_sco_connections = btstack_max(1, hci_number_sco_connections()); 8487 sco_packet_length = 3 + 24 * num_sco_connections * multiplier; 8488 } else { 8489 // 3 byte SCO header + SCO packet size over the air (60 bytes) 8490 sco_packet_length = 3 + 60 * multiplier; 8491 // assert that it still fits inside an SCO buffer 8492 if (sco_packet_length > (hci_stack->sco_data_packet_length + 3)){ 8493 sco_packet_length = 3 + 60; 8494 } 8495 } 8496 #endif 8497 8498 #ifdef HAVE_SCO_TRANSPORT 8499 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 8500 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 8501 sco_packet_length = 3 + 60 * multiplier; 8502 #endif 8503 return sco_packet_length; 8504 } 8505 8506 /** 8507 * @brief Sets the master/slave policy 8508 * @param policy (0: attempt to become master, 1: let connecting device decide) 8509 */ 8510 void hci_set_master_slave_policy(uint8_t policy){ 8511 hci_stack->master_slave_policy = policy; 8512 } 8513 8514 #endif 8515 8516 HCI_STATE hci_get_state(void){ 8517 return hci_stack->state; 8518 } 8519 8520 #ifdef ENABLE_CLASSIC 8521 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){ 8522 hci_stack->gap_classic_accept_callback = accept_callback; 8523 } 8524 #endif 8525 8526 /** 8527 * @brief Set callback for Bluetooth Hardware Error 8528 */ 8529 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){ 8530 hci_stack->hardware_error_callback = fn; 8531 } 8532 8533 void hci_disconnect_all(void){ 8534 btstack_linked_list_iterator_t it; 8535 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 8536 while (btstack_linked_list_iterator_has_next(&it)){ 8537 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 8538 if (con->state == SENT_DISCONNECT) continue; 8539 con->state = SEND_DISCONNECT; 8540 } 8541 hci_run(); 8542 } 8543 8544 uint16_t hci_get_manufacturer(void){ 8545 return hci_stack->manufacturer; 8546 } 8547 8548 #ifdef ENABLE_BLE 8549 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 8550 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 8551 if (!hci_con) return NULL; 8552 return &hci_con->sm_connection; 8553 } 8554 8555 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build 8556 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated 8557 #endif 8558 8559 uint8_t gap_encryption_key_size(hci_con_handle_t con_handle){ 8560 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8561 if (hci_connection == NULL) return 0; 8562 if (hci_is_le_connection(hci_connection)){ 8563 #ifdef ENABLE_BLE 8564 sm_connection_t * sm_conn = &hci_connection->sm_connection; 8565 if (sm_conn->sm_connection_encrypted) { 8566 return sm_conn->sm_actual_encryption_key_size; 8567 } 8568 #endif 8569 } else { 8570 #ifdef ENABLE_CLASSIC 8571 if ((hci_connection->authentication_flags & AUTH_FLAG_CONNECTION_ENCRYPTED)){ 8572 return hci_connection->encryption_key_size; 8573 } 8574 #endif 8575 } 8576 return 0; 8577 } 8578 8579 bool gap_authenticated(hci_con_handle_t con_handle){ 8580 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8581 if (hci_connection == NULL) return false; 8582 8583 switch (hci_connection->address_type){ 8584 #ifdef ENABLE_BLE 8585 case BD_ADDR_TYPE_LE_PUBLIC: 8586 case BD_ADDR_TYPE_LE_RANDOM: 8587 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated 8588 return hci_connection->sm_connection.sm_connection_authenticated != 0; 8589 #endif 8590 #ifdef ENABLE_CLASSIC 8591 case BD_ADDR_TYPE_SCO: 8592 case BD_ADDR_TYPE_ACL: 8593 return gap_authenticated_for_link_key_type(hci_connection->link_key_type); 8594 #endif 8595 default: 8596 return false; 8597 } 8598 } 8599 8600 bool gap_secure_connection(hci_con_handle_t con_handle){ 8601 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8602 if (hci_connection == NULL) return 0; 8603 8604 switch (hci_connection->address_type){ 8605 #ifdef ENABLE_BLE 8606 case BD_ADDR_TYPE_LE_PUBLIC: 8607 case BD_ADDR_TYPE_LE_RANDOM: 8608 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return false; // unencrypted connection cannot be authenticated 8609 return hci_connection->sm_connection.sm_connection_sc != 0; 8610 #endif 8611 #ifdef ENABLE_CLASSIC 8612 case BD_ADDR_TYPE_SCO: 8613 case BD_ADDR_TYPE_ACL: 8614 return gap_secure_connection_for_link_key_type(hci_connection->link_key_type); 8615 #endif 8616 default: 8617 return false; 8618 } 8619 } 8620 8621 bool gap_bonded(hci_con_handle_t con_handle){ 8622 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 8623 if (hci_connection == NULL) return 0; 8624 8625 #ifdef ENABLE_CLASSIC 8626 link_key_t link_key; 8627 link_key_type_t link_key_type; 8628 #endif 8629 switch (hci_connection->address_type){ 8630 #ifdef ENABLE_BLE 8631 case BD_ADDR_TYPE_LE_PUBLIC: 8632 case BD_ADDR_TYPE_LE_RANDOM: 8633 return hci_connection->sm_connection.sm_le_db_index >= 0; 8634 #endif 8635 #ifdef ENABLE_CLASSIC 8636 case BD_ADDR_TYPE_SCO: 8637 case BD_ADDR_TYPE_ACL: 8638 return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type); 8639 #endif 8640 default: 8641 return false; 8642 } 8643 } 8644 8645 #ifdef ENABLE_BLE 8646 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){ 8647 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 8648 if (!sm_conn) return AUTHORIZATION_UNKNOWN; // wrong connection 8649 if (!sm_conn->sm_connection_encrypted) return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized 8650 if (!sm_conn->sm_connection_authenticated) return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized 8651 return sm_conn->sm_connection_authorization_state; 8652 } 8653 #endif 8654 8655 #ifdef ENABLE_CLASSIC 8656 uint8_t gap_sniff_mode_enter(hci_con_handle_t con_handle, uint16_t sniff_min_interval, uint16_t sniff_max_interval, uint16_t sniff_attempt, uint16_t sniff_timeout){ 8657 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8658 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8659 conn->sniff_min_interval = sniff_min_interval; 8660 conn->sniff_max_interval = sniff_max_interval; 8661 conn->sniff_attempt = sniff_attempt; 8662 conn->sniff_timeout = sniff_timeout; 8663 hci_run(); 8664 return 0; 8665 } 8666 8667 /** 8668 * @brief Exit Sniff mode 8669 * @param con_handle 8670 @ @return 0 if ok 8671 */ 8672 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){ 8673 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8674 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8675 conn->sniff_min_interval = 0xffff; 8676 hci_run(); 8677 return 0; 8678 } 8679 8680 uint8_t gap_sniff_subrating_configure(hci_con_handle_t con_handle, uint16_t max_latency, uint16_t min_remote_timeout, uint16_t min_local_timeout){ 8681 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8682 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8683 conn->sniff_subrating_max_latency = max_latency; 8684 conn->sniff_subrating_min_remote_timeout = min_remote_timeout; 8685 conn->sniff_subrating_min_local_timeout = min_local_timeout; 8686 hci_run(); 8687 return ERROR_CODE_SUCCESS; 8688 } 8689 8690 uint8_t gap_qos_set(hci_con_handle_t con_handle, hci_service_type_t service_type, uint32_t token_rate, uint32_t peak_bandwidth, uint32_t latency, uint32_t delay_variation){ 8691 hci_connection_t * conn = hci_connection_for_handle(con_handle); 8692 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8693 conn->qos_service_type = service_type; 8694 conn->qos_token_rate = token_rate; 8695 conn->qos_peak_bandwidth = peak_bandwidth; 8696 conn->qos_latency = latency; 8697 conn->qos_delay_variation = delay_variation; 8698 hci_run(); 8699 return ERROR_CODE_SUCCESS; 8700 } 8701 8702 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){ 8703 hci_stack->new_page_scan_interval = page_scan_interval; 8704 hci_stack->new_page_scan_window = page_scan_window; 8705 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_ACTIVITY; 8706 hci_run(); 8707 } 8708 8709 void gap_set_page_scan_type(page_scan_type_t page_scan_type){ 8710 hci_stack->new_page_scan_type = (uint8_t) page_scan_type; 8711 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_SCAN_TYPE; 8712 hci_run(); 8713 } 8714 8715 void gap_set_page_timeout(uint16_t page_timeout){ 8716 hci_stack->page_timeout = page_timeout; 8717 hci_stack->gap_tasks_classic |= GAP_TASK_WRITE_PAGE_TIMEOUT; 8718 hci_run(); 8719 } 8720 8721 #endif 8722 8723 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 8724 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){ 8725 if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return; 8726 if (le_device_db_index >= le_device_db_max_count()) return; 8727 uint8_t offset = le_device_db_index >> 3; 8728 uint8_t mask = 1 << (le_device_db_index & 7); 8729 hci_stack->le_resolving_list_add_entries[offset] |= mask; 8730 if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){ 8731 // note: go back to remove entries, otherwise, a remove + add will skip the add 8732 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 8733 } 8734 } 8735 8736 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){ 8737 if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return; 8738 if (le_device_db_index >= le_device_db_max_count()) return; 8739 uint8_t offset = le_device_db_index >> 3; 8740 uint8_t mask = 1 << (le_device_db_index & 7); 8741 hci_stack->le_resolving_list_remove_entries[offset] |= mask; 8742 if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){ 8743 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 8744 } 8745 } 8746 8747 uint8_t gap_load_resolving_list_from_le_device_db(void){ 8748 if (hci_command_supported(SUPPORTED_HCI_COMMAND_LE_SET_ADDRESS_RESOLUTION_ENABLE) == false){ 8749 return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; 8750 } 8751 if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){ 8752 // restart le resolving list update 8753 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE; 8754 } 8755 return ERROR_CODE_SUCCESS; 8756 } 8757 #endif 8758 8759 #ifdef ENABLE_BLE 8760 #ifdef ENABLE_LE_CENTRAL 8761 #ifdef ENABLE_LE_EXTENDED_ADVERTISING 8762 8763 static uint8_t hci_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 8764 // check if already in list 8765 btstack_linked_list_iterator_t it; 8766 btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list); 8767 while (btstack_linked_list_iterator_has_next(&it)) { 8768 periodic_advertiser_list_entry_t *entry = (periodic_advertiser_list_entry_t *) btstack_linked_list_iterator_next(&it); 8769 if (entry->sid != advertising_sid) { 8770 continue; 8771 } 8772 if (entry->address_type != address_type) { 8773 continue; 8774 } 8775 if (memcmp(entry->address, address, 6) != 0) { 8776 continue; 8777 } 8778 // disallow if already scheduled to add 8779 if ((entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER) != 0){ 8780 return ERROR_CODE_COMMAND_DISALLOWED; 8781 } 8782 // still on controller, but scheduled to remove -> re-add 8783 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER; 8784 return ERROR_CODE_SUCCESS; 8785 } 8786 // alloc and add to list 8787 periodic_advertiser_list_entry_t * entry = btstack_memory_periodic_advertiser_list_entry_get(); 8788 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 8789 entry->sid = advertising_sid; 8790 entry->address_type = address_type; 8791 (void)memcpy(entry->address, address, 6); 8792 entry->state = LE_PERIODIC_ADVERTISER_LIST_ENTRY_ADD_TO_CONTROLLER; 8793 btstack_linked_list_add(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t*) entry); 8794 return ERROR_CODE_SUCCESS; 8795 } 8796 8797 static uint8_t hci_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 8798 btstack_linked_list_iterator_t it; 8799 btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list); 8800 while (btstack_linked_list_iterator_has_next(&it)){ 8801 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it); 8802 if (entry->sid != advertising_sid) { 8803 continue; 8804 } 8805 if (entry->address_type != address_type) { 8806 continue; 8807 } 8808 if (memcmp(entry->address, address, 6) != 0) { 8809 continue; 8810 } 8811 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){ 8812 // remove from controller if already present 8813 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER; 8814 } else { 8815 // directly remove entry from whitelist 8816 btstack_linked_list_iterator_remove(&it); 8817 btstack_memory_periodic_advertiser_list_entry_free(entry); 8818 } 8819 return ERROR_CODE_SUCCESS; 8820 } 8821 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 8822 } 8823 8824 static void hci_periodic_advertiser_list_clear(void){ 8825 btstack_linked_list_iterator_t it; 8826 btstack_linked_list_iterator_init(&it, &hci_stack->le_periodic_advertiser_list); 8827 while (btstack_linked_list_iterator_has_next(&it)){ 8828 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&it); 8829 if (entry->state & LE_PERIODIC_ADVERTISER_LIST_ENTRY_ON_CONTROLLER){ 8830 // remove from controller if already present 8831 entry->state |= LE_PERIODIC_ADVERTISER_LIST_ENTRY_REMOVE_FROM_CONTROLLER; 8832 continue; 8833 } 8834 // directly remove entry from whitelist 8835 btstack_linked_list_iterator_remove(&it); 8836 btstack_memory_periodic_advertiser_list_entry_free(entry); 8837 } 8838 } 8839 8840 // free all entries unconditionally 8841 static void hci_periodic_advertiser_list_free(void){ 8842 btstack_linked_list_iterator_t lit; 8843 btstack_linked_list_iterator_init(&lit, &hci_stack->le_periodic_advertiser_list); 8844 while (btstack_linked_list_iterator_has_next(&lit)){ 8845 periodic_advertiser_list_entry_t * entry = (periodic_advertiser_list_entry_t*) btstack_linked_list_iterator_next(&lit); 8846 btstack_linked_list_remove(&hci_stack->le_periodic_advertiser_list, (btstack_linked_item_t *) entry); 8847 btstack_memory_periodic_advertiser_list_entry_free(entry); 8848 } 8849 } 8850 8851 uint8_t gap_periodic_advertiser_list_clear(void){ 8852 hci_periodic_advertiser_list_clear(); 8853 hci_run(); 8854 return ERROR_CODE_SUCCESS; 8855 } 8856 8857 uint8_t gap_periodic_advertiser_list_add(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 8858 uint8_t status = hci_periodic_advertiser_list_add(address_type, address, advertising_sid); 8859 if (status){ 8860 return status; 8861 } 8862 hci_run(); 8863 return ERROR_CODE_SUCCESS; 8864 } 8865 8866 uint8_t gap_periodic_advertiser_list_remove(bd_addr_type_t address_type, const bd_addr_t address, uint8_t advertising_sid){ 8867 uint8_t status = hci_periodic_advertiser_list_remove(address_type, address, advertising_sid); 8868 if (status){ 8869 return status; 8870 } 8871 hci_run(); 8872 return ERROR_CODE_SUCCESS; 8873 } 8874 8875 uint8_t gap_periodic_advertising_create_sync(uint8_t options, uint8_t advertising_sid, bd_addr_type_t advertiser_address_type, 8876 bd_addr_t advertiser_address, uint16_t skip, uint16_t sync_timeout, uint8_t sync_cte_type){ 8877 // abort if already active 8878 if (hci_stack->le_periodic_sync_request != LE_CONNECTING_IDLE) { 8879 return ERROR_CODE_COMMAND_DISALLOWED; 8880 } 8881 // store request 8882 hci_stack->le_periodic_sync_request = ((options & 0) != 0) ? LE_CONNECTING_WHITELIST : LE_CONNECTING_DIRECT; 8883 hci_stack->le_periodic_sync_options = options; 8884 hci_stack->le_periodic_sync_advertising_sid = advertising_sid; 8885 hci_stack->le_periodic_sync_advertiser_address_type = advertiser_address_type; 8886 memcpy(hci_stack->le_periodic_sync_advertiser_address, advertiser_address, 6); 8887 hci_stack->le_periodic_sync_skip = skip; 8888 hci_stack->le_periodic_sync_timeout = sync_timeout; 8889 hci_stack->le_periodic_sync_cte_type = sync_cte_type; 8890 8891 hci_run(); 8892 return ERROR_CODE_SUCCESS; 8893 } 8894 8895 uint8_t gap_periodic_advertising_create_sync_cancel(void){ 8896 // abort if not requested 8897 if (hci_stack->le_periodic_sync_request == LE_CONNECTING_IDLE) { 8898 return ERROR_CODE_COMMAND_DISALLOWED; 8899 } 8900 hci_stack->le_periodic_sync_request = LE_CONNECTING_IDLE; 8901 hci_run(); 8902 return ERROR_CODE_SUCCESS; 8903 } 8904 8905 uint8_t gap_periodic_advertising_terminate_sync(uint16_t sync_handle){ 8906 if (hci_stack->le_periodic_terminate_sync_handle != HCI_CON_HANDLE_INVALID){ 8907 return ERROR_CODE_COMMAND_DISALLOWED; 8908 } 8909 hci_stack->le_periodic_terminate_sync_handle = sync_handle; 8910 hci_run(); 8911 return ERROR_CODE_SUCCESS; 8912 } 8913 8914 #endif 8915 #endif 8916 #ifdef ENABLE_LE_ISOCHRONOUS_STREAMS 8917 static uint8_t hci_iso_stream_create(hci_con_handle_t con_handle, uint8_t big_handle) { 8918 hci_iso_stream_t * iso_stream = btstack_memory_hci_iso_stream_get(); 8919 if (iso_stream == NULL){ 8920 return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED; 8921 } else { 8922 iso_stream->state = HCI_ISO_STREAM_STATE_REQUESTED; 8923 iso_stream->con_handle = con_handle; 8924 iso_stream->big_handle = big_handle; 8925 btstack_linked_list_add(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream); 8926 return ERROR_CODE_SUCCESS; 8927 } 8928 } 8929 8930 static hci_iso_stream_t * hci_iso_stream_for_con_handle(hci_con_handle_t con_handle){ 8931 btstack_linked_list_iterator_t it; 8932 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 8933 while (btstack_linked_list_iterator_has_next(&it)){ 8934 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 8935 if (iso_stream->con_handle == con_handle ) { 8936 return iso_stream; 8937 } 8938 } 8939 return NULL; 8940 } 8941 8942 static void hci_iso_stream_finalize(hci_iso_stream_t * iso_stream){ 8943 log_info("hci_iso_stream_finalize con_handle 0x%04x, big_handle 0x%02x", iso_stream->con_handle, iso_stream->big_handle); 8944 btstack_linked_list_remove(&hci_stack->iso_streams, (btstack_linked_item_t*) iso_stream); 8945 btstack_memory_hci_iso_stream_free(iso_stream); 8946 } 8947 8948 static void hci_iso_stream_requested_finalize(uint8_t big_handle) { 8949 btstack_linked_list_iterator_t it; 8950 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 8951 while (btstack_linked_list_iterator_has_next(&it)){ 8952 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 8953 if ((iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) && 8954 (iso_stream->big_handle == big_handle)){ 8955 btstack_linked_list_iterator_remove(&it); 8956 btstack_memory_hci_iso_stream_free(iso_stream); 8957 } 8958 } 8959 } 8960 static void hci_iso_stream_requested_confirm(uint8_t big_handle){ 8961 btstack_linked_list_iterator_t it; 8962 btstack_linked_list_iterator_init(&it, &hci_stack->iso_streams); 8963 while (btstack_linked_list_iterator_has_next(&it)){ 8964 hci_iso_stream_t * iso_stream = (hci_iso_stream_t *) btstack_linked_list_iterator_next(&it); 8965 if ( iso_stream->state == HCI_ISO_STREAM_STATE_REQUESTED ) { 8966 iso_stream->state = HCI_ISO_STREAM_STATE_W4_ESTABLISHED; 8967 } 8968 } 8969 } 8970 8971 static bool hci_iso_sdu_complete(uint8_t * packet, uint16_t size){ 8972 uint8_t sdu_ts_flag = (packet[1] >> 6) & 1; 8973 uint16_t sdu_len_offset = 6 + (sdu_ts_flag * 4); 8974 uint16_t sdu_len = little_endian_read_16(packet, sdu_len_offset) & 0x0fff; 8975 return (sdu_len_offset + 2 + sdu_len) == size; 8976 } 8977 8978 static void hci_iso_packet_handler(uint8_t * packet, uint16_t size){ 8979 if (hci_stack->iso_packet_handler == NULL) { 8980 return; 8981 } 8982 if (size < 4) { 8983 return; 8984 } 8985 8986 // parse header 8987 uint16_t conn_handle_and_flags = little_endian_read_16(packet, 0); 8988 uint16_t iso_data_len = little_endian_read_16(packet, 2); 8989 hci_con_handle_t cis_handle = (hci_con_handle_t) (conn_handle_and_flags & 0xfff); 8990 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(cis_handle); 8991 uint8_t pb_flag = (conn_handle_and_flags >> 12) & 3; 8992 8993 // assert packet is complete 8994 if ((iso_data_len + 4u) != size){ 8995 return; 8996 } 8997 8998 if ((pb_flag & 0x01) == 0){ 8999 if (pb_flag == 0x02){ 9000 // The ISO_Data_Load field contains a header and a complete SDU. 9001 if (hci_iso_sdu_complete(packet, size)) { 9002 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, packet, size); 9003 } 9004 } else { 9005 // The ISO_Data_Load field contains a header and the first fragment of a fragmented SDU. 9006 if (iso_stream == NULL){ 9007 return; 9008 } 9009 if (size > HCI_ISO_PAYLOAD_SIZE){ 9010 return; 9011 } 9012 memcpy(iso_stream->reassembly_buffer, packet, size); 9013 // fix pb_flag 9014 iso_stream->reassembly_buffer[1] = (iso_stream->reassembly_buffer[1] & 0xcf) | 0x20; 9015 iso_stream->reassembly_pos = size; 9016 } 9017 } else { 9018 // iso_data_load contains continuation or last fragment of an SDU 9019 uint8_t ts_flag = (conn_handle_and_flags >> 14) & 1; 9020 if (ts_flag != 0){ 9021 return; 9022 } 9023 // append fragment 9024 if (iso_stream == NULL){ 9025 return; 9026 } 9027 if (iso_stream->reassembly_pos == 0){ 9028 return; 9029 } 9030 if ((iso_stream->reassembly_pos + iso_data_len) > size){ 9031 // reset reassembly buffer 9032 iso_stream->reassembly_pos = 0; 9033 return; 9034 } 9035 memcpy(&iso_stream->reassembly_buffer[iso_stream->reassembly_pos], &packet[4], iso_data_len); 9036 iso_stream->reassembly_pos += iso_data_len; 9037 9038 // deliver if last fragment and SDU complete 9039 if (pb_flag == 0x03){ 9040 if (hci_iso_sdu_complete(iso_stream->reassembly_buffer, iso_stream->reassembly_pos)){ 9041 (hci_stack->iso_packet_handler)(HCI_ISO_DATA_PACKET, 0, iso_stream->reassembly_buffer, iso_stream->reassembly_pos); 9042 } 9043 iso_stream->reassembly_pos = 0; 9044 } 9045 } 9046 } 9047 9048 static void hci_emit_big_created(const le_audio_big_t * big, uint8_t status){ 9049 uint8_t event [6 + (MAX_NR_BIS * 2)]; 9050 uint16_t pos = 0; 9051 event[pos++] = HCI_EVENT_META_GAP; 9052 event[pos++] = 4 + (2 * big->num_bis); 9053 event[pos++] = GAP_SUBEVENT_BIG_CREATED; 9054 event[pos++] = status; 9055 event[pos++] = big->big_handle; 9056 event[pos++] = big->num_bis; 9057 uint8_t i; 9058 for (i=0;i<big->num_bis;i++){ 9059 little_endian_store_16(event, pos, big->bis_con_handles[i]); 9060 pos += 2; 9061 } 9062 hci_emit_event(event, pos, 0); 9063 } 9064 9065 static void hci_emit_big_terminated(const le_audio_big_t * big){ 9066 uint8_t event [4]; 9067 uint16_t pos = 0; 9068 event[pos++] = HCI_EVENT_META_GAP; 9069 event[pos++] = 2; 9070 event[pos++] = GAP_SUBEVENT_BIG_TERMINATED; 9071 event[pos++] = big->big_handle; 9072 hci_emit_event(event, pos, 0); 9073 } 9074 9075 static void hci_emit_big_sync_created(const le_audio_big_sync_t * big_sync, uint8_t status){ 9076 uint8_t event [6 + (MAX_NR_BIS * 2)]; 9077 uint16_t pos = 0; 9078 event[pos++] = HCI_EVENT_META_GAP; 9079 event[pos++] = 4; 9080 event[pos++] = GAP_SUBEVENT_BIG_SYNC_CREATED; 9081 event[pos++] = status; 9082 event[pos++] = big_sync->big_handle; 9083 event[pos++] = big_sync->num_bis; 9084 uint8_t i; 9085 for (i=0;i<big_sync->num_bis;i++){ 9086 little_endian_store_16(event, pos, big_sync->bis_con_handles[i]); 9087 pos += 2; 9088 } 9089 hci_emit_event(event, pos, 0); 9090 } 9091 9092 static void hci_emit_big_sync_stopped(uint8_t big_handle){ 9093 uint8_t event [4]; 9094 uint16_t pos = 0; 9095 event[pos++] = HCI_EVENT_META_GAP; 9096 event[pos++] = 2; 9097 event[pos++] = GAP_SUBEVENT_BIG_SYNC_STOPPED; 9098 event[pos++] = big_handle; 9099 hci_emit_event(event, pos, 0); 9100 } 9101 9102 static void hci_emit_bis_can_send_now(const le_audio_big_t *big, uint8_t bis_index) { 9103 uint8_t event[6]; 9104 uint16_t pos = 0; 9105 event[pos++] = HCI_EVENT_BIS_CAN_SEND_NOW; 9106 event[pos++] = sizeof(event) - 2; 9107 event[pos++] = big->big_handle; 9108 event[pos++] = bis_index; 9109 little_endian_store_16(event, pos, big->bis_con_handles[bis_index]); 9110 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 9111 } 9112 9113 static le_audio_big_t * hci_big_for_handle(uint8_t big_handle){ 9114 btstack_linked_list_iterator_t it; 9115 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 9116 while (btstack_linked_list_iterator_has_next(&it)){ 9117 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 9118 if ( big->big_handle == big_handle ) { 9119 return big; 9120 } 9121 } 9122 return NULL; 9123 } 9124 9125 static le_audio_big_sync_t * hci_big_sync_for_handle(uint8_t big_handle){ 9126 btstack_linked_list_iterator_t it; 9127 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_big_syncs); 9128 while (btstack_linked_list_iterator_has_next(&it)){ 9129 le_audio_big_sync_t * big_sync = (le_audio_big_sync_t *) btstack_linked_list_iterator_next(&it); 9130 if ( big_sync->big_handle == big_handle ) { 9131 return big_sync; 9132 } 9133 } 9134 return NULL; 9135 } 9136 9137 void hci_set_num_iso_packets_to_queue(uint8_t num_packets){ 9138 hci_stack->iso_packets_to_queue = num_packets; 9139 } 9140 9141 static void hci_iso_notify_can_send_now(void){ 9142 btstack_linked_list_iterator_t it; 9143 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 9144 while (btstack_linked_list_iterator_has_next(&it)){ 9145 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 9146 // track number completed packet timestamps 9147 if (big->num_completed_timestamp_current_valid){ 9148 big->num_completed_timestamp_current_valid = false; 9149 if (big->num_completed_timestamp_previous_valid){ 9150 // detect delayed sending of all BIS: tolerate up to 50% delayed event handling 9151 uint32_t iso_interval_missed_threshold_ms = big->params->sdu_interval_us * 3 / 2000; 9152 int32_t num_completed_timestamp_delta_ms = btstack_time_delta(big->num_completed_timestamp_current_ms, 9153 big->num_completed_timestamp_previous_ms); 9154 if (num_completed_timestamp_delta_ms > iso_interval_missed_threshold_ms){ 9155 // to catch up, skip packet on all BIS 9156 uint8_t i; 9157 for (i=0;i<big->num_bis;i++){ 9158 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9159 if (iso_stream){ 9160 iso_stream->num_packets_to_skip++; 9161 } 9162 } 9163 } 9164 } 9165 big->num_completed_timestamp_previous_valid = true; 9166 big->num_completed_timestamp_previous_ms = big->num_completed_timestamp_current_ms; 9167 } 9168 9169 if (big->can_send_now_requested){ 9170 // check if no outgoing iso packets pending and no can send now have to be emitted 9171 uint8_t i; 9172 bool can_send = true; 9173 uint8_t num_iso_queued_minimum = 0; 9174 for (i=0;i<big->num_bis;i++){ 9175 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9176 if (iso_stream == NULL) continue; 9177 // handle case where individual ISO packet was sent too late: 9178 // for each additionally queued packet, a new one needs to get skipped 9179 if (i==0){ 9180 num_iso_queued_minimum = iso_stream->num_packets_sent; 9181 } else if (iso_stream->num_packets_sent > num_iso_queued_minimum){ 9182 uint8_t num_packets_to_skip = iso_stream->num_packets_sent - num_iso_queued_minimum; 9183 iso_stream->num_packets_to_skip += num_packets_to_skip; 9184 iso_stream->num_packets_sent -= num_packets_to_skip; 9185 } 9186 // check if we can send now 9187 if ((iso_stream->num_packets_sent >= hci_stack->iso_packets_to_queue) || (iso_stream->emit_ready_to_send)){ 9188 can_send = false; 9189 break; 9190 } 9191 } 9192 if (can_send){ 9193 // propagate can send now to individual streams 9194 big->can_send_now_requested = false; 9195 for (i=0;i<big->num_bis;i++){ 9196 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9197 iso_stream->emit_ready_to_send = true; 9198 } 9199 } 9200 } 9201 } 9202 9203 if (hci_stack->hci_packet_buffer_reserved) return; 9204 9205 btstack_linked_list_iterator_init(&it, &hci_stack->le_audio_bigs); 9206 while (btstack_linked_list_iterator_has_next(&it)){ 9207 le_audio_big_t * big = (le_audio_big_t *) btstack_linked_list_iterator_next(&it); 9208 // report bis ready 9209 uint8_t i; 9210 for (i=0;i<big->num_bis;i++){ 9211 hci_iso_stream_t * iso_stream = hci_iso_stream_for_con_handle(big->bis_con_handles[i]); 9212 if ((iso_stream != NULL) && iso_stream->emit_ready_to_send){ 9213 iso_stream->emit_ready_to_send = false; 9214 hci_emit_bis_can_send_now(big, i); 9215 break; 9216 } 9217 } 9218 } 9219 } 9220 9221 uint8_t gap_big_create(le_audio_big_t * storage, le_audio_big_params_t * big_params){ 9222 if (hci_big_for_handle(big_params->big_handle) != NULL){ 9223 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 9224 } 9225 if (big_params->num_bis == 0){ 9226 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9227 } 9228 if (big_params->num_bis > MAX_NR_BIS){ 9229 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9230 } 9231 9232 // reserve ISO Streams 9233 uint8_t i; 9234 uint8_t status = ERROR_CODE_SUCCESS; 9235 for (i=0;i<big_params->num_bis;i++){ 9236 status = hci_iso_stream_create(HCI_CON_HANDLE_INVALID, big_params->big_handle); 9237 if (status != ERROR_CODE_SUCCESS) { 9238 break; 9239 } 9240 } 9241 9242 // free structs on error 9243 if (status != ERROR_CODE_SUCCESS){ 9244 hci_iso_stream_requested_finalize(big_params->big_handle); 9245 return status; 9246 } 9247 9248 le_audio_big_t * big = storage; 9249 big->big_handle = big_params->big_handle; 9250 big->params = big_params; 9251 big->state = LE_AUDIO_BIG_STATE_CREATE; 9252 big->num_bis = big_params->num_bis; 9253 btstack_linked_list_add(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 9254 9255 hci_run(); 9256 9257 return ERROR_CODE_SUCCESS; 9258 } 9259 9260 uint8_t gap_big_sync_create(le_audio_big_sync_t * storage, le_audio_big_sync_params_t * big_sync_params){ 9261 if (hci_big_sync_for_handle(big_sync_params->big_handle) != NULL){ 9262 return ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS; 9263 } 9264 if (big_sync_params->num_bis == 0){ 9265 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9266 } 9267 if (big_sync_params->num_bis > MAX_NR_BIS){ 9268 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 9269 } 9270 9271 le_audio_big_sync_t * big_sync = storage; 9272 big_sync->big_handle = big_sync_params->big_handle; 9273 big_sync->params = big_sync_params; 9274 big_sync->state = LE_AUDIO_BIG_STATE_CREATE; 9275 big_sync->num_bis = big_sync_params->num_bis; 9276 btstack_linked_list_add(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 9277 9278 hci_run(); 9279 9280 return ERROR_CODE_SUCCESS; 9281 } 9282 9283 uint8_t gap_big_terminate(uint8_t big_handle){ 9284 le_audio_big_t * big = hci_big_for_handle(big_handle); 9285 if (big == NULL){ 9286 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9287 } 9288 switch (big->state){ 9289 case LE_AUDIO_BIG_STATE_CREATE: 9290 btstack_linked_list_remove(&hci_stack->le_audio_bigs, (btstack_linked_item_t *) big); 9291 hci_emit_big_terminated(big); 9292 break; 9293 case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH: 9294 big->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE; 9295 break; 9296 case LE_AUDIO_BIG_STATE_W4_ESTABLISHED: 9297 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 9298 case LE_AUDIO_BIG_STATE_ACTIVE: 9299 big->state = LE_AUDIO_BIG_STATE_TERMINATE; 9300 hci_run(); 9301 break; 9302 default: 9303 return ERROR_CODE_COMMAND_DISALLOWED; 9304 } 9305 return ERROR_CODE_SUCCESS; 9306 } 9307 9308 uint8_t gap_big_sync_terminate(uint8_t big_handle){ 9309 le_audio_big_sync_t * big_sync = hci_big_sync_for_handle(big_handle); 9310 if (big_sync == NULL){ 9311 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9312 } 9313 switch (big_sync->state){ 9314 case LE_AUDIO_BIG_STATE_CREATE: 9315 btstack_linked_list_remove(&hci_stack->le_audio_big_syncs, (btstack_linked_item_t *) big_sync); 9316 hci_emit_big_sync_stopped(big_handle); 9317 break; 9318 case LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH: 9319 big_sync->state = LE_AUDIO_BIG_STATE_W4_SETUP_ISO_PATH_THEN_TERMINATE; 9320 break; 9321 case LE_AUDIO_BIG_STATE_W4_ESTABLISHED: 9322 case LE_AUDIO_BIG_STATE_SETUP_ISO_PATH: 9323 case LE_AUDIO_BIG_STATE_ACTIVE: 9324 big_sync->state = LE_AUDIO_BIG_STATE_TERMINATE; 9325 hci_run(); 9326 break; 9327 default: 9328 return ERROR_CODE_COMMAND_DISALLOWED; 9329 } 9330 return ERROR_CODE_SUCCESS; 9331 } 9332 9333 uint8_t hci_request_bis_can_send_now_events(uint8_t big_handle){ 9334 le_audio_big_t * big = hci_big_for_handle(big_handle); 9335 if (big == NULL){ 9336 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 9337 } 9338 if (big->state != LE_AUDIO_BIG_STATE_ACTIVE){ 9339 return ERROR_CODE_COMMAND_DISALLOWED; 9340 } 9341 big->can_send_now_requested = true; 9342 hci_iso_notify_can_send_now(); 9343 return ERROR_CODE_SUCCESS; 9344 } 9345 #endif 9346 #endif /* ENABLE_BLE */ 9347 9348 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION 9349 void hci_setup_test_connections_fuzz(void){ 9350 hci_connection_t * conn; 9351 9352 // default address: 66:55:44:33:00:01 9353 bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00}; 9354 9355 // setup Controller info 9356 hci_stack->num_cmd_packets = 255; 9357 hci_stack->acl_packets_total_num = 255; 9358 9359 // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01 9360 addr[5] = 0x01; 9361 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 9362 conn->con_handle = addr[5]; 9363 conn->role = HCI_ROLE_SLAVE; 9364 conn->state = RECEIVED_CONNECTION_REQUEST; 9365 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9366 9367 // setup incoming Classic SCO connection with con handle 0x0002 9368 addr[5] = 0x02; 9369 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 9370 conn->con_handle = addr[5]; 9371 conn->role = HCI_ROLE_SLAVE; 9372 conn->state = RECEIVED_CONNECTION_REQUEST; 9373 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9374 9375 // setup ready Classic ACL connection with con handle 0x0003 9376 addr[5] = 0x03; 9377 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 9378 conn->con_handle = addr[5]; 9379 conn->role = HCI_ROLE_SLAVE; 9380 conn->state = OPEN; 9381 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9382 9383 // setup ready Classic SCO connection with con handle 0x0004 9384 addr[5] = 0x04; 9385 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 9386 conn->con_handle = addr[5]; 9387 conn->role = HCI_ROLE_SLAVE; 9388 conn->state = OPEN; 9389 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9390 9391 // setup ready LE ACL connection with con handle 0x005 and public address 9392 addr[5] = 0x05; 9393 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC); 9394 conn->con_handle = addr[5]; 9395 conn->role = HCI_ROLE_SLAVE; 9396 conn->state = OPEN; 9397 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 9398 conn->sm_connection.sm_connection_encrypted = 1; 9399 } 9400 9401 void hci_free_connections_fuzz(void){ 9402 btstack_linked_list_iterator_t it; 9403 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 9404 while (btstack_linked_list_iterator_has_next(&it)){ 9405 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 9406 btstack_linked_list_iterator_remove(&it); 9407 btstack_memory_hci_connection_free(con); 9408 } 9409 } 9410 void hci_simulate_working_fuzz(void){ 9411 hci_stack->le_scanning_param_update = false; 9412 hci_init_done(); 9413 hci_stack->num_cmd_packets = 255; 9414 } 9415 #endif 9416