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