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