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