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