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