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