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