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 uint8_t auth_req_ignoring_mitm = conn->io_cap_response_auth_req & 0xfe; 2686 if (auth_req_ignoring_mitm == SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_NO_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 void gap_set_security_mode(gap_security_mode_t security_mode){ 3416 btstack_assert((security_mode == GAP_SECURITY_MODE_4) || (security_mode == GAP_SECURITY_MODE_2)); 3417 hci_stack->gap_security_mode = security_mode; 3418 } 3419 3420 gap_security_mode_t gap_get_security_mode(void){ 3421 return hci_stack->gap_security_mode; 3422 } 3423 3424 void gap_set_security_level(gap_security_level_t security_level){ 3425 hci_stack->gap_security_level = security_level; 3426 } 3427 3428 gap_security_level_t gap_get_security_level(void){ 3429 return hci_stack->gap_security_level; 3430 } 3431 3432 void gap_set_secure_connections_only_mode(bool enable){ 3433 hci_stack->gap_secure_connections_only_mode = enable; 3434 } 3435 3436 bool gap_get_secure_connections_only_mode(void){ 3437 return hci_stack->gap_secure_connections_only_mode; 3438 } 3439 #endif 3440 3441 #ifdef ENABLE_CLASSIC 3442 void gap_set_class_of_device(uint32_t class_of_device){ 3443 hci_stack->class_of_device = class_of_device; 3444 } 3445 3446 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){ 3447 hci_stack->default_link_policy_settings = default_link_policy_settings; 3448 } 3449 3450 void gap_set_allow_role_switch(bool allow_role_switch){ 3451 hci_stack->allow_role_switch = allow_role_switch ? 1 : 0; 3452 } 3453 3454 uint8_t hci_get_allow_role_switch(void){ 3455 return hci_stack->allow_role_switch; 3456 } 3457 3458 void gap_set_link_supervision_timeout(uint16_t link_supervision_timeout){ 3459 hci_stack->link_supervision_timeout = link_supervision_timeout; 3460 } 3461 3462 void hci_disable_l2cap_timeout_check(void){ 3463 disable_l2cap_timeouts = 1; 3464 } 3465 #endif 3466 3467 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API) 3468 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h 3469 void hci_set_bd_addr(bd_addr_t addr){ 3470 (void)memcpy(hci_stack->custom_bd_addr, addr, 6); 3471 hci_stack->custom_bd_addr_set = 1; 3472 } 3473 #endif 3474 3475 // State-Module-Driver overview 3476 // state module low-level 3477 // HCI_STATE_OFF off close 3478 // HCI_STATE_INITIALIZING, on open 3479 // HCI_STATE_WORKING, on open 3480 // HCI_STATE_HALTING, on open 3481 // HCI_STATE_SLEEPING, off/sleep close 3482 // HCI_STATE_FALLING_ASLEEP on open 3483 3484 static int hci_power_control_on(void){ 3485 3486 // power on 3487 int err = 0; 3488 if (hci_stack->control && hci_stack->control->on){ 3489 err = (*hci_stack->control->on)(); 3490 } 3491 if (err){ 3492 log_error( "POWER_ON failed"); 3493 hci_emit_hci_open_failed(); 3494 return err; 3495 } 3496 3497 // int chipset driver 3498 if (hci_stack->chipset && hci_stack->chipset->init){ 3499 hci_stack->chipset->init(hci_stack->config); 3500 } 3501 3502 // init transport 3503 if (hci_stack->hci_transport->init){ 3504 hci_stack->hci_transport->init(hci_stack->config); 3505 } 3506 3507 // open transport 3508 err = hci_stack->hci_transport->open(); 3509 if (err){ 3510 log_error( "HCI_INIT failed, turning Bluetooth off again"); 3511 if (hci_stack->control && hci_stack->control->off){ 3512 (*hci_stack->control->off)(); 3513 } 3514 hci_emit_hci_open_failed(); 3515 return err; 3516 } 3517 return 0; 3518 } 3519 3520 static void hci_power_control_off(void){ 3521 3522 log_info("hci_power_control_off"); 3523 3524 // close low-level device 3525 hci_stack->hci_transport->close(); 3526 3527 log_info("hci_power_control_off - hci_transport closed"); 3528 3529 // power off 3530 if (hci_stack->control && hci_stack->control->off){ 3531 (*hci_stack->control->off)(); 3532 } 3533 3534 log_info("hci_power_control_off - control closed"); 3535 3536 hci_stack->state = HCI_STATE_OFF; 3537 } 3538 3539 static void hci_power_control_sleep(void){ 3540 3541 log_info("hci_power_control_sleep"); 3542 3543 #if 0 3544 // don't close serial port during sleep 3545 3546 // close low-level device 3547 hci_stack->hci_transport->close(hci_stack->config); 3548 #endif 3549 3550 // sleep mode 3551 if (hci_stack->control && hci_stack->control->sleep){ 3552 (*hci_stack->control->sleep)(); 3553 } 3554 3555 hci_stack->state = HCI_STATE_SLEEPING; 3556 } 3557 3558 static int hci_power_control_wake(void){ 3559 3560 log_info("hci_power_control_wake"); 3561 3562 // wake on 3563 if (hci_stack->control && hci_stack->control->wake){ 3564 (*hci_stack->control->wake)(); 3565 } 3566 3567 #if 0 3568 // open low-level device 3569 int err = hci_stack->hci_transport->open(hci_stack->config); 3570 if (err){ 3571 log_error( "HCI_INIT failed, turning Bluetooth off again"); 3572 if (hci_stack->control && hci_stack->control->off){ 3573 (*hci_stack->control->off)(); 3574 } 3575 hci_emit_hci_open_failed(); 3576 return err; 3577 } 3578 #endif 3579 3580 return 0; 3581 } 3582 3583 static void hci_power_transition_to_initializing(void){ 3584 // set up state machine 3585 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 3586 hci_stack->hci_packet_buffer_reserved = 0; 3587 hci_stack->state = HCI_STATE_INITIALIZING; 3588 hci_stack->substate = HCI_INIT_SEND_RESET; 3589 } 3590 3591 // returns error 3592 static int hci_power_control_state_off(HCI_POWER_MODE power_mode){ 3593 int err; 3594 switch (power_mode){ 3595 case HCI_POWER_ON: 3596 err = hci_power_control_on(); 3597 if (err != 0) { 3598 log_error("hci_power_control_on() error %d", err); 3599 return err; 3600 } 3601 hci_power_transition_to_initializing(); 3602 break; 3603 case HCI_POWER_OFF: 3604 // do nothing 3605 break; 3606 case HCI_POWER_SLEEP: 3607 // do nothing (with SLEEP == OFF) 3608 break; 3609 default: 3610 btstack_assert(false); 3611 break; 3612 } 3613 return ERROR_CODE_SUCCESS; 3614 } 3615 3616 static int hci_power_control_state_initializing(HCI_POWER_MODE power_mode){ 3617 switch (power_mode){ 3618 case HCI_POWER_ON: 3619 // do nothing 3620 break; 3621 case HCI_POWER_OFF: 3622 // no connections yet, just turn it off 3623 hci_power_control_off(); 3624 break; 3625 case HCI_POWER_SLEEP: 3626 // no connections yet, just turn it off 3627 hci_power_control_sleep(); 3628 break; 3629 default: 3630 btstack_assert(false); 3631 break; 3632 } 3633 return ERROR_CODE_SUCCESS; 3634 } 3635 3636 static int hci_power_control_state_working(HCI_POWER_MODE power_mode) { 3637 switch (power_mode){ 3638 case HCI_POWER_ON: 3639 // do nothing 3640 break; 3641 case HCI_POWER_OFF: 3642 // see hci_run 3643 hci_stack->state = HCI_STATE_HALTING; 3644 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER; 3645 break; 3646 case HCI_POWER_SLEEP: 3647 // see hci_run 3648 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 3649 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 3650 break; 3651 default: 3652 btstack_assert(false); 3653 break; 3654 } 3655 return ERROR_CODE_SUCCESS; 3656 } 3657 3658 static int hci_power_control_state_halting(HCI_POWER_MODE power_mode) { 3659 switch (power_mode){ 3660 case HCI_POWER_ON: 3661 hci_power_transition_to_initializing(); 3662 break; 3663 case HCI_POWER_OFF: 3664 // do nothing 3665 break; 3666 case HCI_POWER_SLEEP: 3667 // see hci_run 3668 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 3669 hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT; 3670 break; 3671 default: 3672 btstack_assert(false); 3673 break; 3674 } 3675 return ERROR_CODE_SUCCESS; 3676 } 3677 3678 static int hci_power_control_state_falling_asleep(HCI_POWER_MODE power_mode) { 3679 switch (power_mode){ 3680 case HCI_POWER_ON: 3681 3682 #ifdef HAVE_PLATFORM_IPHONE_OS 3683 // nothing to do, if H4 supports power management 3684 if (btstack_control_iphone_power_management_enabled()){ 3685 hci_stack->state = HCI_STATE_INITIALIZING; 3686 hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE; // init after sleep 3687 break; 3688 } 3689 #endif 3690 hci_power_transition_to_initializing(); 3691 break; 3692 case HCI_POWER_OFF: 3693 // see hci_run 3694 hci_stack->state = HCI_STATE_HALTING; 3695 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER; 3696 break; 3697 case HCI_POWER_SLEEP: 3698 // do nothing 3699 break; 3700 default: 3701 btstack_assert(false); 3702 break; 3703 } 3704 return ERROR_CODE_SUCCESS; 3705 } 3706 3707 static int hci_power_control_state_sleeping(HCI_POWER_MODE power_mode) { 3708 int err; 3709 switch (power_mode){ 3710 case HCI_POWER_ON: 3711 #ifdef HAVE_PLATFORM_IPHONE_OS 3712 // nothing to do, if H4 supports power management 3713 if (btstack_control_iphone_power_management_enabled()){ 3714 hci_stack->state = HCI_STATE_INITIALIZING; 3715 hci_stack->substate = HCI_INIT_AFTER_SLEEP; 3716 hci_update_scan_enable(); 3717 break; 3718 } 3719 #endif 3720 err = hci_power_control_wake(); 3721 if (err) return err; 3722 hci_power_transition_to_initializing(); 3723 break; 3724 case HCI_POWER_OFF: 3725 hci_stack->state = HCI_STATE_HALTING; 3726 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER; 3727 break; 3728 case HCI_POWER_SLEEP: 3729 // do nothing 3730 break; 3731 default: 3732 btstack_assert(false); 3733 break; 3734 } 3735 return ERROR_CODE_SUCCESS; 3736 } 3737 3738 int hci_power_control(HCI_POWER_MODE power_mode){ 3739 log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state); 3740 int err = 0; 3741 switch (hci_stack->state){ 3742 case HCI_STATE_OFF: 3743 err = hci_power_control_state_off(power_mode); 3744 break; 3745 case HCI_STATE_INITIALIZING: 3746 err = hci_power_control_state_initializing(power_mode); 3747 break; 3748 case HCI_STATE_WORKING: 3749 err = hci_power_control_state_working(power_mode); 3750 break; 3751 case HCI_STATE_HALTING: 3752 err = hci_power_control_state_halting(power_mode); 3753 break; 3754 case HCI_STATE_FALLING_ASLEEP: 3755 err = hci_power_control_state_falling_asleep(power_mode); 3756 break; 3757 case HCI_STATE_SLEEPING: 3758 err = hci_power_control_state_sleeping(power_mode); 3759 break; 3760 default: 3761 btstack_assert(false); 3762 break; 3763 } 3764 if (err != 0){ 3765 return err; 3766 } 3767 3768 // create internal event 3769 hci_emit_state(); 3770 3771 // trigger next/first action 3772 hci_run(); 3773 3774 return 0; 3775 } 3776 3777 3778 #ifdef ENABLE_CLASSIC 3779 3780 static void hci_update_scan_enable(void){ 3781 // 2 = page scan, 1 = inq scan 3782 hci_stack->new_scan_enable_value = (hci_stack->connectable << 1) | hci_stack->discoverable; 3783 hci_run(); 3784 } 3785 3786 void gap_discoverable_control(uint8_t enable){ 3787 if (enable) enable = 1; // normalize argument 3788 3789 if (hci_stack->discoverable == enable){ 3790 hci_emit_discoverable_enabled(hci_stack->discoverable); 3791 return; 3792 } 3793 3794 hci_stack->discoverable = enable; 3795 hci_update_scan_enable(); 3796 } 3797 3798 void gap_connectable_control(uint8_t enable){ 3799 if (enable) enable = 1; // normalize argument 3800 3801 // don't emit event 3802 if (hci_stack->connectable == enable) return; 3803 3804 hci_stack->connectable = enable; 3805 hci_update_scan_enable(); 3806 } 3807 #endif 3808 3809 void gap_local_bd_addr(bd_addr_t address_buffer){ 3810 (void)memcpy(address_buffer, hci_stack->local_bd_addr, 6); 3811 } 3812 3813 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 3814 static void hci_host_num_completed_packets(void){ 3815 3816 // create packet manually as arrays are not supported and num_commands should not get reduced 3817 hci_reserve_packet_buffer(); 3818 uint8_t * packet = hci_get_outgoing_packet_buffer(); 3819 3820 uint16_t size = 0; 3821 uint16_t num_handles = 0; 3822 packet[size++] = 0x35; 3823 packet[size++] = 0x0c; 3824 size++; // skip param len 3825 size++; // skip num handles 3826 3827 // add { handle, packets } entries 3828 btstack_linked_item_t * it; 3829 for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){ 3830 hci_connection_t * connection = (hci_connection_t *) it; 3831 if (connection->num_packets_completed){ 3832 little_endian_store_16(packet, size, connection->con_handle); 3833 size += 2; 3834 little_endian_store_16(packet, size, connection->num_packets_completed); 3835 size += 2; 3836 // 3837 num_handles++; 3838 connection->num_packets_completed = 0; 3839 } 3840 } 3841 3842 packet[2] = size - 3; 3843 packet[3] = num_handles; 3844 3845 hci_stack->host_completed_packets = 0; 3846 3847 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 3848 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 3849 3850 // release packet buffer for synchronous transport implementations 3851 if (hci_transport_synchronous()){ 3852 hci_release_packet_buffer(); 3853 hci_emit_transport_packet_sent(); 3854 } 3855 } 3856 #endif 3857 3858 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){ 3859 UNUSED(ds); 3860 hci_stack->substate = HCI_HALTING_CLOSE; 3861 // allow packet handlers to defer final shutdown 3862 hci_emit_state(); 3863 hci_run(); 3864 } 3865 3866 static bool hci_run_acl_fragments(void){ 3867 if (hci_stack->acl_fragmentation_total_size > 0u) { 3868 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer); 3869 hci_connection_t *connection = hci_connection_for_handle(con_handle); 3870 if (connection) { 3871 if (hci_can_send_prepared_acl_packet_now(con_handle)){ 3872 hci_send_acl_packet_fragments(connection); 3873 return true; 3874 } 3875 } else { 3876 // connection gone -> discard further fragments 3877 log_info("hci_run: fragmented ACL packet no connection -> discard fragment"); 3878 hci_stack->acl_fragmentation_total_size = 0; 3879 hci_stack->acl_fragmentation_pos = 0; 3880 } 3881 } 3882 return false; 3883 } 3884 3885 #ifdef ENABLE_CLASSIC 3886 static bool hci_run_general_gap_classic(void){ 3887 3888 // decline incoming connections 3889 if (hci_stack->decline_reason){ 3890 uint8_t reason = hci_stack->decline_reason; 3891 hci_stack->decline_reason = 0; 3892 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 3893 return true; 3894 } 3895 // write page scan activity 3896 if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_interval != 0xffff) && hci_classic_supported()){ 3897 hci_send_cmd(&hci_write_page_scan_activity, hci_stack->new_page_scan_interval, hci_stack->new_page_scan_window); 3898 hci_stack->new_page_scan_interval = 0xffff; 3899 hci_stack->new_page_scan_window = 0xffff; 3900 return true; 3901 } 3902 // write page scan type 3903 if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_page_scan_type != 0xff) && hci_classic_supported()){ 3904 hci_send_cmd(&hci_write_page_scan_type, hci_stack->new_page_scan_type); 3905 hci_stack->new_page_scan_type = 0xff; 3906 return true; 3907 } 3908 // send scan enable 3909 if ((hci_stack->state == HCI_STATE_WORKING) && (hci_stack->new_scan_enable_value != 0xff) && hci_classic_supported()){ 3910 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 3911 hci_stack->new_scan_enable_value = 0xff; 3912 return true; 3913 } 3914 // start/stop inquiry 3915 if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)){ 3916 uint8_t duration = hci_stack->inquiry_state; 3917 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_ACTIVE; 3918 hci_send_cmd(&hci_inquiry, hci_stack->inquiry_lap, duration, 0); 3919 return true; 3920 } 3921 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){ 3922 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED; 3923 hci_send_cmd(&hci_inquiry_cancel); 3924 return true; 3925 } 3926 // remote name request 3927 if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){ 3928 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE; 3929 hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr, 3930 hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset); 3931 return true; 3932 } 3933 #ifdef ENABLE_CLASSIC_PAIRING_OOB 3934 // Local OOB data 3935 if ((hci_stack->state == HCI_STATE_WORKING) && hci_stack->classic_read_local_oob_data){ 3936 hci_stack->classic_read_local_oob_data = false; 3937 if (hci_stack->local_supported_commands[1] & 0x10u){ 3938 hci_send_cmd(&hci_read_local_extended_oob_data); 3939 } else { 3940 hci_send_cmd(&hci_read_local_oob_data); 3941 } 3942 } 3943 #endif 3944 // pairing 3945 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){ 3946 uint8_t state = hci_stack->gap_pairing_state; 3947 hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE; 3948 uint8_t pin_code[16]; 3949 switch (state){ 3950 case GAP_PAIRING_STATE_SEND_PIN: 3951 memset(pin_code, 0, 16); 3952 memcpy(pin_code, hci_stack->gap_pairing_input.gap_pairing_pin, hci_stack->gap_pairing_pin_len); 3953 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_pin_len, pin_code); 3954 break; 3955 case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE: 3956 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr); 3957 break; 3958 case GAP_PAIRING_STATE_SEND_PASSKEY: 3959 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey); 3960 break; 3961 case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE: 3962 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr); 3963 break; 3964 case GAP_PAIRING_STATE_SEND_CONFIRMATION: 3965 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr); 3966 break; 3967 case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE: 3968 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr); 3969 break; 3970 default: 3971 break; 3972 } 3973 return true; 3974 } 3975 return false; 3976 } 3977 #endif 3978 3979 #ifdef ENABLE_BLE 3980 static bool hci_run_general_gap_le(void){ 3981 3982 // advertisements, active scanning, and creating connections requires random address to be set if using private address 3983 3984 if (hci_stack->state != HCI_STATE_WORKING) return false; 3985 if ( (hci_stack->le_own_addr_type != BD_ADDR_TYPE_LE_PUBLIC) && (hci_stack->le_random_address_set == 0u) ) return false; 3986 3987 3988 // Phase 1: collect what to stop 3989 3990 bool scanning_stop = false; 3991 bool connecting_stop = false; 3992 bool advertising_stop = false; 3993 3994 #ifndef ENABLE_LE_CENTRAL 3995 UNUSED(scanning_stop); 3996 UNUSED(connecting_stop); 3997 #endif 3998 #ifndef ENABLE_LE_PERIPHERAL 3999 UNUSED(advertising_stop); 4000 #endif 4001 4002 // check if whitelist needs modification 4003 bool whitelist_modification_pending = false; 4004 btstack_linked_list_iterator_t lit; 4005 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 4006 while (btstack_linked_list_iterator_has_next(&lit)){ 4007 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 4008 if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){ 4009 whitelist_modification_pending = true; 4010 break; 4011 } 4012 } 4013 // check if resolving list needs modification 4014 bool resolving_list_modification_pending = false; 4015 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 4016 bool resolving_list_supported = (hci_stack->local_supported_commands[1] & (1 << 2)) != 0; 4017 if (resolving_list_supported && hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_DONE){ 4018 resolving_list_modification_pending = true; 4019 } 4020 #endif 4021 4022 #ifdef ENABLE_LE_CENTRAL 4023 // scanning control 4024 if (hci_stack->le_scanning_active) { 4025 // stop if: 4026 // - parameter change required 4027 // - it's disabled 4028 // - whitelist change required but used for scanning 4029 // - resolving list modified 4030 bool scanning_uses_whitelist = (hci_stack->le_scan_filter_policy & 1) == 1; 4031 if ((hci_stack->le_scanning_param_update) || 4032 !hci_stack->le_scanning_enabled || 4033 scanning_uses_whitelist || 4034 resolving_list_modification_pending){ 4035 4036 scanning_stop = true; 4037 } 4038 } 4039 #endif 4040 4041 #ifdef ENABLE_LE_CENTRAL 4042 // connecting control 4043 bool connecting_with_whitelist; 4044 switch (hci_stack->le_connecting_state){ 4045 case LE_CONNECTING_DIRECT: 4046 case LE_CONNECTING_WHITELIST: 4047 // stop connecting if: 4048 // - connecting uses white and whitelist modification pending 4049 // - if it got disabled 4050 // - resolving list modified 4051 connecting_with_whitelist = hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST; 4052 if ((connecting_with_whitelist && whitelist_modification_pending) || 4053 (hci_stack->le_connecting_request == LE_CONNECTING_IDLE) || 4054 resolving_list_modification_pending) { 4055 4056 connecting_stop = true; 4057 } 4058 break; 4059 default: 4060 break; 4061 } 4062 #endif 4063 4064 #ifdef ENABLE_LE_PERIPHERAL 4065 // le advertisement control 4066 if (hci_stack->le_advertisements_active){ 4067 // stop if: 4068 // - parameter change required 4069 // - it's disabled 4070 // - whitelist change required but used for advertisement filter policy 4071 // - resolving list modified 4072 bool advertising_uses_whitelist = hci_stack->le_advertisements_filter_policy != 0; 4073 bool advertising_change = (hci_stack->le_advertisements_todo & (LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_SET_ADV_DATA)) != 0; 4074 if (advertising_change || 4075 (hci_stack->le_advertisements_enabled_for_current_roles == 0) || 4076 (advertising_uses_whitelist & whitelist_modification_pending) || 4077 resolving_list_modification_pending) { 4078 4079 advertising_stop = true; 4080 } 4081 } 4082 #endif 4083 4084 4085 // Phase 2: stop everything that should be off during modifications 4086 4087 #ifdef ENABLE_LE_CENTRAL 4088 if (scanning_stop){ 4089 hci_stack->le_scanning_active = false; 4090 hci_send_cmd(&hci_le_set_scan_enable, 0, 0); 4091 return true; 4092 } 4093 #endif 4094 4095 #ifdef ENABLE_LE_CENTRAL 4096 if (connecting_stop){ 4097 hci_send_cmd(&hci_le_create_connection_cancel); 4098 return true; 4099 } 4100 #endif 4101 4102 #ifdef ENABLE_LE_PERIPHERAL 4103 if (advertising_stop){ 4104 hci_stack->le_advertisements_active = false; 4105 hci_send_cmd(&hci_le_set_advertise_enable, 0); 4106 return true; 4107 } 4108 #endif 4109 4110 // Phase 3: modify 4111 4112 #ifdef ENABLE_LE_CENTRAL 4113 if (hci_stack->le_scanning_param_update){ 4114 hci_stack->le_scanning_param_update = false; 4115 hci_send_cmd(&hci_le_set_scan_parameters, hci_stack->le_scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, 4116 hci_stack->le_own_addr_type, hci_stack->le_scan_filter_policy); 4117 return true; 4118 } 4119 #endif 4120 4121 #ifdef ENABLE_LE_PERIPHERAL 4122 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){ 4123 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS; 4124 hci_stack->le_advertisements_own_addr_type = hci_stack->le_own_addr_type; 4125 hci_send_cmd(&hci_le_set_advertising_parameters, 4126 hci_stack->le_advertisements_interval_min, 4127 hci_stack->le_advertisements_interval_max, 4128 hci_stack->le_advertisements_type, 4129 hci_stack->le_advertisements_own_addr_type, 4130 hci_stack->le_advertisements_direct_address_type, 4131 hci_stack->le_advertisements_direct_address, 4132 hci_stack->le_advertisements_channel_map, 4133 hci_stack->le_advertisements_filter_policy); 4134 return true; 4135 } 4136 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){ 4137 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 4138 uint8_t adv_data_clean[31]; 4139 memset(adv_data_clean, 0, sizeof(adv_data_clean)); 4140 (void)memcpy(adv_data_clean, hci_stack->le_advertisements_data, 4141 hci_stack->le_advertisements_data_len); 4142 btstack_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len, hci_stack->local_bd_addr); 4143 hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean); 4144 return true; 4145 } 4146 if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){ 4147 hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 4148 uint8_t scan_data_clean[31]; 4149 memset(scan_data_clean, 0, sizeof(scan_data_clean)); 4150 (void)memcpy(scan_data_clean, hci_stack->le_scan_response_data, 4151 hci_stack->le_scan_response_data_len); 4152 btstack_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len, hci_stack->local_bd_addr); 4153 hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, scan_data_clean); 4154 return true; 4155 } 4156 #endif 4157 4158 4159 #ifdef ENABLE_LE_CENTRAL 4160 // if connect with whitelist was active and is not cancelled yet, wait until next time 4161 if (hci_stack->le_connecting_state == LE_CONNECTING_CANCEL) return false; 4162 #endif 4163 4164 // LE Whitelist Management 4165 if (whitelist_modification_pending){ 4166 // add/remove entries 4167 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 4168 while (btstack_linked_list_iterator_has_next(&lit)){ 4169 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 4170 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){ 4171 entry->state &= ~LE_WHITELIST_REMOVE_FROM_CONTROLLER; 4172 hci_send_cmd(&hci_le_remove_device_from_white_list, entry->address_type, entry->address); 4173 return true; 4174 } 4175 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){ 4176 entry->state &= ~LE_WHITELIST_ADD_TO_CONTROLLER; 4177 entry->state |= LE_WHITELIST_ON_CONTROLLER; 4178 hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address); 4179 return true; 4180 } 4181 if ((entry->state & LE_WHITELIST_ON_CONTROLLER) == 0){ 4182 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 4183 btstack_memory_whitelist_entry_free(entry); 4184 } 4185 } 4186 } 4187 4188 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 4189 // LE Resolving List Management 4190 if (resolving_list_supported) { 4191 uint16_t i; 4192 switch (hci_stack->le_resolving_list_state) { 4193 case LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION: 4194 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE; 4195 hci_send_cmd(&hci_le_set_address_resolution_enabled, 1); 4196 return true; 4197 case LE_RESOLVING_LIST_READ_SIZE: 4198 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_SEND_CLEAR; 4199 hci_send_cmd(&hci_le_read_resolving_list_size); 4200 return true; 4201 case LE_RESOLVING_LIST_SEND_CLEAR: 4202 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 4203 (void) memset(hci_stack->le_resolving_list_add_entries, 0xff, 4204 sizeof(hci_stack->le_resolving_list_add_entries)); 4205 (void) memset(hci_stack->le_resolving_list_remove_entries, 0, 4206 sizeof(hci_stack->le_resolving_list_remove_entries)); 4207 hci_send_cmd(&hci_le_clear_resolving_list); 4208 return true; 4209 case LE_RESOLVING_LIST_REMOVE_ENTRIES: 4210 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) { 4211 uint8_t offset = i >> 3; 4212 uint8_t mask = 1 << (i & 7); 4213 if ((hci_stack->le_resolving_list_remove_entries[offset] & mask) == 0) continue; 4214 hci_stack->le_resolving_list_remove_entries[offset] &= ~mask; 4215 bd_addr_t peer_identity_addreses; 4216 int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN; 4217 sm_key_t peer_irk; 4218 le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk); 4219 if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue; 4220 4221 #ifdef ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE 4222 // trigger whitelist entry 'update' (work around for controller bug) 4223 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 4224 while (btstack_linked_list_iterator_has_next(&lit)) { 4225 whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&lit); 4226 if (entry->address_type != peer_identity_addr_type) continue; 4227 if (memcmp(entry->address, peer_identity_addreses, 6) != 0) continue; 4228 log_info("trigger whitelist update %s", bd_addr_to_str(peer_identity_addreses)); 4229 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER; 4230 } 4231 #endif 4232 4233 hci_send_cmd(&hci_le_remove_device_from_resolving_list, peer_identity_addr_type, 4234 peer_identity_addreses); 4235 return true; 4236 } 4237 4238 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_ADD_ENTRIES; 4239 4240 /* fall through */ 4241 4242 case LE_RESOLVING_LIST_ADD_ENTRIES: 4243 for (i = 0; i < MAX_NUM_RESOLVING_LIST_ENTRIES && i < le_device_db_max_count(); i++) { 4244 uint8_t offset = i >> 3; 4245 uint8_t mask = 1 << (i & 7); 4246 if ((hci_stack->le_resolving_list_add_entries[offset] & mask) == 0) continue; 4247 hci_stack->le_resolving_list_add_entries[offset] &= ~mask; 4248 bd_addr_t peer_identity_addreses; 4249 int peer_identity_addr_type = (int) BD_ADDR_TYPE_UNKNOWN; 4250 sm_key_t peer_irk; 4251 le_device_db_info(i, &peer_identity_addr_type, peer_identity_addreses, peer_irk); 4252 if (peer_identity_addr_type == BD_ADDR_TYPE_UNKNOWN) continue; 4253 const uint8_t *local_irk = gap_get_persistent_irk(); 4254 // command uses format specifier 'P' that stores 16-byte value without flip 4255 uint8_t local_irk_flipped[16]; 4256 uint8_t peer_irk_flipped[16]; 4257 reverse_128(local_irk, local_irk_flipped); 4258 reverse_128(peer_irk, peer_irk_flipped); 4259 hci_send_cmd(&hci_le_add_device_to_resolving_list, peer_identity_addr_type, peer_identity_addreses, 4260 peer_irk_flipped, local_irk_flipped); 4261 return true; 4262 } 4263 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE; 4264 break; 4265 4266 default: 4267 break; 4268 } 4269 } 4270 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_DONE; 4271 #endif 4272 4273 // Phase 4: restore state 4274 4275 #ifdef ENABLE_LE_CENTRAL 4276 // re-start scanning 4277 if ((hci_stack->le_scanning_enabled && !hci_stack->le_scanning_active)){ 4278 hci_stack->le_scanning_active = true; 4279 hci_send_cmd(&hci_le_set_scan_enable, 1, 0); 4280 return true; 4281 } 4282 #endif 4283 4284 #ifdef ENABLE_LE_CENTRAL 4285 // re-start connecting 4286 if ( (hci_stack->le_connecting_state == LE_CONNECTING_IDLE) && (hci_stack->le_connecting_request == LE_CONNECTING_WHITELIST)){ 4287 bd_addr_t null_addr; 4288 memset(null_addr, 0, 6); 4289 hci_stack->le_connection_own_addr_type = hci_stack->le_own_addr_type; 4290 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address); 4291 hci_send_cmd(&hci_le_create_connection, 4292 hci_stack->le_connection_scan_interval, // scan interval: 60 ms 4293 hci_stack->le_connection_scan_window, // scan interval: 30 ms 4294 1, // use whitelist 4295 0, // peer address type 4296 null_addr, // peer bd addr 4297 hci_stack->le_connection_own_addr_type, // our addr type: 4298 hci_stack->le_connection_interval_min, // conn interval min 4299 hci_stack->le_connection_interval_max, // conn interval max 4300 hci_stack->le_connection_latency, // conn latency 4301 hci_stack->le_supervision_timeout, // conn latency 4302 hci_stack->le_minimum_ce_length, // min ce length 4303 hci_stack->le_maximum_ce_length // max ce length 4304 ); 4305 return true; 4306 } 4307 #endif 4308 4309 #ifdef ENABLE_LE_PERIPHERAL 4310 // re-start advertising 4311 if (hci_stack->le_advertisements_enabled_for_current_roles && !hci_stack->le_advertisements_active){ 4312 // check if advertisements should be enabled given 4313 hci_stack->le_advertisements_active = true; 4314 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_advertisements_own_address); 4315 hci_send_cmd(&hci_le_set_advertise_enable, 1); 4316 return true; 4317 } 4318 #endif 4319 4320 return false; 4321 } 4322 #endif 4323 4324 static bool hci_run_general_pending_commands(void){ 4325 btstack_linked_item_t * it; 4326 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 4327 hci_connection_t * connection = (hci_connection_t *) it; 4328 4329 switch(connection->state){ 4330 case SEND_CREATE_CONNECTION: 4331 switch(connection->address_type){ 4332 #ifdef ENABLE_CLASSIC 4333 case BD_ADDR_TYPE_ACL: 4334 log_info("sending hci_create_connection"); 4335 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_stack->allow_role_switch); 4336 break; 4337 #endif 4338 default: 4339 #ifdef ENABLE_BLE 4340 #ifdef ENABLE_LE_CENTRAL 4341 log_info("sending hci_le_create_connection"); 4342 hci_stack->le_connection_own_addr_type = hci_stack->le_own_addr_type; 4343 hci_get_own_address_for_addr_type(hci_stack->le_connection_own_addr_type, hci_stack->le_connection_own_address); 4344 hci_send_cmd(&hci_le_create_connection, 4345 hci_stack->le_connection_scan_interval, // conn scan interval 4346 hci_stack->le_connection_scan_window, // conn scan windows 4347 0, // don't use whitelist 4348 connection->address_type, // peer address type 4349 connection->address, // peer bd addr 4350 hci_stack->le_connection_own_addr_type, // our addr type: 4351 hci_stack->le_connection_interval_min, // conn interval min 4352 hci_stack->le_connection_interval_max, // conn interval max 4353 hci_stack->le_connection_latency, // conn latency 4354 hci_stack->le_supervision_timeout, // conn latency 4355 hci_stack->le_minimum_ce_length, // min ce length 4356 hci_stack->le_maximum_ce_length // max ce length 4357 ); 4358 connection->state = SENT_CREATE_CONNECTION; 4359 #endif 4360 #endif 4361 break; 4362 } 4363 return true; 4364 4365 #ifdef ENABLE_CLASSIC 4366 case RECEIVED_CONNECTION_REQUEST: 4367 connection->role = HCI_ROLE_SLAVE; 4368 if (connection->address_type == BD_ADDR_TYPE_ACL){ 4369 log_info("sending hci_accept_connection_request"); 4370 connection->state = ACCEPTED_CONNECTION_REQUEST; 4371 hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy); 4372 } 4373 return true; 4374 #endif 4375 4376 #ifdef ENABLE_BLE 4377 #ifdef ENABLE_LE_CENTRAL 4378 case SEND_CANCEL_CONNECTION: 4379 connection->state = SENT_CANCEL_CONNECTION; 4380 hci_send_cmd(&hci_le_create_connection_cancel); 4381 return true; 4382 #endif 4383 #endif 4384 case SEND_DISCONNECT: 4385 connection->state = SENT_DISCONNECT; 4386 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 4387 return true; 4388 4389 default: 4390 break; 4391 } 4392 4393 // no further commands if connection is about to get shut down 4394 if (connection->state == SENT_DISCONNECT) continue; 4395 4396 if (connection->authentication_flags & READ_RSSI){ 4397 connectionClearAuthenticationFlags(connection, READ_RSSI); 4398 hci_send_cmd(&hci_read_rssi, connection->con_handle); 4399 return true; 4400 } 4401 4402 #ifdef ENABLE_CLASSIC 4403 4404 if (connection->authentication_flags & WRITE_SUPERVISION_TIMEOUT){ 4405 connectionClearAuthenticationFlags(connection, WRITE_SUPERVISION_TIMEOUT); 4406 hci_send_cmd(&hci_write_link_supervision_timeout, connection->con_handle, hci_stack->link_supervision_timeout); 4407 return true; 4408 } 4409 4410 // Handling link key request requires remote supported features 4411 if ( ((connection->authentication_flags & HANDLE_LINK_KEY_REQUEST) != 0) && ((connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) != 0)){ 4412 log_info("responding to link key request, have link key db: %u", hci_stack->link_key_db != NULL); 4413 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 4414 4415 // lookup link key using cached key first 4416 bool have_link_key = connection->link_key_type != INVALID_LINK_KEY; 4417 if (!have_link_key && (hci_stack->link_key_db != NULL)){ 4418 have_link_key = hci_stack->link_key_db->get_link_key(connection->address, connection->link_key, &connection->link_key_type); 4419 } 4420 4421 const uint16_t sc_enabled_mask = BONDING_REMOTE_SUPPORTS_SC_HOST | BONDING_REMOTE_SUPPORTS_SC_CONTROLLER; 4422 bool sc_enabled_remote = (connection->bonding_flags & sc_enabled_mask) == sc_enabled_mask; 4423 bool sc_downgrade = have_link_key && (gap_secure_connection_for_link_key_type(connection->link_key_type) == 1) && !sc_enabled_remote; 4424 if (sc_downgrade){ 4425 log_info("Link key based on SC, but remote does not support SC -> disconnect"); 4426 connection->state = SENT_DISCONNECT; 4427 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE); 4428 return true; 4429 } 4430 4431 bool security_level_sufficient = have_link_key && (gap_security_level_for_link_key_type(connection->link_key_type) >= connection->requested_security_level); 4432 if (have_link_key && security_level_sufficient){ 4433 hci_send_cmd(&hci_link_key_request_reply, connection->address, &connection->link_key); 4434 } else { 4435 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 4436 } 4437 return true; 4438 } 4439 4440 if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){ 4441 log_info("denying to pin request"); 4442 connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST); 4443 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 4444 return true; 4445 } 4446 4447 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 4448 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 4449 // set authentication requirements: 4450 // - MITM = ssp_authentication_requirement (USER) | requested_security_level (dynamic) 4451 // - BONDING MODE: 4452 // - initiator: dedicated if requested, bondable otherwise 4453 // - responder: local & remote bondable 4454 uint8_t authreq = hci_stack->ssp_authentication_requirement & 1; 4455 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 4456 authreq |= 1; 4457 } 4458 if (connection->bonding_flags & BONDING_DEDICATED){ 4459 authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 4460 } else if (hci_stack->bondable){ 4461 authreq |= SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 4462 } 4463 uint8_t have_oob_data = 0; 4464 #ifdef ENABLE_CLASSIC_PAIRING_OOB 4465 if (connection->classic_oob_c_192 != NULL){ 4466 have_oob_data |= 1; 4467 } 4468 if (connection->classic_oob_c_256 != NULL){ 4469 have_oob_data |= 2; 4470 } 4471 #endif 4472 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, have_oob_data, authreq); 4473 return true; 4474 } 4475 4476 if (connection->authentication_flags & SEND_IO_CAPABILITIES_NEGATIVE_REPLY) { 4477 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 4478 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 4479 return true; 4480 } 4481 4482 #ifdef ENABLE_CLASSIC_PAIRING_OOB 4483 if (connection->authentication_flags & SEND_REMOTE_OOB_DATA_REPLY){ 4484 connectionClearAuthenticationFlags(connection, SEND_REMOTE_OOB_DATA_REPLY); 4485 const uint8_t zero[16] = { 0 }; 4486 const uint8_t * r_192 = zero; 4487 const uint8_t * c_192 = zero; 4488 const uint8_t * r_256 = zero; 4489 const uint8_t * c_256 = zero; 4490 // verify P-256 OOB 4491 if ((connection->classic_oob_c_256 != NULL) && ((hci_stack->local_supported_commands[1] & 0x08u) != 0)) { 4492 c_256 = connection->classic_oob_c_256; 4493 if (connection->classic_oob_r_256 != NULL) { 4494 r_256 = connection->classic_oob_r_256; 4495 } 4496 } 4497 // verify P-192 OOB 4498 if ((connection->classic_oob_c_192 != NULL)) { 4499 c_192 = connection->classic_oob_c_192; 4500 if (connection->classic_oob_r_192 != NULL) { 4501 r_192 = connection->classic_oob_r_192; 4502 } 4503 } 4504 // Reply 4505 if (c_256 != zero) { 4506 hci_send_cmd(&hci_remote_oob_extended_data_request_reply, &connection->address, c_192, r_192, c_256, r_256); 4507 } else if (c_192 != zero){ 4508 hci_send_cmd(&hci_remote_oob_data_request_reply, &connection->address, c_192, r_192); 4509 } else { 4510 hci_send_cmd(&hci_remote_oob_data_request_negative_reply, &connection->address); 4511 } 4512 return true; 4513 } 4514 #endif 4515 4516 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 4517 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 4518 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 4519 return true; 4520 } 4521 4522 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 4523 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 4524 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 4525 return true; 4526 } 4527 4528 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_0){ 4529 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_0; 4530 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 4531 return true; 4532 } 4533 4534 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_1){ 4535 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_1; 4536 hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 1); 4537 return true; 4538 } 4539 4540 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES_PAGE_2){ 4541 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES_PAGE_2; 4542 hci_send_cmd(&hci_read_remote_extended_features_command, connection->con_handle, 2); 4543 return true; 4544 } 4545 4546 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 4547 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 4548 connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT; 4549 connection->state = SENT_DISCONNECT; 4550 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 4551 return true; 4552 } 4553 4554 if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){ 4555 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 4556 connection->bonding_flags |= BONDING_SENT_AUTHENTICATE_REQUEST; 4557 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 4558 return true; 4559 } 4560 4561 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 4562 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 4563 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 4564 return true; 4565 } 4566 if (connection->bonding_flags & BONDING_SEND_READ_ENCRYPTION_KEY_SIZE){ 4567 connection->bonding_flags &= ~BONDING_SEND_READ_ENCRYPTION_KEY_SIZE; 4568 hci_send_cmd(&hci_read_encryption_key_size, connection->con_handle, 1); 4569 return true; 4570 } 4571 #endif 4572 4573 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 4574 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 4575 if (connection->state != SENT_DISCONNECT){ 4576 connection->state = SENT_DISCONNECT; 4577 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_AUTHENTICATION_FAILURE); 4578 return true; 4579 } 4580 } 4581 4582 #ifdef ENABLE_CLASSIC 4583 uint16_t sniff_min_interval; 4584 switch (connection->sniff_min_interval){ 4585 case 0: 4586 break; 4587 case 0xffff: 4588 connection->sniff_min_interval = 0; 4589 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle); 4590 return true; 4591 default: 4592 sniff_min_interval = connection->sniff_min_interval; 4593 connection->sniff_min_interval = 0; 4594 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout); 4595 return true; 4596 } 4597 4598 if (connection->sniff_subrating_max_latency != 0xffff){ 4599 uint16_t max_latency = connection->sniff_subrating_max_latency; 4600 connection->sniff_subrating_max_latency = 0; 4601 hci_send_cmd(&hci_sniff_subrating, connection->con_handle, max_latency, connection->sniff_subrating_min_remote_timeout, connection->sniff_subrating_min_local_timeout); 4602 return true; 4603 } 4604 4605 if (connection->qos_service_type != HCI_SERVICE_TyPE_INVALID){ 4606 uint8_t service_type = (uint8_t) connection->qos_service_type; 4607 connection->qos_service_type = HCI_SERVICE_TyPE_INVALID; 4608 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); 4609 return true; 4610 } 4611 4612 if (connection->request_role != HCI_ROLE_INVALID){ 4613 hci_role_t role = connection->request_role; 4614 connection->request_role = HCI_ROLE_INVALID; 4615 hci_send_cmd(&hci_switch_role_command, connection->address, role); 4616 return true; 4617 } 4618 #endif 4619 4620 #ifdef ENABLE_BLE 4621 switch (connection->le_con_parameter_update_state){ 4622 // response to L2CAP CON PARAMETER UPDATE REQUEST 4623 case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS: 4624 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 4625 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min, 4626 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 4627 0x0000, 0xffff); 4628 return true; 4629 case CON_PARAMETER_UPDATE_REPLY: 4630 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 4631 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min, 4632 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 4633 0x0000, 0xffff); 4634 return true; 4635 case CON_PARAMETER_UPDATE_NEGATIVE_REPLY: 4636 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE; 4637 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE); 4638 return true; 4639 default: 4640 break; 4641 } 4642 if (connection->le_phy_update_all_phys != 0xffu){ 4643 uint8_t all_phys = connection->le_phy_update_all_phys; 4644 connection->le_phy_update_all_phys = 0xff; 4645 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); 4646 return true; 4647 } 4648 #endif 4649 } 4650 return false; 4651 } 4652 4653 static void hci_run(void){ 4654 4655 bool done; 4656 4657 // send continuation fragments first, as they block the prepared packet buffer 4658 done = hci_run_acl_fragments(); 4659 if (done) return; 4660 4661 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL 4662 // send host num completed packets next as they don't require num_cmd_packets > 0 4663 if (!hci_can_send_comand_packet_transport()) return; 4664 if (hci_stack->host_completed_packets){ 4665 hci_host_num_completed_packets(); 4666 return; 4667 } 4668 #endif 4669 4670 if (!hci_can_send_command_packet_now()) return; 4671 4672 // global/non-connection oriented commands 4673 4674 4675 #ifdef ENABLE_CLASSIC 4676 // general gap classic 4677 done = hci_run_general_gap_classic(); 4678 if (done) return; 4679 #endif 4680 4681 #ifdef ENABLE_BLE 4682 // general gap le 4683 done = hci_run_general_gap_le(); 4684 if (done) return; 4685 #endif 4686 4687 // send pending HCI commands 4688 done = hci_run_general_pending_commands(); 4689 if (done) return; 4690 4691 // stack state sub statemachines 4692 hci_connection_t * connection; 4693 switch (hci_stack->state){ 4694 case HCI_STATE_INITIALIZING: 4695 hci_initializing_run(); 4696 break; 4697 4698 case HCI_STATE_HALTING: 4699 4700 log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate); 4701 switch (hci_stack->substate){ 4702 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER: 4703 case HCI_HALTING_DISCONNECT_ALL_TIMER: 4704 4705 #ifdef ENABLE_BLE 4706 #ifdef ENABLE_LE_CENTRAL 4707 // free whitelist entries 4708 { 4709 btstack_linked_list_iterator_t lit; 4710 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist); 4711 while (btstack_linked_list_iterator_has_next(&lit)){ 4712 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit); 4713 btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry); 4714 btstack_memory_whitelist_entry_free(entry); 4715 } 4716 } 4717 #endif 4718 #endif 4719 // close all open connections 4720 connection = (hci_connection_t *) hci_stack->connections; 4721 if (connection){ 4722 hci_con_handle_t con_handle = (uint16_t) connection->con_handle; 4723 if (!hci_can_send_command_packet_now()) return; 4724 4725 // check state 4726 if (connection->state == SENT_DISCONNECT) return; 4727 connection->state = SENT_DISCONNECT; 4728 4729 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle); 4730 4731 // cancel all l2cap connections right away instead of waiting for disconnection complete event ... 4732 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host 4733 4734 // ... which would be ignored anyway as we shutdown (free) the connection now 4735 hci_shutdown_connection(connection); 4736 4737 // finally, send the disconnect command 4738 hci_send_cmd(&hci_disconnect, con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 4739 return; 4740 } 4741 4742 if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){ 4743 // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event 4744 log_info("HCI_STATE_HALTING: wait 50 ms"); 4745 hci_stack->substate = HCI_HALTING_W4_TIMER; 4746 btstack_run_loop_set_timer(&hci_stack->timeout, 50); 4747 btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler); 4748 btstack_run_loop_add_timer(&hci_stack->timeout); 4749 break; 4750 } 4751 4752 /* fall through */ 4753 4754 case HCI_HALTING_CLOSE: 4755 log_info("HCI_STATE_HALTING, calling off"); 4756 4757 // switch mode 4758 hci_power_control_off(); 4759 4760 log_info("HCI_STATE_HALTING, emitting state"); 4761 hci_emit_state(); 4762 log_info("HCI_STATE_HALTING, done"); 4763 break; 4764 4765 case HCI_HALTING_W4_TIMER: 4766 // keep waiting 4767 4768 break; 4769 default: 4770 break; 4771 } 4772 4773 break; 4774 4775 case HCI_STATE_FALLING_ASLEEP: 4776 switch(hci_stack->substate) { 4777 case HCI_FALLING_ASLEEP_DISCONNECT: 4778 log_info("HCI_STATE_FALLING_ASLEEP"); 4779 // close all open connections 4780 connection = (hci_connection_t *) hci_stack->connections; 4781 4782 #ifdef HAVE_PLATFORM_IPHONE_OS 4783 // don't close connections, if H4 supports power management 4784 if (btstack_control_iphone_power_management_enabled()){ 4785 connection = NULL; 4786 } 4787 #endif 4788 if (connection){ 4789 4790 // send disconnect 4791 if (!hci_can_send_command_packet_now()) return; 4792 4793 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 4794 hci_send_cmd(&hci_disconnect, connection->con_handle, ERROR_CODE_REMOTE_USER_TERMINATED_CONNECTION); 4795 4796 // send disconnected event right away - causes higher layer connections to get closed, too. 4797 hci_shutdown_connection(connection); 4798 return; 4799 } 4800 4801 if (hci_classic_supported()){ 4802 // disable page and inquiry scan 4803 if (!hci_can_send_command_packet_now()) return; 4804 4805 log_info("HCI_STATE_HALTING, disabling inq scans"); 4806 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 4807 4808 // continue in next sub state 4809 hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE; 4810 break; 4811 } 4812 4813 /* fall through */ 4814 4815 case HCI_FALLING_ASLEEP_COMPLETE: 4816 log_info("HCI_STATE_HALTING, calling sleep"); 4817 #ifdef HAVE_PLATFORM_IPHONE_OS 4818 // don't actually go to sleep, if H4 supports power management 4819 if (btstack_control_iphone_power_management_enabled()){ 4820 // SLEEP MODE reached 4821 hci_stack->state = HCI_STATE_SLEEPING; 4822 hci_emit_state(); 4823 break; 4824 } 4825 #endif 4826 // switch mode 4827 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 4828 hci_emit_state(); 4829 break; 4830 4831 default: 4832 break; 4833 } 4834 break; 4835 4836 default: 4837 break; 4838 } 4839 } 4840 4841 int hci_send_cmd_packet(uint8_t *packet, int size){ 4842 // house-keeping 4843 4844 #ifdef ENABLE_CLASSIC 4845 bd_addr_t addr; 4846 hci_connection_t * conn; 4847 #endif 4848 #ifdef ENABLE_LE_CENTRAL 4849 uint8_t initiator_filter_policy; 4850 #endif 4851 4852 uint16_t opcode = little_endian_read_16(packet, 0); 4853 switch (opcode) { 4854 case HCI_OPCODE_HCI_WRITE_LOOPBACK_MODE: 4855 hci_stack->loopback_mode = packet[3]; 4856 break; 4857 4858 #ifdef ENABLE_CLASSIC 4859 case HCI_OPCODE_HCI_CREATE_CONNECTION: 4860 reverse_bd_addr(&packet[3], addr); 4861 log_info("Create_connection to %s", bd_addr_to_str(addr)); 4862 4863 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 4864 if (!conn) { 4865 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 4866 if (!conn) { 4867 // notify client that alloc failed 4868 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 4869 return -1; // packet not sent to controller 4870 } 4871 conn->state = SEND_CREATE_CONNECTION; 4872 conn->role = HCI_ROLE_MASTER; 4873 } 4874 log_info("conn state %u", conn->state); 4875 switch (conn->state) { 4876 // if connection active exists 4877 case OPEN: 4878 // and OPEN, emit connection complete command 4879 hci_emit_connection_complete(addr, conn->con_handle, 0); 4880 return -1; // packet not sent to controller 4881 case RECEIVED_DISCONNECTION_COMPLETE: 4882 // create connection triggered in disconnect complete event, let's do it now 4883 break; 4884 case SEND_CREATE_CONNECTION: 4885 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now 4886 break; 4887 default: 4888 // otherwise, just ignore as it is already in the open process 4889 return -1; // packet not sent to controller 4890 } 4891 conn->state = SENT_CREATE_CONNECTION; 4892 4893 // track outgoing connection 4894 hci_stack->outgoing_addr_type = BD_ADDR_TYPE_ACL; 4895 (void) memcpy(hci_stack->outgoing_addr, addr, 6); 4896 break; 4897 case HCI_OPCODE_HCI_LINK_KEY_REQUEST_REPLY: 4898 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 4899 break; 4900 case HCI_OPCODE_HCI_LINK_KEY_REQUEST_NEGATIVE_REPLY: 4901 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 4902 break; 4903 case HCI_OPCODE_HCI_DELETE_STORED_LINK_KEY: 4904 if (hci_stack->link_key_db) { 4905 reverse_bd_addr(&packet[3], addr); 4906 hci_stack->link_key_db->delete_link_key(addr); 4907 } 4908 break; 4909 case HCI_OPCODE_HCI_PIN_CODE_REQUEST_NEGATIVE_REPLY: 4910 case HCI_OPCODE_HCI_PIN_CODE_REQUEST_REPLY: 4911 reverse_bd_addr(&packet[3], addr); 4912 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 4913 if (conn) { 4914 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 4915 } 4916 break; 4917 case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_NEGATIVE_REPLY: 4918 case HCI_OPCODE_HCI_USER_CONFIRMATION_REQUEST_REPLY: 4919 case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_NEGATIVE_REPLY: 4920 case HCI_OPCODE_HCI_USER_PASSKEY_REQUEST_REPLY: 4921 reverse_bd_addr(&packet[3], addr); 4922 conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 4923 if (conn) { 4924 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 4925 } 4926 break; 4927 4928 #if defined (ENABLE_SCO_OVER_HCI) || defined (HAVE_SCO_TRANSPORT) 4929 case HCI_OPCODE_HCI_SETUP_SYNCHRONOUS_CONNECTION: 4930 // setup_synchronous_connection? Voice setting at offset 22 4931 // TODO: compare to current setting if sco connection already active 4932 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15); 4933 break; 4934 case HCI_OPCODE_HCI_ACCEPT_SYNCHRONOUS_CONNECTION: 4935 // accept_synchronus_connection? Voice setting at offset 18 4936 // TODO: compare to current setting if sco connection already active 4937 hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19); 4938 break; 4939 #endif 4940 #endif 4941 4942 #ifdef ENABLE_BLE 4943 case HCI_OPCODE_HCI_LE_SET_RANDOM_ADDRESS: 4944 hci_stack->le_random_address_set = 1; 4945 reverse_bd_addr(&packet[3], hci_stack->le_random_address); 4946 break; 4947 #ifdef ENABLE_LE_PERIPHERAL 4948 case HCI_OPCODE_HCI_LE_SET_ADVERTISE_ENABLE: 4949 hci_stack->le_advertisements_active = packet[3] != 0; 4950 break; 4951 #endif 4952 #ifdef ENABLE_LE_CENTRAL 4953 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION: 4954 // white list used? 4955 initiator_filter_policy = packet[7]; 4956 switch (initiator_filter_policy) { 4957 case 0: 4958 // whitelist not used 4959 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT; 4960 break; 4961 case 1: 4962 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST; 4963 break; 4964 default: 4965 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy); 4966 break; 4967 } 4968 // track outgoing connection 4969 hci_stack->outgoing_addr_type = (bd_addr_type_t) packet[8]; // peer addres type 4970 reverse_bd_addr( &packet[9], hci_stack->outgoing_addr); // peer address 4971 break; 4972 case HCI_OPCODE_HCI_LE_CREATE_CONNECTION_CANCEL: 4973 hci_stack->le_connecting_state = LE_CONNECTING_CANCEL; 4974 break; 4975 #endif 4976 #endif 4977 default: 4978 break; 4979 } 4980 4981 hci_stack->num_cmd_packets--; 4982 4983 hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size); 4984 return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 4985 } 4986 4987 // disconnect because of security block 4988 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 4989 hci_connection_t * connection = hci_connection_for_handle(con_handle); 4990 if (!connection) return; 4991 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 4992 } 4993 4994 4995 // Configure Secure Simple Pairing 4996 4997 #ifdef ENABLE_CLASSIC 4998 4999 // enable will enable SSP during init 5000 void gap_ssp_set_enable(int enable){ 5001 hci_stack->ssp_enable = enable; 5002 } 5003 5004 static int hci_local_ssp_activated(void){ 5005 return gap_ssp_supported() && hci_stack->ssp_enable; 5006 } 5007 5008 // if set, BTstack will respond to io capability request using authentication requirement 5009 void gap_ssp_set_io_capability(int io_capability){ 5010 hci_stack->ssp_io_capability = io_capability; 5011 } 5012 void gap_ssp_set_authentication_requirement(int authentication_requirement){ 5013 hci_stack->ssp_authentication_requirement = authentication_requirement; 5014 } 5015 5016 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 5017 void gap_ssp_set_auto_accept(int auto_accept){ 5018 hci_stack->ssp_auto_accept = auto_accept; 5019 } 5020 5021 void gap_secure_connections_enable(bool enable){ 5022 hci_stack->secure_connections_enable = enable; 5023 } 5024 5025 #endif 5026 5027 // va_list part of hci_send_cmd 5028 int hci_send_cmd_va_arg(const hci_cmd_t * cmd, va_list argptr){ 5029 if (!hci_can_send_command_packet_now()){ 5030 log_error("hci_send_cmd called but cannot send packet now"); 5031 return 0; 5032 } 5033 5034 // for HCI INITIALIZATION 5035 // log_info("hci_send_cmd: opcode %04x", cmd->opcode); 5036 hci_stack->last_cmd_opcode = cmd->opcode; 5037 5038 hci_reserve_packet_buffer(); 5039 uint8_t * packet = hci_stack->hci_packet_buffer; 5040 uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr); 5041 int err = hci_send_cmd_packet(packet, size); 5042 5043 // release packet buffer on error or for synchronous transport implementations 5044 if ((err < 0) || hci_transport_synchronous()){ 5045 hci_release_packet_buffer(); 5046 hci_emit_transport_packet_sent(); 5047 } 5048 5049 return err; 5050 } 5051 5052 /** 5053 * pre: numcmds >= 0 - it's allowed to send a command to the controller 5054 */ 5055 int hci_send_cmd(const hci_cmd_t * cmd, ...){ 5056 va_list argptr; 5057 va_start(argptr, cmd); 5058 int res = hci_send_cmd_va_arg(cmd, argptr); 5059 va_end(argptr); 5060 return res; 5061 } 5062 5063 // Create various non-HCI events. 5064 // TODO: generalize, use table similar to hci_create_command 5065 5066 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){ 5067 // dump packet 5068 if (dump) { 5069 hci_dump_packet( HCI_EVENT_PACKET, 0, event, size); 5070 } 5071 5072 // dispatch to all event handlers 5073 btstack_linked_list_iterator_t it; 5074 btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers); 5075 while (btstack_linked_list_iterator_has_next(&it)){ 5076 btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it); 5077 entry->callback(HCI_EVENT_PACKET, 0, event, size); 5078 } 5079 } 5080 5081 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){ 5082 if (!hci_stack->acl_packet_handler) return; 5083 hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size); 5084 } 5085 5086 #ifdef ENABLE_CLASSIC 5087 static void hci_notify_if_sco_can_send_now(void){ 5088 // notify SCO sender if waiting 5089 if (!hci_stack->sco_waiting_for_can_send_now) return; 5090 if (hci_can_send_sco_packet_now()){ 5091 hci_stack->sco_waiting_for_can_send_now = 0; 5092 uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 }; 5093 hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event)); 5094 hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event)); 5095 } 5096 } 5097 5098 // parsing end emitting has been merged to reduce code size 5099 static void gap_inquiry_explode(uint8_t *packet, uint16_t size) { 5100 uint8_t event[28+GAP_INQUIRY_MAX_NAME_LEN]; 5101 5102 uint8_t * eir_data; 5103 ad_context_t context; 5104 const uint8_t * name; 5105 uint8_t name_len; 5106 5107 if (size < 3) return; 5108 5109 int event_type = hci_event_packet_get_type(packet); 5110 int num_reserved_fields = (event_type == HCI_EVENT_INQUIRY_RESULT) ? 2 : 1; // 2 for old event, 1 otherwise 5111 int num_responses = hci_event_inquiry_result_get_num_responses(packet); 5112 5113 switch (event_type){ 5114 case HCI_EVENT_INQUIRY_RESULT: 5115 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 5116 if (size != (3 + (num_responses * 14))) return; 5117 break; 5118 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 5119 if (size != 257) return; 5120 if (num_responses != 1) return; 5121 break; 5122 default: 5123 return; 5124 } 5125 5126 // event[1] is set at the end 5127 int i; 5128 for (i=0; i<num_responses;i++){ 5129 memset(event, 0, sizeof(event)); 5130 event[0] = GAP_EVENT_INQUIRY_RESULT; 5131 uint8_t event_size = 18; // if name is not set by EIR 5132 5133 (void)memcpy(&event[2], &packet[3 + (i * 6)], 6); // bd_addr 5134 event[8] = packet[3 + (num_responses*(6)) + (i*1)]; // page_scan_repetition_mode 5135 (void)memcpy(&event[9], 5136 &packet[3 + (num_responses * (6 + 1 + num_reserved_fields)) + (i * 3)], 5137 3); // class of device 5138 (void)memcpy(&event[12], 5139 &packet[3 + (num_responses * (6 + 1 + num_reserved_fields + 3)) + (i * 2)], 5140 2); // clock offset 5141 5142 switch (event_type){ 5143 case HCI_EVENT_INQUIRY_RESULT: 5144 // 14,15,16,17 = 0, size 18 5145 break; 5146 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 5147 event[14] = 1; 5148 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi 5149 // 16,17 = 0, size 18 5150 break; 5151 case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: 5152 event[14] = 1; 5153 event[15] = packet [3 + (num_responses*(6+1+num_reserved_fields+3+2)) + (i*1)]; // rssi 5154 // EIR packets only contain a single inquiry response 5155 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)]; 5156 name = NULL; 5157 // Iterate over EIR data 5158 for (ad_iterator_init(&context, EXTENDED_INQUIRY_RESPONSE_DATA_LEN, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){ 5159 uint8_t data_type = ad_iterator_get_data_type(&context); 5160 uint8_t data_size = ad_iterator_get_data_len(&context); 5161 const uint8_t * data = ad_iterator_get_data(&context); 5162 // Prefer Complete Local Name over Shortened Local Name 5163 switch (data_type){ 5164 case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME: 5165 if (name) continue; 5166 /* fall through */ 5167 case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME: 5168 name = data; 5169 name_len = data_size; 5170 break; 5171 case BLUETOOTH_DATA_TYPE_DEVICE_ID: 5172 if (data_size != 8) break; 5173 event[16] = 1; 5174 memcpy(&event[17], data, 8); 5175 break; 5176 default: 5177 break; 5178 } 5179 } 5180 if (name){ 5181 event[25] = 1; 5182 // truncate name if needed 5183 int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN); 5184 event[26] = len; 5185 (void)memcpy(&event[27], name, len); 5186 event_size += len; 5187 } 5188 break; 5189 default: 5190 return; 5191 } 5192 event[1] = event_size - 2; 5193 hci_emit_event(event, event_size, 1); 5194 } 5195 } 5196 #endif 5197 5198 void hci_emit_state(void){ 5199 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 5200 uint8_t event[3]; 5201 event[0] = BTSTACK_EVENT_STATE; 5202 event[1] = sizeof(event) - 2u; 5203 event[2] = hci_stack->state; 5204 hci_emit_event(event, sizeof(event), 1); 5205 } 5206 5207 #ifdef ENABLE_CLASSIC 5208 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){ 5209 uint8_t event[13]; 5210 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 5211 event[1] = sizeof(event) - 2; 5212 event[2] = status; 5213 little_endian_store_16(event, 3, con_handle); 5214 reverse_bd_addr(address, &event[5]); 5215 event[11] = 1; // ACL connection 5216 event[12] = 0; // encryption disabled 5217 hci_emit_event(event, sizeof(event), 1); 5218 } 5219 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 5220 if (disable_l2cap_timeouts) return; 5221 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 5222 uint8_t event[4]; 5223 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 5224 event[1] = sizeof(event) - 2; 5225 little_endian_store_16(event, 2, conn->con_handle); 5226 hci_emit_event(event, sizeof(event), 1); 5227 } 5228 #endif 5229 5230 #ifdef ENABLE_BLE 5231 #ifdef ENABLE_LE_CENTRAL 5232 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){ 5233 uint8_t event[21]; 5234 event[0] = HCI_EVENT_LE_META; 5235 event[1] = sizeof(event) - 2u; 5236 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 5237 event[3] = status; 5238 little_endian_store_16(event, 4, con_handle); 5239 event[6] = 0; // TODO: role 5240 event[7] = address_type; 5241 reverse_bd_addr(address, &event[8]); 5242 little_endian_store_16(event, 14, 0); // interval 5243 little_endian_store_16(event, 16, 0); // latency 5244 little_endian_store_16(event, 18, 0); // supervision timeout 5245 event[20] = 0; // master clock accuracy 5246 hci_emit_event(event, sizeof(event), 1); 5247 } 5248 #endif 5249 #endif 5250 5251 static void hci_emit_transport_packet_sent(void){ 5252 // notify upper stack that it might be possible to send again 5253 uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0}; 5254 hci_emit_event(&event[0], sizeof(event), 0); // don't dump 5255 } 5256 5257 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){ 5258 uint8_t event[6]; 5259 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 5260 event[1] = sizeof(event) - 2u; 5261 event[2] = 0; // status = OK 5262 little_endian_store_16(event, 3, con_handle); 5263 event[5] = reason; 5264 hci_emit_event(event, sizeof(event), 1); 5265 } 5266 5267 static void hci_emit_nr_connections_changed(void){ 5268 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 5269 uint8_t event[3]; 5270 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 5271 event[1] = sizeof(event) - 2u; 5272 event[2] = nr_hci_connections(); 5273 hci_emit_event(event, sizeof(event), 1); 5274 } 5275 5276 static void hci_emit_hci_open_failed(void){ 5277 log_info("BTSTACK_EVENT_POWERON_FAILED"); 5278 uint8_t event[2]; 5279 event[0] = BTSTACK_EVENT_POWERON_FAILED; 5280 event[1] = sizeof(event) - 2u; 5281 hci_emit_event(event, sizeof(event), 1); 5282 } 5283 5284 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){ 5285 log_info("hci_emit_dedicated_bonding_result %u ", status); 5286 uint8_t event[9]; 5287 int pos = 0; 5288 event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED; 5289 event[pos++] = sizeof(event) - 2u; 5290 event[pos++] = status; 5291 reverse_bd_addr(address, &event[pos]); 5292 hci_emit_event(event, sizeof(event), 1); 5293 } 5294 5295 5296 #ifdef ENABLE_CLASSIC 5297 5298 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 5299 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 5300 uint8_t event[5]; 5301 int pos = 0; 5302 event[pos++] = GAP_EVENT_SECURITY_LEVEL; 5303 event[pos++] = sizeof(event) - 2; 5304 little_endian_store_16(event, 2, con_handle); 5305 pos += 2; 5306 event[pos++] = level; 5307 hci_emit_event(event, sizeof(event), 1); 5308 } 5309 5310 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 5311 if (!connection) return LEVEL_0; 5312 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 5313 // BIAS: we only consider Authenticated if the connection is already encrypted, which requires that both sides have link key 5314 if ((connection->authentication_flags & CONNECTION_AUTHENTICATED) == 0) return LEVEL_0; 5315 if (connection->encryption_key_size < hci_stack->gap_required_encyrption_key_size) return LEVEL_0; 5316 gap_security_level_t security_level = gap_security_level_for_link_key_type(connection->link_key_type); 5317 // LEVEL 4 always requires 128 bit encrytion key size 5318 if ((security_level == LEVEL_4) && (connection->encryption_key_size < 16)){ 5319 security_level = LEVEL_3; 5320 } 5321 return security_level; 5322 } 5323 5324 static void hci_emit_discoverable_enabled(uint8_t enabled){ 5325 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 5326 uint8_t event[3]; 5327 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 5328 event[1] = sizeof(event) - 2; 5329 event[2] = enabled; 5330 hci_emit_event(event, sizeof(event), 1); 5331 } 5332 5333 // query if remote side supports eSCO 5334 int hci_remote_esco_supported(hci_con_handle_t con_handle){ 5335 hci_connection_t * connection = hci_connection_for_handle(con_handle); 5336 if (!connection) return 0; 5337 return (connection->remote_supported_features[0] & 1) != 0; 5338 } 5339 5340 static bool hci_ssp_supported(hci_connection_t * connection){ 5341 const uint8_t mask = BONDING_REMOTE_SUPPORTS_SSP_CONTROLLER | BONDING_REMOTE_SUPPORTS_SSP_HOST; 5342 return (connection->bonding_flags & mask) == mask; 5343 } 5344 5345 // query if remote side supports SSP 5346 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 5347 hci_connection_t * connection = hci_connection_for_handle(con_handle); 5348 if (!connection) return 0; 5349 return hci_ssp_supported(connection) ? 1 : 0; 5350 } 5351 5352 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){ 5353 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 5354 } 5355 5356 // GAP API 5357 /** 5358 * @bbrief enable/disable bonding. default is enabled 5359 * @praram enabled 5360 */ 5361 void gap_set_bondable_mode(int enable){ 5362 hci_stack->bondable = enable ? 1 : 0; 5363 } 5364 /** 5365 * @brief Get bondable mode. 5366 * @return 1 if bondable 5367 */ 5368 int gap_get_bondable_mode(void){ 5369 return hci_stack->bondable; 5370 } 5371 5372 /** 5373 * @brief map link keys to security levels 5374 */ 5375 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 5376 switch (link_key_type){ 5377 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 5378 return LEVEL_4; 5379 case COMBINATION_KEY: 5380 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 5381 return LEVEL_3; 5382 default: 5383 return LEVEL_2; 5384 } 5385 } 5386 5387 /** 5388 * @brief map link keys to secure connection yes/no 5389 */ 5390 int gap_secure_connection_for_link_key_type(link_key_type_t link_key_type){ 5391 switch (link_key_type){ 5392 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 5393 case UNAUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 5394 return 1; 5395 default: 5396 return 0; 5397 } 5398 } 5399 5400 /** 5401 * @brief map link keys to authenticated 5402 */ 5403 int gap_authenticated_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 AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 5407 return 1; 5408 default: 5409 return 0; 5410 } 5411 } 5412 5413 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 5414 log_info("gap_mitm_protection_required_for_security_level %u", level); 5415 return level > LEVEL_2; 5416 } 5417 5418 /** 5419 * @brief get current security level 5420 */ 5421 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 5422 hci_connection_t * connection = hci_connection_for_handle(con_handle); 5423 if (!connection) return LEVEL_0; 5424 return gap_security_level_for_connection(connection); 5425 } 5426 5427 /** 5428 * @brief request connection to device to 5429 * @result GAP_AUTHENTICATION_RESULT 5430 */ 5431 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 5432 hci_connection_t * connection = hci_connection_for_handle(con_handle); 5433 if (!connection){ 5434 hci_emit_security_level(con_handle, LEVEL_0); 5435 return; 5436 } 5437 5438 btstack_assert(hci_is_le_connection(connection) == false); 5439 5440 gap_security_level_t current_level = gap_security_level(con_handle); 5441 log_info("gap_request_security_level requested level %u, planned level %u, current level %u", 5442 requested_level, connection->requested_security_level, current_level); 5443 5444 // authentication active if authentication request was sent or planned level > 0 5445 bool authentication_active = ((connection->bonding_flags & BONDING_SENT_AUTHENTICATE_REQUEST) != 0) || (connection->requested_security_level > LEVEL_0); 5446 if (authentication_active){ 5447 // authentication already active 5448 if (connection->requested_security_level < requested_level){ 5449 // increase requested level as new level is higher 5450 // TODO: handle re-authentication when done 5451 connection->requested_security_level = requested_level; 5452 } 5453 } else { 5454 // no request active, notify if security sufficient 5455 if (requested_level <= current_level){ 5456 hci_emit_security_level(con_handle, current_level); 5457 return; 5458 } 5459 5460 // store request 5461 connection->requested_security_level = requested_level; 5462 5463 // start to authenticate connection 5464 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 5465 hci_run(); 5466 } 5467 } 5468 5469 /** 5470 * @brief start dedicated bonding with device. disconnect after bonding 5471 * @param device 5472 * @param request MITM protection 5473 * @result GAP_DEDICATED_BONDING_COMPLETE 5474 */ 5475 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 5476 5477 // create connection state machine 5478 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_ACL); 5479 5480 if (!connection){ 5481 return BTSTACK_MEMORY_ALLOC_FAILED; 5482 } 5483 5484 // delete linkn key 5485 gap_drop_link_key_for_bd_addr(device); 5486 5487 // configure LEVEL_2/3, dedicated bonding 5488 connection->state = SEND_CREATE_CONNECTION; 5489 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 5490 log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level); 5491 connection->bonding_flags = BONDING_DEDICATED; 5492 5493 // wait for GAP Security Result and send GAP Dedicated Bonding complete 5494 5495 // handle: connnection failure (connection complete != ok) 5496 // handle: authentication failure 5497 // handle: disconnect on done 5498 5499 hci_run(); 5500 5501 return 0; 5502 } 5503 #endif 5504 5505 void gap_set_local_name(const char * local_name){ 5506 hci_stack->local_name = local_name; 5507 } 5508 5509 5510 #ifdef ENABLE_BLE 5511 5512 #ifdef ENABLE_LE_CENTRAL 5513 void gap_start_scan(void){ 5514 hci_stack->le_scanning_enabled = true; 5515 hci_run(); 5516 } 5517 5518 void gap_stop_scan(void){ 5519 hci_stack->le_scanning_enabled = false; 5520 hci_run(); 5521 } 5522 5523 void gap_set_scan_params(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window, uint8_t scanning_filter_policy){ 5524 hci_stack->le_scan_type = scan_type; 5525 hci_stack->le_scan_filter_policy = scanning_filter_policy; 5526 hci_stack->le_scan_interval = scan_interval; 5527 hci_stack->le_scan_window = scan_window; 5528 hci_stack->le_scanning_param_update = true; 5529 hci_run(); 5530 } 5531 5532 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 5533 gap_set_scan_params(scan_type, scan_interval, scan_window, 0); 5534 } 5535 5536 uint8_t gap_connect(const bd_addr_t addr, bd_addr_type_t addr_type){ 5537 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 5538 if (!conn){ 5539 // disallow if le connection is already outgoing 5540 if (hci_is_le_connection_type(addr_type) && hci_stack->le_connecting_request != LE_CONNECTING_IDLE){ 5541 log_error("le connection already active"); 5542 return ERROR_CODE_COMMAND_DISALLOWED; 5543 } 5544 5545 log_info("gap_connect: no connection exists yet, creating context"); 5546 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 5547 if (!conn){ 5548 // notify client that alloc failed 5549 hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED); 5550 log_info("gap_connect: failed to alloc hci_connection_t"); 5551 return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller 5552 } 5553 5554 // set le connecting state 5555 if (hci_is_le_connection_type(addr_type)){ 5556 hci_stack->le_connecting_request = LE_CONNECTING_DIRECT; 5557 } 5558 5559 conn->state = SEND_CREATE_CONNECTION; 5560 log_info("gap_connect: send create connection next"); 5561 hci_run(); 5562 return ERROR_CODE_SUCCESS; 5563 } 5564 5565 if (!hci_is_le_connection(conn) || 5566 (conn->state == SEND_CREATE_CONNECTION) || 5567 (conn->state == SENT_CREATE_CONNECTION)) { 5568 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED); 5569 log_error("gap_connect: classic connection or connect is already being created"); 5570 return GATT_CLIENT_IN_WRONG_STATE; 5571 } 5572 5573 // check if connection was just disconnected 5574 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 5575 log_info("gap_connect: send create connection (again)"); 5576 conn->state = SEND_CREATE_CONNECTION; 5577 hci_run(); 5578 return ERROR_CODE_SUCCESS; 5579 } 5580 5581 log_info("gap_connect: context exists with state %u", conn->state); 5582 hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, ERROR_CODE_SUCCESS); 5583 hci_run(); 5584 return ERROR_CODE_SUCCESS; 5585 } 5586 5587 // @assumption: only a single outgoing LE Connection exists 5588 static hci_connection_t * gap_get_outgoing_connection(void){ 5589 btstack_linked_item_t *it; 5590 for (it = (btstack_linked_item_t *) hci_stack->connections; it != NULL; it = it->next){ 5591 hci_connection_t * conn = (hci_connection_t *) it; 5592 if (!hci_is_le_connection(conn)) continue; 5593 switch (conn->state){ 5594 case SEND_CREATE_CONNECTION: 5595 case SENT_CREATE_CONNECTION: 5596 case SENT_CANCEL_CONNECTION: 5597 return conn; 5598 default: 5599 break; 5600 }; 5601 } 5602 return NULL; 5603 } 5604 5605 uint8_t gap_connect_cancel(void){ 5606 hci_connection_t * conn = gap_get_outgoing_connection(); 5607 if (!conn) return 0; 5608 switch (conn->state){ 5609 case SEND_CREATE_CONNECTION: 5610 // skip sending create connection and emit event instead 5611 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 5612 hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 5613 btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn); 5614 btstack_memory_hci_connection_free( conn ); 5615 break; 5616 case SENT_CREATE_CONNECTION: 5617 // request to send cancel connection 5618 conn->state = SEND_CANCEL_CONNECTION; 5619 hci_run(); 5620 break; 5621 default: 5622 break; 5623 } 5624 return 0; 5625 } 5626 #endif 5627 5628 #ifdef ENABLE_LE_CENTRAL 5629 /** 5630 * @brief Set connection parameters for outgoing connections 5631 * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms 5632 * @param conn_scan_window (unit: 0.625 msec), default: 30 ms 5633 * @param conn_interval_min (unit: 1.25ms), default: 10 ms 5634 * @param conn_interval_max (unit: 1.25ms), default: 30 ms 5635 * @param conn_latency, default: 4 5636 * @param supervision_timeout (unit: 10ms), default: 720 ms 5637 * @param min_ce_length (unit: 0.625ms), default: 10 ms 5638 * @param max_ce_length (unit: 0.625ms), default: 30 ms 5639 */ 5640 5641 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window, 5642 uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, 5643 uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){ 5644 hci_stack->le_connection_scan_interval = conn_scan_interval; 5645 hci_stack->le_connection_scan_window = conn_scan_window; 5646 hci_stack->le_connection_interval_min = conn_interval_min; 5647 hci_stack->le_connection_interval_max = conn_interval_max; 5648 hci_stack->le_connection_latency = conn_latency; 5649 hci_stack->le_supervision_timeout = supervision_timeout; 5650 hci_stack->le_minimum_ce_length = min_ce_length; 5651 hci_stack->le_maximum_ce_length = max_ce_length; 5652 } 5653 #endif 5654 5655 /** 5656 * @brief Updates the connection parameters for a given LE connection 5657 * @param handle 5658 * @param conn_interval_min (unit: 1.25ms) 5659 * @param conn_interval_max (unit: 1.25ms) 5660 * @param conn_latency 5661 * @param supervision_timeout (unit: 10ms) 5662 * @returns 0 if ok 5663 */ 5664 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min, 5665 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 5666 hci_connection_t * connection = hci_connection_for_handle(con_handle); 5667 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 5668 connection->le_conn_interval_min = conn_interval_min; 5669 connection->le_conn_interval_max = conn_interval_max; 5670 connection->le_conn_latency = conn_latency; 5671 connection->le_supervision_timeout = supervision_timeout; 5672 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS; 5673 hci_run(); 5674 return 0; 5675 } 5676 5677 /** 5678 * @brief Request an update of the connection parameter for a given LE connection 5679 * @param handle 5680 * @param conn_interval_min (unit: 1.25ms) 5681 * @param conn_interval_max (unit: 1.25ms) 5682 * @param conn_latency 5683 * @param supervision_timeout (unit: 10ms) 5684 * @returns 0 if ok 5685 */ 5686 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min, 5687 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 5688 hci_connection_t * connection = hci_connection_for_handle(con_handle); 5689 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 5690 connection->le_conn_interval_min = conn_interval_min; 5691 connection->le_conn_interval_max = conn_interval_max; 5692 connection->le_conn_latency = conn_latency; 5693 connection->le_supervision_timeout = supervision_timeout; 5694 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST; 5695 uint8_t l2cap_trigger_run_event[2] = { L2CAP_EVENT_TRIGGER_RUN, 0}; 5696 hci_emit_event(l2cap_trigger_run_event, sizeof(l2cap_trigger_run_event), 0); 5697 return 0; 5698 } 5699 5700 #ifdef ENABLE_LE_PERIPHERAL 5701 5702 /** 5703 * @brief Set Advertisement Data 5704 * @param advertising_data_length 5705 * @param advertising_data (max 31 octets) 5706 * @note data is not copied, pointer has to stay valid 5707 */ 5708 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){ 5709 hci_stack->le_advertisements_data_len = advertising_data_length; 5710 hci_stack->le_advertisements_data = advertising_data; 5711 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA; 5712 hci_run(); 5713 } 5714 5715 /** 5716 * @brief Set Scan Response 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_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){ 5722 hci_stack->le_scan_response_data_len = scan_response_data_length; 5723 hci_stack->le_scan_response_data = scan_response_data; 5724 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA; 5725 hci_run(); 5726 } 5727 5728 /** 5729 * @brief Set Advertisement Parameters 5730 * @param adv_int_min 5731 * @param adv_int_max 5732 * @param adv_type 5733 * @param direct_address_type 5734 * @param direct_address 5735 * @param channel_map 5736 * @param filter_policy 5737 * 5738 * @note internal use. use gap_advertisements_set_params from gap_le.h instead. 5739 */ 5740 void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type, 5741 uint8_t direct_address_typ, bd_addr_t direct_address, 5742 uint8_t channel_map, uint8_t filter_policy) { 5743 5744 hci_stack->le_advertisements_interval_min = adv_int_min; 5745 hci_stack->le_advertisements_interval_max = adv_int_max; 5746 hci_stack->le_advertisements_type = adv_type; 5747 hci_stack->le_advertisements_direct_address_type = direct_address_typ; 5748 hci_stack->le_advertisements_channel_map = channel_map; 5749 hci_stack->le_advertisements_filter_policy = filter_policy; 5750 (void)memcpy(hci_stack->le_advertisements_direct_address, direct_address, 5751 6); 5752 5753 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS | LE_ADVERTISEMENT_TASKS_PARAMS_SET; 5754 hci_run(); 5755 } 5756 5757 /** 5758 * @brief Enable/Disable Advertisements 5759 * @param enabled 5760 */ 5761 void gap_advertisements_enable(int enabled){ 5762 hci_stack->le_advertisements_enabled = enabled != 0; 5763 hci_update_advertisements_enabled_for_current_roles(); 5764 hci_run(); 5765 } 5766 5767 #endif 5768 5769 void hci_le_set_own_address_type(uint8_t own_address_type){ 5770 log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type); 5771 if (own_address_type == hci_stack->le_own_addr_type) return; 5772 hci_stack->le_own_addr_type = own_address_type; 5773 5774 #ifdef ENABLE_LE_PERIPHERAL 5775 // update advertisement parameters, too 5776 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS; 5777 hci_run(); 5778 #endif 5779 #ifdef ENABLE_LE_CENTRAL 5780 // note: we don't update scan parameters or modify ongoing connection attempts 5781 #endif 5782 } 5783 5784 #endif 5785 5786 uint8_t gap_disconnect(hci_con_handle_t handle){ 5787 hci_connection_t * conn = hci_connection_for_handle(handle); 5788 if (!conn){ 5789 hci_emit_disconnection_complete(handle, 0); 5790 return 0; 5791 } 5792 // ignore if already disconnected 5793 if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){ 5794 return 0; 5795 } 5796 conn->state = SEND_DISCONNECT; 5797 hci_run(); 5798 return 0; 5799 } 5800 5801 int gap_read_rssi(hci_con_handle_t con_handle){ 5802 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 5803 if (hci_connection == NULL) return 0; 5804 connectionSetAuthenticationFlags(hci_connection, READ_RSSI); 5805 hci_run(); 5806 return 1; 5807 } 5808 5809 /** 5810 * @brief Get connection type 5811 * @param con_handle 5812 * @result connection_type 5813 */ 5814 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){ 5815 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 5816 if (!conn) return GAP_CONNECTION_INVALID; 5817 switch (conn->address_type){ 5818 case BD_ADDR_TYPE_LE_PUBLIC: 5819 case BD_ADDR_TYPE_LE_RANDOM: 5820 return GAP_CONNECTION_LE; 5821 case BD_ADDR_TYPE_SCO: 5822 return GAP_CONNECTION_SCO; 5823 case BD_ADDR_TYPE_ACL: 5824 return GAP_CONNECTION_ACL; 5825 default: 5826 return GAP_CONNECTION_INVALID; 5827 } 5828 } 5829 5830 hci_role_t gap_get_role(hci_con_handle_t connection_handle){ 5831 hci_connection_t * conn = hci_connection_for_handle(connection_handle); 5832 if (!conn) return HCI_ROLE_INVALID; 5833 return (hci_role_t) conn->role; 5834 } 5835 5836 5837 #ifdef ENABLE_CLASSIC 5838 uint8_t gap_request_role(const bd_addr_t addr, hci_role_t role){ 5839 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 5840 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 5841 conn->request_role = role; 5842 hci_run(); 5843 return ERROR_CODE_SUCCESS; 5844 } 5845 #endif 5846 5847 #ifdef ENABLE_BLE 5848 5849 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){ 5850 hci_connection_t * conn = hci_connection_for_handle(con_handle); 5851 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 5852 5853 conn->le_phy_update_all_phys = all_phys; 5854 conn->le_phy_update_tx_phys = tx_phys; 5855 conn->le_phy_update_rx_phys = rx_phys; 5856 conn->le_phy_update_phy_options = phy_options; 5857 5858 hci_run(); 5859 5860 return 0; 5861 } 5862 5863 static uint8_t hci_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){ 5864 // check if already in list 5865 btstack_linked_list_iterator_t it; 5866 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 5867 while (btstack_linked_list_iterator_has_next(&it)) { 5868 whitelist_entry_t *entry = (whitelist_entry_t *) btstack_linked_list_iterator_next(&it); 5869 if (entry->address_type != address_type) { 5870 continue; 5871 } 5872 if (memcmp(entry->address, address, 6) != 0) { 5873 continue; 5874 } 5875 // disallow if already scheduled to add 5876 if ((entry->state & LE_WHITELIST_ADD_TO_CONTROLLER) != 0){ 5877 return ERROR_CODE_COMMAND_DISALLOWED; 5878 } 5879 // still on controller, but scheduled to remove -> re-add 5880 entry->state |= LE_WHITELIST_ADD_TO_CONTROLLER; 5881 return ERROR_CODE_SUCCESS; 5882 } 5883 // alloc and add to list 5884 whitelist_entry_t * entry = btstack_memory_whitelist_entry_get(); 5885 if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED; 5886 entry->address_type = address_type; 5887 (void)memcpy(entry->address, address, 6); 5888 entry->state = LE_WHITELIST_ADD_TO_CONTROLLER; 5889 btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry); 5890 return ERROR_CODE_SUCCESS; 5891 } 5892 5893 static uint8_t hci_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){ 5894 btstack_linked_list_iterator_t it; 5895 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 5896 while (btstack_linked_list_iterator_has_next(&it)){ 5897 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 5898 if (entry->address_type != address_type) { 5899 continue; 5900 } 5901 if (memcmp(entry->address, address, 6) != 0) { 5902 continue; 5903 } 5904 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 5905 // remove from controller if already present 5906 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 5907 } else { 5908 // directly remove entry from whitelist 5909 btstack_linked_list_iterator_remove(&it); 5910 btstack_memory_whitelist_entry_free(entry); 5911 } 5912 return ERROR_CODE_SUCCESS; 5913 } 5914 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 5915 } 5916 5917 static void hci_whitelist_clear(void){ 5918 btstack_linked_list_iterator_t it; 5919 btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist); 5920 while (btstack_linked_list_iterator_has_next(&it)){ 5921 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it); 5922 if (entry->state & LE_WHITELIST_ON_CONTROLLER){ 5923 // remove from controller if already present 5924 entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER; 5925 continue; 5926 } 5927 // directly remove entry from whitelist 5928 btstack_linked_list_iterator_remove(&it); 5929 btstack_memory_whitelist_entry_free(entry); 5930 } 5931 } 5932 5933 /** 5934 * @brief Clear Whitelist 5935 * @returns 0 if ok 5936 */ 5937 uint8_t gap_whitelist_clear(void){ 5938 hci_whitelist_clear(); 5939 hci_run(); 5940 return ERROR_CODE_SUCCESS; 5941 } 5942 5943 /** 5944 * @brief Add Device to Whitelist 5945 * @param address_typ 5946 * @param address 5947 * @returns 0 if ok 5948 */ 5949 uint8_t gap_whitelist_add(bd_addr_type_t address_type, const bd_addr_t address){ 5950 uint8_t status = hci_whitelist_add(address_type, address); 5951 if (status){ 5952 return status; 5953 } 5954 hci_run(); 5955 return ERROR_CODE_SUCCESS; 5956 } 5957 5958 /** 5959 * @brief Remove Device from Whitelist 5960 * @param address_typ 5961 * @param address 5962 * @returns 0 if ok 5963 */ 5964 uint8_t gap_whitelist_remove(bd_addr_type_t address_type, const bd_addr_t address){ 5965 uint8_t status = hci_whitelist_remove(address_type, address); 5966 if (status){ 5967 return status; 5968 } 5969 hci_run(); 5970 return ERROR_CODE_SUCCESS; 5971 } 5972 5973 #ifdef ENABLE_LE_CENTRAL 5974 /** 5975 * @brief Connect with Whitelist 5976 * @note Explicit whitelist management and this connect with whitelist replace deprecated gap_auto_connection_* functions 5977 * @returns - if ok 5978 */ 5979 uint8_t gap_connect_with_whitelist(void){ 5980 if (hci_stack->le_connecting_request != LE_CONNECTING_IDLE){ 5981 return ERROR_CODE_COMMAND_DISALLOWED; 5982 } 5983 hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST; 5984 hci_run(); 5985 return ERROR_CODE_SUCCESS; 5986 } 5987 5988 /** 5989 * @brief Auto Connection Establishment - Start Connecting to device 5990 * @param address_typ 5991 * @param address 5992 * @returns 0 if ok 5993 */ 5994 uint8_t gap_auto_connection_start(bd_addr_type_t address_type, const bd_addr_t address){ 5995 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){ 5996 return ERROR_CODE_COMMAND_DISALLOWED; 5997 } 5998 5999 uint8_t status = hci_whitelist_add(address_type, address); 6000 if (status == BTSTACK_MEMORY_ALLOC_FAILED) { 6001 return status; 6002 } 6003 6004 hci_stack->le_connecting_request = LE_CONNECTING_WHITELIST; 6005 6006 hci_run(); 6007 return ERROR_CODE_SUCCESS; 6008 } 6009 6010 /** 6011 * @brief Auto Connection Establishment - Stop Connecting to device 6012 * @param address_typ 6013 * @param address 6014 * @returns 0 if ok 6015 */ 6016 uint8_t gap_auto_connection_stop(bd_addr_type_t address_type, const bd_addr_t address){ 6017 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT){ 6018 return ERROR_CODE_COMMAND_DISALLOWED; 6019 } 6020 6021 hci_whitelist_remove(address_type, address); 6022 if (btstack_linked_list_empty(&hci_stack->le_whitelist)){ 6023 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 6024 } 6025 hci_run(); 6026 return 0; 6027 } 6028 6029 /** 6030 * @brief Auto Connection Establishment - Stop everything 6031 * @note Convenience function to stop all active auto connection attempts 6032 */ 6033 uint8_t gap_auto_connection_stop_all(void){ 6034 if (hci_stack->le_connecting_request == LE_CONNECTING_DIRECT) { 6035 return ERROR_CODE_COMMAND_DISALLOWED; 6036 } 6037 hci_whitelist_clear(); 6038 hci_stack->le_connecting_request = LE_CONNECTING_IDLE; 6039 hci_run(); 6040 return ERROR_CODE_SUCCESS; 6041 } 6042 6043 uint16_t gap_le_connection_interval(hci_con_handle_t con_handle){ 6044 hci_connection_t * conn = hci_connection_for_handle(con_handle); 6045 if (!conn) return 0; 6046 return conn->le_connection_interval; 6047 } 6048 #endif 6049 #endif 6050 6051 #ifdef ENABLE_CLASSIC 6052 /** 6053 * @brief Set Extended Inquiry Response data 6054 * @param eir_data size HCI_EXTENDED_INQUIRY_RESPONSE_DATA_LEN (240) bytes, is not copied make sure memory is accessible during stack startup 6055 * @note has to be done before stack starts up 6056 */ 6057 void gap_set_extended_inquiry_response(const uint8_t * data){ 6058 hci_stack->eir_data = data; 6059 } 6060 6061 /** 6062 * @brief Start GAP Classic Inquiry 6063 * @param duration in 1.28s units 6064 * @return 0 if ok 6065 * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE 6066 */ 6067 int gap_inquiry_start(uint8_t duration_in_1280ms_units){ 6068 if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED; 6069 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6070 if ((duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN) || (duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX)){ 6071 return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS; 6072 } 6073 hci_stack->inquiry_state = duration_in_1280ms_units; 6074 hci_run(); 6075 return 0; 6076 } 6077 6078 /** 6079 * @brief Stop GAP Classic Inquiry 6080 * @returns 0 if ok 6081 */ 6082 int gap_inquiry_stop(void){ 6083 if ((hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN) && (hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX)) { 6084 // emit inquiry complete event, before it even started 6085 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0}; 6086 hci_emit_event(event, sizeof(event), 1); 6087 return 0; 6088 } 6089 if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED; 6090 hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL; 6091 hci_run(); 6092 return 0; 6093 } 6094 6095 void gap_inquiry_set_lap(uint32_t lap){ 6096 hci_stack->inquiry_lap = lap; 6097 } 6098 6099 6100 /** 6101 * @brief Remote Name Request 6102 * @param addr 6103 * @param page_scan_repetition_mode 6104 * @param clock_offset only used when bit 15 is set 6105 * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 6106 */ 6107 int gap_remote_name_request(const bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){ 6108 if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6109 (void)memcpy(hci_stack->remote_name_addr, addr, 6); 6110 hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode; 6111 hci_stack->remote_name_clock_offset = clock_offset; 6112 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND; 6113 hci_run(); 6114 return 0; 6115 } 6116 6117 static int gap_pairing_set_state_and_run(const bd_addr_t addr, uint8_t state){ 6118 hci_stack->gap_pairing_state = state; 6119 (void)memcpy(hci_stack->gap_pairing_addr, addr, 6); 6120 hci_run(); 6121 return 0; 6122 } 6123 6124 /** 6125 * @brief Legacy Pairing Pin Code Response for binary data / non-strings 6126 * @param addr 6127 * @param pin_data 6128 * @param pin_len 6129 * @return 0 if ok 6130 */ 6131 int gap_pin_code_response_binary(const bd_addr_t addr, const uint8_t * pin_data, uint8_t pin_len){ 6132 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6133 hci_stack->gap_pairing_input.gap_pairing_pin = pin_data; 6134 hci_stack->gap_pairing_pin_len = pin_len; 6135 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN); 6136 } 6137 6138 /** 6139 * @brief Legacy Pairing Pin Code Response 6140 * @param addr 6141 * @param pin 6142 * @return 0 if ok 6143 */ 6144 int gap_pin_code_response(const bd_addr_t addr, const char * pin){ 6145 return gap_pin_code_response_binary(addr, (const uint8_t*) pin, strlen(pin)); 6146 } 6147 6148 /** 6149 * @brief Abort Legacy Pairing 6150 * @param addr 6151 * @param pin 6152 * @return 0 if ok 6153 */ 6154 int gap_pin_code_negative(bd_addr_t addr){ 6155 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6156 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE); 6157 } 6158 6159 /** 6160 * @brief SSP Passkey Response 6161 * @param addr 6162 * @param passkey 6163 * @return 0 if ok 6164 */ 6165 int gap_ssp_passkey_response(const bd_addr_t addr, uint32_t passkey){ 6166 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6167 hci_stack->gap_pairing_input.gap_pairing_passkey = passkey; 6168 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY); 6169 } 6170 6171 /** 6172 * @brief Abort SSP Passkey Entry/Pairing 6173 * @param addr 6174 * @param pin 6175 * @return 0 if ok 6176 */ 6177 int gap_ssp_passkey_negative(const bd_addr_t addr){ 6178 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6179 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE); 6180 } 6181 6182 /** 6183 * @brief Accept SSP Numeric Comparison 6184 * @param addr 6185 * @param passkey 6186 * @return 0 if ok 6187 */ 6188 int gap_ssp_confirmation_response(const bd_addr_t addr){ 6189 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6190 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION); 6191 } 6192 6193 /** 6194 * @brief Abort SSP Numeric Comparison/Pairing 6195 * @param addr 6196 * @param pin 6197 * @return 0 if ok 6198 */ 6199 int gap_ssp_confirmation_negative(const bd_addr_t addr){ 6200 if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED; 6201 return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE); 6202 } 6203 6204 #ifdef ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY 6205 6206 static uint8_t gap_set_auth_flag_and_run(const bd_addr_t addr, hci_authentication_flags_t flag){ 6207 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 6208 if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 6209 connectionSetAuthenticationFlags(conn, flag); 6210 hci_run(); 6211 return ERROR_CODE_SUCCESS; 6212 } 6213 6214 uint8_t gap_ssp_io_capabilities_response(const bd_addr_t addr){ 6215 return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_REPLY); 6216 } 6217 6218 uint8_t gap_ssp_io_capabilities_negative(const bd_addr_t addr){ 6219 return gap_set_auth_flag_and_run(addr, SEND_IO_CAPABILITIES_NEGATIVE_REPLY); 6220 } 6221 #endif 6222 6223 #ifdef ENABLE_CLASSIC_PAIRING_OOB 6224 /** 6225 * @brief Report Remote OOB Data 6226 * @param bd_addr 6227 * @param c_192 Simple Pairing Hash C derived from P-192 public key 6228 * @param r_192 Simple Pairing Randomizer derived from P-192 public key 6229 * @param c_256 Simple Pairing Hash C derived from P-256 public key 6230 * @param r_256 Simple Pairing Randomizer derived from P-256 public key 6231 */ 6232 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){ 6233 hci_connection_t * connection = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 6234 if (connection == NULL) { 6235 return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 6236 } 6237 connection->classic_oob_c_192 = c_192; 6238 connection->classic_oob_r_192 = r_192; 6239 connection->classic_oob_c_256 = c_256; 6240 connection->classic_oob_r_256 = r_256; 6241 return ERROR_CODE_SUCCESS; 6242 } 6243 /** 6244 * @brief Generate new OOB data 6245 * @note OOB data will be provided in GAP_EVENT_LOCAL_OOB_DATA and be used in future pairing procedures 6246 */ 6247 void gap_ssp_generate_oob_data(void){ 6248 hci_stack->classic_read_local_oob_data = true; 6249 hci_run(); 6250 } 6251 6252 #endif 6253 6254 /** 6255 * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on. 6256 * @param inquiry_mode see bluetooth_defines.h 6257 */ 6258 void hci_set_inquiry_mode(inquiry_mode_t inquiry_mode){ 6259 hci_stack->inquiry_mode = inquiry_mode; 6260 } 6261 6262 /** 6263 * @brief Configure Voice Setting for use with SCO data in HSP/HFP 6264 */ 6265 void hci_set_sco_voice_setting(uint16_t voice_setting){ 6266 hci_stack->sco_voice_setting = voice_setting; 6267 } 6268 6269 /** 6270 * @brief Get SCO Voice Setting 6271 * @return current voice setting 6272 */ 6273 uint16_t hci_get_sco_voice_setting(void){ 6274 return hci_stack->sco_voice_setting; 6275 } 6276 6277 static int hci_have_usb_transport(void){ 6278 if (!hci_stack->hci_transport) return 0; 6279 const char * transport_name = hci_stack->hci_transport->name; 6280 if (!transport_name) return 0; 6281 return (transport_name[0] == 'H') && (transport_name[1] == '2'); 6282 } 6283 6284 /** @brief Get SCO packet length for current SCO Voice setting 6285 * @note Using SCO packets of the exact length is required for USB transfer 6286 * @return Length of SCO packets in bytes (not audio frames) 6287 */ 6288 int hci_get_sco_packet_length(void){ 6289 int sco_packet_length = 0; 6290 6291 #ifdef ENABLE_SCO_OVER_HCI 6292 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 6293 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 6294 6295 if (hci_have_usb_transport()){ 6296 // see Core Spec for H2 USB Transfer. 6297 // 3 byte SCO header + 24 bytes per connection 6298 int num_sco_connections = btstack_max(1, hci_number_sco_connections()); 6299 sco_packet_length = 3 + 24 * num_sco_connections * multiplier; 6300 } else { 6301 // 3 byte SCO header + SCO packet size over the air (60 bytes) 6302 sco_packet_length = 3 + 60 * multiplier; 6303 // assert that it still fits inside an SCO buffer 6304 if (sco_packet_length > hci_stack->sco_data_packet_length){ 6305 sco_packet_length = 3 + 60; 6306 } 6307 } 6308 #endif 6309 6310 #ifdef HAVE_SCO_TRANSPORT 6311 // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes 6312 int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2; 6313 sco_packet_length = 3 + 60 * multiplier; 6314 #endif 6315 return sco_packet_length; 6316 } 6317 6318 /** 6319 * @brief Sets the master/slave policy 6320 * @param policy (0: attempt to become master, 1: let connecting device decide) 6321 */ 6322 void hci_set_master_slave_policy(uint8_t policy){ 6323 hci_stack->master_slave_policy = policy; 6324 } 6325 6326 #endif 6327 6328 HCI_STATE hci_get_state(void){ 6329 return hci_stack->state; 6330 } 6331 6332 #ifdef ENABLE_CLASSIC 6333 void gap_register_classic_connection_filter(int (*accept_callback)(bd_addr_t addr, hci_link_type_t link_type)){ 6334 hci_stack->gap_classic_accept_callback = accept_callback; 6335 } 6336 #endif 6337 6338 /** 6339 * @brief Set callback for Bluetooth Hardware Error 6340 */ 6341 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){ 6342 hci_stack->hardware_error_callback = fn; 6343 } 6344 6345 void hci_disconnect_all(void){ 6346 btstack_linked_list_iterator_t it; 6347 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 6348 while (btstack_linked_list_iterator_has_next(&it)){ 6349 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 6350 if (con->state == SENT_DISCONNECT) continue; 6351 con->state = SEND_DISCONNECT; 6352 } 6353 hci_run(); 6354 } 6355 6356 uint16_t hci_get_manufacturer(void){ 6357 return hci_stack->manufacturer; 6358 } 6359 6360 #ifdef ENABLE_BLE 6361 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){ 6362 hci_connection_t * hci_con = hci_connection_for_handle(con_handle); 6363 if (!hci_con) return NULL; 6364 return &hci_con->sm_connection; 6365 } 6366 6367 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build 6368 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated 6369 #endif 6370 6371 int gap_encryption_key_size(hci_con_handle_t con_handle){ 6372 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 6373 if (hci_connection == NULL) return 0; 6374 if (hci_is_le_connection(hci_connection)){ 6375 #ifdef ENABLE_BLE 6376 sm_connection_t * sm_conn = &hci_connection->sm_connection; 6377 if (sm_conn->sm_connection_encrypted) { 6378 return sm_conn->sm_actual_encryption_key_size; 6379 } 6380 #endif 6381 } else { 6382 #ifdef ENABLE_CLASSIC 6383 if ((hci_connection->authentication_flags & CONNECTION_ENCRYPTED)){ 6384 return hci_connection->encryption_key_size; 6385 } 6386 #endif 6387 } 6388 return 0; 6389 } 6390 6391 int gap_authenticated(hci_con_handle_t con_handle){ 6392 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 6393 if (hci_connection == NULL) return 0; 6394 6395 switch (hci_connection->address_type){ 6396 #ifdef ENABLE_BLE 6397 case BD_ADDR_TYPE_LE_PUBLIC: 6398 case BD_ADDR_TYPE_LE_RANDOM: 6399 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated 6400 return hci_connection->sm_connection.sm_connection_authenticated; 6401 #endif 6402 #ifdef ENABLE_CLASSIC 6403 case BD_ADDR_TYPE_SCO: 6404 case BD_ADDR_TYPE_ACL: 6405 return gap_authenticated_for_link_key_type(hci_connection->link_key_type); 6406 #endif 6407 default: 6408 return 0; 6409 } 6410 } 6411 6412 int gap_secure_connection(hci_con_handle_t con_handle){ 6413 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 6414 if (hci_connection == NULL) return 0; 6415 6416 switch (hci_connection->address_type){ 6417 #ifdef ENABLE_BLE 6418 case BD_ADDR_TYPE_LE_PUBLIC: 6419 case BD_ADDR_TYPE_LE_RANDOM: 6420 if (hci_connection->sm_connection.sm_connection_encrypted == 0) return 0; // unencrypted connection cannot be authenticated 6421 return hci_connection->sm_connection.sm_connection_sc; 6422 #endif 6423 #ifdef ENABLE_CLASSIC 6424 case BD_ADDR_TYPE_SCO: 6425 case BD_ADDR_TYPE_ACL: 6426 return gap_secure_connection_for_link_key_type(hci_connection->link_key_type); 6427 #endif 6428 default: 6429 return 0; 6430 } 6431 } 6432 6433 bool gap_bonded(hci_con_handle_t con_handle){ 6434 hci_connection_t * hci_connection = hci_connection_for_handle(con_handle); 6435 if (hci_connection == NULL) return 0; 6436 6437 #ifdef ENABLE_CLASSIC 6438 link_key_t link_key; 6439 link_key_type_t link_key_type; 6440 #endif 6441 switch (hci_connection->address_type){ 6442 #ifdef ENABLE_BLE 6443 case BD_ADDR_TYPE_LE_PUBLIC: 6444 case BD_ADDR_TYPE_LE_RANDOM: 6445 return hci_connection->sm_connection.sm_le_db_index >= 0; 6446 #endif 6447 #ifdef ENABLE_CLASSIC 6448 case BD_ADDR_TYPE_SCO: 6449 case BD_ADDR_TYPE_ACL: 6450 return hci_stack->link_key_db && hci_stack->link_key_db->get_link_key(hci_connection->address, link_key, &link_key_type); 6451 #endif 6452 default: 6453 return false; 6454 } 6455 } 6456 6457 #ifdef ENABLE_BLE 6458 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){ 6459 sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle); 6460 if (!sm_conn) return AUTHORIZATION_UNKNOWN; // wrong connection 6461 if (!sm_conn->sm_connection_encrypted) return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized 6462 if (!sm_conn->sm_connection_authenticated) return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized 6463 return sm_conn->sm_connection_authorization_state; 6464 } 6465 #endif 6466 6467 #ifdef ENABLE_CLASSIC 6468 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){ 6469 hci_connection_t * conn = hci_connection_for_handle(con_handle); 6470 if (!conn) return GAP_CONNECTION_INVALID; 6471 conn->sniff_min_interval = sniff_min_interval; 6472 conn->sniff_max_interval = sniff_max_interval; 6473 conn->sniff_attempt = sniff_attempt; 6474 conn->sniff_timeout = sniff_timeout; 6475 hci_run(); 6476 return 0; 6477 } 6478 6479 /** 6480 * @brief Exit Sniff mode 6481 * @param con_handle 6482 @ @return 0 if ok 6483 */ 6484 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){ 6485 hci_connection_t * conn = hci_connection_for_handle(con_handle); 6486 if (!conn) return GAP_CONNECTION_INVALID; 6487 conn->sniff_min_interval = 0xffff; 6488 hci_run(); 6489 return 0; 6490 } 6491 6492 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){ 6493 hci_connection_t * conn = hci_connection_for_handle(con_handle); 6494 if (!conn) return GAP_CONNECTION_INVALID; 6495 conn->sniff_subrating_max_latency = max_latency; 6496 conn->sniff_subrating_min_remote_timeout = min_remote_timeout; 6497 conn->sniff_subrating_min_local_timeout = min_local_timeout; 6498 hci_run(); 6499 return ERROR_CODE_SUCCESS; 6500 } 6501 6502 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){ 6503 hci_connection_t * conn = hci_connection_for_handle(con_handle); 6504 if (!conn) return GAP_CONNECTION_INVALID; 6505 conn->qos_service_type = service_type; 6506 conn->qos_token_rate = token_rate; 6507 conn->qos_peak_bandwidth = peak_bandwidth; 6508 conn->qos_latency = latency; 6509 conn->qos_delay_variation = delay_variation; 6510 hci_run(); 6511 return ERROR_CODE_SUCCESS; 6512 } 6513 6514 void gap_set_page_scan_activity(uint16_t page_scan_interval, uint16_t page_scan_window){ 6515 hci_stack->new_page_scan_interval = page_scan_interval; 6516 hci_stack->new_page_scan_window = page_scan_window; 6517 hci_run(); 6518 } 6519 6520 void gap_set_page_scan_type(page_scan_type_t page_scan_type){ 6521 hci_stack->new_page_scan_type = (uint8_t) page_scan_type; 6522 hci_run(); 6523 } 6524 6525 #endif 6526 6527 void hci_halting_defer(void){ 6528 if (hci_stack->state != HCI_STATE_HALTING) return; 6529 switch (hci_stack->substate){ 6530 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER: 6531 case HCI_HALTING_CLOSE: 6532 hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER; 6533 break; 6534 default: 6535 break; 6536 } 6537 } 6538 6539 #ifdef ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION 6540 void hci_load_le_device_db_entry_into_resolving_list(uint16_t le_device_db_index){ 6541 if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return; 6542 if (le_device_db_index >= le_device_db_max_count()) return; 6543 uint8_t offset = le_device_db_index >> 3; 6544 uint8_t mask = 1 << (le_device_db_index & 7); 6545 hci_stack->le_resolving_list_add_entries[offset] |= mask; 6546 if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){ 6547 // note: go back to remove entries, otherwise, a remove + add will skip the add 6548 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 6549 } 6550 } 6551 6552 void hci_remove_le_device_db_entry_from_resolving_list(uint16_t le_device_db_index){ 6553 if (le_device_db_index >= MAX_NUM_RESOLVING_LIST_ENTRIES) return; 6554 if (le_device_db_index >= le_device_db_max_count()) return; 6555 uint8_t offset = le_device_db_index >> 3; 6556 uint8_t mask = 1 << (le_device_db_index & 7); 6557 hci_stack->le_resolving_list_remove_entries[offset] |= mask; 6558 if (hci_stack->le_resolving_list_state == LE_RESOLVING_LIST_DONE){ 6559 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_REMOVE_ENTRIES; 6560 } 6561 } 6562 6563 uint8_t gap_load_resolving_list_from_le_device_db(void){ 6564 if ((hci_stack->local_supported_commands[1] & (1 << 2)) == 0) { 6565 return ERROR_CODE_UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; 6566 } 6567 if (hci_stack->le_resolving_list_state != LE_RESOLVING_LIST_SEND_ENABLE_ADDRESS_RESOLUTION){ 6568 // restart le resolving list update 6569 hci_stack->le_resolving_list_state = LE_RESOLVING_LIST_READ_SIZE; 6570 } 6571 return ERROR_CODE_SUCCESS; 6572 } 6573 #endif 6574 6575 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION 6576 void hci_setup_test_connections_fuzz(void){ 6577 hci_connection_t * conn; 6578 6579 // default address: 66:55:44:33:00:01 6580 bd_addr_t addr = { 0x66, 0x55, 0x44, 0x33, 0x00, 0x00}; 6581 6582 // setup Controller info 6583 hci_stack->num_cmd_packets = 255; 6584 hci_stack->acl_packets_total_num = 255; 6585 6586 // setup incoming Classic ACL connection with con handle 0x0001, 66:55:44:33:22:01 6587 addr[5] = 0x01; 6588 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 6589 conn->con_handle = addr[5]; 6590 conn->role = HCI_ROLE_SLAVE; 6591 conn->state = RECEIVED_CONNECTION_REQUEST; 6592 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 6593 6594 // setup incoming Classic SCO connection with con handle 0x0002 6595 addr[5] = 0x02; 6596 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 6597 conn->con_handle = addr[5]; 6598 conn->role = HCI_ROLE_SLAVE; 6599 conn->state = RECEIVED_CONNECTION_REQUEST; 6600 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 6601 6602 // setup ready Classic ACL connection with con handle 0x0003 6603 addr[5] = 0x03; 6604 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); 6605 conn->con_handle = addr[5]; 6606 conn->role = HCI_ROLE_SLAVE; 6607 conn->state = OPEN; 6608 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 6609 6610 // setup ready Classic SCO connection with con handle 0x0004 6611 addr[5] = 0x04; 6612 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO); 6613 conn->con_handle = addr[5]; 6614 conn->role = HCI_ROLE_SLAVE; 6615 conn->state = OPEN; 6616 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 6617 6618 // setup ready LE ACL connection with con handle 0x005 and public address 6619 addr[5] = 0x05; 6620 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_LE_PUBLIC); 6621 conn->con_handle = addr[5]; 6622 conn->role = HCI_ROLE_SLAVE; 6623 conn->state = OPEN; 6624 conn->sm_connection.sm_role = HCI_ROLE_SLAVE; 6625 conn->sm_connection.sm_connection_encrypted = 1; 6626 } 6627 6628 void hci_free_connections_fuzz(void){ 6629 btstack_linked_list_iterator_t it; 6630 btstack_linked_list_iterator_init(&it, &hci_stack->connections); 6631 while (btstack_linked_list_iterator_has_next(&it)){ 6632 hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it); 6633 btstack_linked_list_iterator_remove(&it); 6634 btstack_memory_hci_connection_free(con); 6635 } 6636 } 6637 void hci_simulate_working_fuzz(void){ 6638 hci_init_done(); 6639 hci_stack->num_cmd_packets = 255; 6640 } 6641 #endif 6642