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