1 /* 2 * Copyright (C) 2009-2012 by Matthias Ringwald 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 MATTHIAS RINGWALD 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 [email protected] 34 * 35 */ 36 37 /* 38 * hci.c 39 * 40 * Created by Matthias Ringwald on 4/29/09. 41 * 42 */ 43 44 #include "btstack-config.h" 45 46 #include "hci.h" 47 #include "gap.h" 48 49 #include <stdarg.h> 50 #include <string.h> 51 #include <stdio.h> 52 53 #ifndef EMBEDDED 54 #include <unistd.h> // gethostbyname 55 #include <btstack/version.h> 56 #endif 57 58 #include "btstack_memory.h" 59 #include "debug.h" 60 #include "hci_dump.h" 61 62 #include <btstack/hci_cmds.h> 63 64 #define HCI_CONNECTION_TIMEOUT_MS 10000 65 66 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11 67 68 #ifdef USE_BLUETOOL 69 #include "../platforms/ios/src/bt_control_iphone.h" 70 #endif 71 72 static void hci_update_scan_enable(void); 73 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 74 static void hci_connection_timeout_handler(timer_source_t *timer); 75 static void hci_connection_timestamp(hci_connection_t *connection); 76 static int hci_power_control_on(void); 77 static void hci_power_control_off(void); 78 static void hci_state_reset(); 79 80 // the STACK is here 81 #ifndef HAVE_MALLOC 82 static hci_stack_t hci_stack_static; 83 #endif 84 static hci_stack_t * hci_stack = NULL; 85 86 // test helper 87 static uint8_t disable_l2cap_timeouts = 0; 88 89 /** 90 * create connection for given address 91 * 92 * @return connection OR NULL, if no memory left 93 */ 94 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){ 95 96 log_info("create_connection_for_addr %s", bd_addr_to_str(addr)); 97 hci_connection_t * conn = btstack_memory_hci_connection_get(); 98 if (!conn) return NULL; 99 BD_ADDR_COPY(conn->address, addr); 100 conn->address_type = addr_type; 101 conn->con_handle = 0xffff; 102 conn->authentication_flags = AUTH_FLAGS_NONE; 103 conn->bonding_flags = 0; 104 conn->requested_security_level = LEVEL_0; 105 linked_item_set_user(&conn->timeout.item, conn); 106 conn->timeout.process = hci_connection_timeout_handler; 107 hci_connection_timestamp(conn); 108 conn->acl_recombination_length = 0; 109 conn->acl_recombination_pos = 0; 110 conn->num_acl_packets_sent = 0; 111 linked_list_add(&hci_stack->connections, (linked_item_t *) conn); 112 return conn; 113 } 114 115 /** 116 * get connection for a given handle 117 * 118 * @return connection OR NULL, if not found 119 */ 120 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 121 linked_item_t *it; 122 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 123 if ( ((hci_connection_t *) it)->con_handle == con_handle){ 124 return (hci_connection_t *) it; 125 } 126 } 127 return NULL; 128 } 129 130 /** 131 * get connection for given address 132 * 133 * @return connection OR NULL, if not found 134 */ 135 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){ 136 linked_item_t *it; 137 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 138 hci_connection_t * connection = (hci_connection_t *) it; 139 if (connection->address_type != addr_type) continue; 140 if (memcmp(addr, connection->address, 6) != 0) continue; 141 return connection; 142 } 143 return NULL; 144 } 145 146 static void hci_connection_timeout_handler(timer_source_t *timer){ 147 hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item); 148 #ifdef HAVE_TIME 149 struct timeval tv; 150 gettimeofday(&tv, NULL); 151 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 152 // connections might be timed out 153 hci_emit_l2cap_check_timeout(connection); 154 } 155 #endif 156 #ifdef HAVE_TICK 157 if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 158 // connections might be timed out 159 hci_emit_l2cap_check_timeout(connection); 160 } 161 #endif 162 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 163 run_loop_add_timer(timer); 164 } 165 166 static void hci_connection_timestamp(hci_connection_t *connection){ 167 #ifdef HAVE_TIME 168 gettimeofday(&connection->timestamp, NULL); 169 #endif 170 #ifdef HAVE_TICK 171 connection->timestamp = embedded_get_ticks(); 172 #endif 173 } 174 175 176 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 177 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 178 } 179 180 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 181 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 182 } 183 184 185 /** 186 * add authentication flags and reset timer 187 * @note: assumes classic connection 188 */ 189 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 190 bd_addr_t addr; 191 bt_flip_addr(addr, *(bd_addr_t *) bd_addr); 192 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 193 if (conn) { 194 connectionSetAuthenticationFlags(conn, flags); 195 hci_connection_timestamp(conn); 196 } 197 } 198 199 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 200 hci_connection_t * conn = hci_connection_for_handle(handle); 201 if (!conn) return 0; 202 if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1; 203 if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1; 204 return 0; 205 } 206 207 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){ 208 if (hci_stack->remote_device_db) { 209 hci_stack->remote_device_db->delete_link_key(addr); 210 } 211 } 212 213 int hci_is_le_connection(hci_connection_t * connection){ 214 return connection->address_type == BD_ADDR_TYPE_LE_PUBLIC || 215 connection->address_type == BD_ADDR_TYPE_LE_RANDOM; 216 } 217 218 219 /** 220 * count connections 221 */ 222 static int nr_hci_connections(void){ 223 int count = 0; 224 linked_item_t *it; 225 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++); 226 return count; 227 } 228 229 /** 230 * Dummy handler called by HCI 231 */ 232 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 233 } 234 235 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){ 236 hci_connection_t * connection = hci_connection_for_handle(handle); 237 if (!connection) { 238 log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle); 239 return 0; 240 } 241 return connection->num_acl_packets_sent; 242 } 243 244 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){ 245 246 int num_packets_sent_classic = 0; 247 int num_packets_sent_le = 0; 248 249 bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN; 250 251 linked_item_t *it; 252 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 253 hci_connection_t * connection = (hci_connection_t *) it; 254 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){ 255 num_packets_sent_classic += connection->num_acl_packets_sent; 256 } else { 257 num_packets_sent_le += connection->num_acl_packets_sent; 258 } 259 if (connection->con_handle == con_handle){ 260 address_type = connection->address_type; 261 } 262 } 263 264 int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic; 265 int free_slots_le = 0; 266 267 if (free_slots_classic < 0){ 268 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); 269 return 0; 270 } 271 272 if (hci_stack->le_acl_packets_total_num){ 273 // if we have LE slots, they are used 274 free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le; 275 if (free_slots_le < 0){ 276 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); 277 return 0; 278 } 279 } else { 280 // otherwise, classic slots are used for LE, too 281 free_slots_classic -= num_packets_sent_le; 282 if (free_slots_classic < 0){ 283 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); 284 return 0; 285 } 286 } 287 288 switch (address_type){ 289 case BD_ADDR_TYPE_UNKNOWN: 290 log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle); 291 return 0; 292 293 case BD_ADDR_TYPE_CLASSIC: 294 return free_slots_classic; 295 296 default: 297 if (hci_stack->le_acl_packets_total_num){ 298 return free_slots_le; 299 } 300 return free_slots_classic; 301 } 302 } 303 304 305 // @deprecated 306 int hci_can_send_packet_now(uint8_t packet_type){ 307 switch (packet_type) { 308 case HCI_ACL_DATA_PACKET: 309 return hci_can_send_prepared_acl_packet_now(0); 310 case HCI_COMMAND_DATA_PACKET: 311 return hci_can_send_command_packet_now(); 312 default: 313 return 0; 314 } 315 } 316 317 // @deprecated 318 // same as hci_can_send_packet_now, but also checks if packet buffer is free for use 319 int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){ 320 321 if (hci_stack->hci_packet_buffer_reserved) return 0; 322 323 switch (packet_type) { 324 case HCI_ACL_DATA_PACKET: 325 return hci_can_send_acl_packet_now(0); 326 case HCI_COMMAND_DATA_PACKET: 327 return hci_can_send_command_packet_now(); 328 default: 329 return 0; 330 } 331 } 332 333 334 // new functions replacing hci_can_send_packet_now[_using_packet_buffer] 335 int hci_can_send_command_packet_now(void){ 336 if (hci_stack->hci_packet_buffer_reserved) return 0; 337 338 // check for async hci transport implementations 339 if (hci_stack->hci_transport->can_send_packet_now){ 340 if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){ 341 return 0; 342 } 343 } 344 345 return hci_stack->num_cmd_packets > 0; 346 } 347 348 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) { 349 // check for async hci transport implementations 350 if (hci_stack->hci_transport->can_send_packet_now){ 351 if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){ 352 return 0; 353 } 354 } 355 return hci_number_free_acl_slots_for_handle(con_handle) > 0; 356 } 357 358 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){ 359 if (hci_stack->hci_packet_buffer_reserved) return 0; 360 return hci_can_send_prepared_acl_packet_now(con_handle); 361 } 362 363 // used for internal checks in l2cap[-le].c 364 int hci_is_packet_buffer_reserved(void){ 365 return hci_stack->hci_packet_buffer_reserved; 366 } 367 368 // reserves outgoing packet buffer. @returns 1 if successful 369 int hci_reserve_packet_buffer(void){ 370 if (hci_stack->hci_packet_buffer_reserved) { 371 log_error("hci_reserve_packet_buffer called but buffer already reserved"); 372 return 0; 373 } 374 hci_stack->hci_packet_buffer_reserved = 1; 375 return 1; 376 } 377 378 void hci_release_packet_buffer(void){ 379 hci_stack->hci_packet_buffer_reserved = 0; 380 } 381 382 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 383 int hci_transport_synchronous(void){ 384 return hci_stack->hci_transport->can_send_packet_now == NULL; 385 } 386 387 static int hci_send_acl_packet_fragments(hci_connection_t *connection){ 388 389 // 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); 390 391 // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers 392 uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length; 393 if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){ 394 max_acl_data_packet_length = hci_stack->le_data_packets_length; 395 } 396 397 // testing: reduce buffer to minimum 398 // max_acl_data_packet_length = 52; 399 400 int err; 401 // multiple packets could be send on a synchronous HCI transport 402 while (1){ 403 404 // get current data 405 const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4; 406 int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos; 407 int more_fragments = 0; 408 409 // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length 410 if (current_acl_data_packet_length > max_acl_data_packet_length){ 411 more_fragments = 1; 412 current_acl_data_packet_length = max_acl_data_packet_length; 413 } 414 415 // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent) 416 if (acl_header_pos > 0){ 417 uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0); 418 handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12); 419 bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags); 420 } 421 422 // update header len 423 bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length); 424 425 // count packet 426 connection->num_acl_packets_sent++; 427 428 // send packet 429 uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos]; 430 const int size = current_acl_data_packet_length + 4; 431 // hexdump(packet, size); 432 err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 433 434 // done yet? 435 if (!more_fragments) break; 436 437 // update start of next fragment to send 438 hci_stack->acl_fragmentation_pos += current_acl_data_packet_length; 439 440 // can send more? 441 if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err; 442 } 443 444 // done 445 hci_stack->acl_fragmentation_pos = 0; 446 hci_stack->acl_fragmentation_total_size = 0; 447 448 // free buffer now for synchronous transport 449 if (!hci_transport_synchronous()){ 450 hci_release_packet_buffer(); 451 } 452 453 return err; 454 } 455 456 // pre: caller has reserved the packet buffer 457 int hci_send_acl_packet_buffer(int size){ 458 459 // log_info("hci_send_acl_packet_buffer size %u", size); 460 461 if (!hci_stack->hci_packet_buffer_reserved) { 462 log_error("hci_send_acl_packet_buffer called without reserving packet buffer"); 463 return 0; 464 } 465 466 uint8_t * packet = hci_stack->hci_packet_buffer; 467 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 468 469 // check for free places on Bluetooth module 470 if (!hci_can_send_prepared_acl_packet_now(con_handle)) { 471 log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller"); 472 hci_release_packet_buffer(); 473 return BTSTACK_ACL_BUFFERS_FULL; 474 } 475 476 hci_connection_t *connection = hci_connection_for_handle( con_handle); 477 if (!connection) { 478 log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle); 479 hci_release_packet_buffer(); 480 return 0; 481 } 482 hci_connection_timestamp(connection); 483 484 // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size); 485 486 // setup data 487 hci_stack->acl_fragmentation_total_size = size; 488 hci_stack->acl_fragmentation_pos = 4; // start of L2CAP packet 489 490 return hci_send_acl_packet_fragments(connection); 491 } 492 493 static void acl_handler(uint8_t *packet, int size){ 494 495 // log_info("acl_handler: size %u", size); 496 497 // get info 498 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 499 hci_connection_t *conn = hci_connection_for_handle(con_handle); 500 uint8_t acl_flags = READ_ACL_FLAGS(packet); 501 uint16_t acl_length = READ_ACL_LENGTH(packet); 502 503 // ignore non-registered handle 504 if (!conn){ 505 log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle); 506 return; 507 } 508 509 // assert packet is complete 510 if (acl_length + 4 != size){ 511 log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4); 512 return; 513 } 514 515 // update idle timestamp 516 hci_connection_timestamp(conn); 517 518 // handle different packet types 519 switch (acl_flags & 0x03) { 520 521 case 0x01: // continuation fragment 522 523 // sanity check 524 if (conn->acl_recombination_pos == 0) { 525 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle); 526 return; 527 } 528 529 // append fragment payload (header already stored) 530 memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length ); 531 conn->acl_recombination_pos += acl_length; 532 533 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length, 534 // conn->acl_recombination_pos, conn->acl_recombination_length); 535 536 // forward complete L2CAP packet if complete. 537 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 538 539 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos); 540 // reset recombination buffer 541 conn->acl_recombination_length = 0; 542 conn->acl_recombination_pos = 0; 543 } 544 break; 545 546 case 0x02: { // first fragment 547 548 // sanity check 549 if (conn->acl_recombination_pos) { 550 log_error( "ACL First Fragment but data in buffer for handle 0x%02x", con_handle); 551 return; 552 } 553 554 // peek into L2CAP packet! 555 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 556 557 // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length); 558 559 // compare fragment size to L2CAP packet size 560 if (acl_length >= l2cap_length + 4){ 561 562 // forward fragment as L2CAP packet 563 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 564 565 } else { 566 // store first fragment and tweak acl length for complete package 567 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4); 568 conn->acl_recombination_pos = acl_length + 4; 569 conn->acl_recombination_length = l2cap_length; 570 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4); 571 } 572 break; 573 574 } 575 default: 576 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03); 577 return; 578 } 579 580 // execute main loop 581 hci_run(); 582 } 583 584 static void hci_shutdown_connection(hci_connection_t *conn){ 585 log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address)); 586 587 run_loop_remove_timer(&conn->timeout); 588 589 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 590 btstack_memory_hci_connection_free( conn ); 591 592 // now it's gone 593 hci_emit_nr_connections_changed(); 594 } 595 596 static const uint16_t packet_type_sizes[] = { 597 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 598 HCI_ACL_DH1_SIZE, 0, 0, 0, 599 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 600 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 601 }; 602 static const uint8_t packet_type_feature_requirement_bit[] = { 603 0, // 3 slot packets 604 1, // 5 slot packets 605 25, // EDR 2 mpbs 606 26, // EDR 3 mbps 607 39, // 3 slot EDR packts 608 40, // 5 slot EDR packet 609 }; 610 static const uint16_t packet_type_feature_packet_mask[] = { 611 0x0f00, // 3 slot packets 612 0xf000, // 5 slot packets 613 0x1102, // EDR 2 mpbs 614 0x2204, // EDR 3 mbps 615 0x0300, // 3 slot EDR packts 616 0x3000, // 5 slot EDR packet 617 }; 618 619 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 620 // enable packet types based on size 621 uint16_t packet_types = 0; 622 int i; 623 for (i=0;i<16;i++){ 624 if (packet_type_sizes[i] == 0) continue; 625 if (packet_type_sizes[i] <= buffer_size){ 626 packet_types |= 1 << i; 627 } 628 } 629 // disable packet types due to missing local supported features 630 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 631 int bit_idx = packet_type_feature_requirement_bit[i]; 632 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 633 if (feature_set) continue; 634 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 635 packet_types &= ~packet_type_feature_packet_mask[i]; 636 } 637 // flip bits for "may not be used" 638 packet_types ^= 0x3306; 639 return packet_types; 640 } 641 642 uint16_t hci_usable_acl_packet_types(void){ 643 return hci_stack->packet_types; 644 } 645 646 uint8_t* hci_get_outgoing_packet_buffer(void){ 647 // hci packet buffer is >= acl data packet length 648 return hci_stack->hci_packet_buffer; 649 } 650 651 uint16_t hci_max_acl_data_packet_length(void){ 652 return hci_stack->acl_data_packet_length; 653 } 654 655 int hci_non_flushable_packet_boundary_flag_supported(void){ 656 // No. 54, byte 6, bit 6 657 return (hci_stack->local_supported_features[6] & (1 << 6)) != 0; 658 } 659 660 int hci_ssp_supported(void){ 661 // No. 51, byte 6, bit 3 662 return (hci_stack->local_supported_features[6] & (1 << 3)) != 0; 663 } 664 665 int hci_classic_supported(void){ 666 // No. 37, byte 4, bit 5, = No BR/EDR Support 667 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 668 } 669 670 int hci_le_supported(void){ 671 #ifdef HAVE_BLE 672 // No. 37, byte 4, bit 6 = LE Supported (Controller) 673 return (hci_stack->local_supported_features[4] & (1 << 6)) != 0; 674 #else 675 return 0; 676 #endif 677 } 678 679 // get addr type and address used in advertisement packets 680 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){ 681 *addr_type = hci_stack->adv_addr_type; 682 if (hci_stack->adv_addr_type){ 683 memcpy(addr, hci_stack->adv_address, 6); 684 } else { 685 memcpy(addr, hci_stack->local_bd_addr, 6); 686 } 687 } 688 689 #ifdef HAVE_BLE 690 void le_handle_advertisement_report(uint8_t *packet, int size){ 691 int offset = 3; 692 int num_reports = packet[offset]; 693 offset += 1; 694 695 int i; 696 log_info("HCI: handle adv report with num reports: %d", num_reports); 697 for (i=0; i<num_reports;i++){ 698 uint8_t data_length = packet[offset + 8]; 699 uint8_t event_size = 10 + data_length; 700 uint8_t event[2 + event_size ]; 701 int pos = 0; 702 event[pos++] = GAP_LE_ADVERTISING_REPORT; 703 event[pos++] = event_size; 704 memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address 705 offset += 8; 706 pos += 8; 707 event[pos++] = packet[offset + 1 + data_length]; // rssi 708 event[pos++] = packet[offset++]; //data_length; 709 memcpy(&event[pos], &packet[offset], data_length); 710 pos += data_length; 711 offset += data_length + 1; // rssi 712 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 713 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 714 } 715 } 716 #endif 717 718 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){ 719 uint8_t command_completed = 0; 720 if ((hci_stack->substate % 2) == 0) return; 721 // odd: waiting for event 722 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ 723 uint16_t opcode = READ_BT_16(packet,3); 724 if (opcode == hci_stack->last_cmd_opcode){ 725 command_completed = 1; 726 log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate); 727 } else { 728 log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 729 } 730 } 731 if (packet[0] == HCI_EVENT_COMMAND_STATUS){ 732 uint8_t status = packet[2]; 733 uint16_t opcode = READ_BT_16(packet,4); 734 if (opcode == hci_stack->last_cmd_opcode){ 735 if (status){ 736 command_completed = 1; 737 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate); 738 } else { 739 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode); 740 } 741 } else { 742 log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode); 743 } 744 } 745 746 if (!command_completed) return; 747 748 switch(hci_stack->substate >> 1){ 749 default: 750 hci_stack->substate++; 751 break; 752 } 753 } 754 755 static void hci_initializing_state_machine(){ 756 // log_info("hci_init: substate %u", hci_stack->substate); 757 if (hci_stack->substate % 2) { 758 // odd: waiting for command completion 759 return; 760 } 761 switch (hci_stack->substate >> 1){ 762 case 0: // RESET 763 hci_state_reset(); 764 765 hci_send_cmd(&hci_reset); 766 if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){ 767 // skip baud change 768 hci_stack->substate = 4; // >> 1 = 2 769 } 770 break; 771 case 1: // SEND BAUD CHANGE 772 hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer); 773 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 774 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 775 break; 776 case 2: // LOCAL BAUD CHANGE 777 log_info("Local baud rate change"); 778 hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main); 779 hci_stack->substate += 2; 780 // break missing here for fall through 781 782 case 3: 783 log_info("Custom init"); 784 // Custom initialization 785 if (hci_stack->control && hci_stack->control->next_cmd){ 786 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer); 787 if (valid_cmd){ 788 int size = 3 + hci_stack->hci_packet_buffer[2]; 789 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0); 790 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 791 hci_stack->substate = 4; // more init commands 792 break; 793 } 794 log_info("hci_run: init script done"); 795 } 796 // otherwise continue 797 hci_send_cmd(&hci_read_bd_addr); 798 break; 799 case 4: 800 hci_send_cmd(&hci_read_buffer_size); 801 break; 802 case 5: 803 hci_send_cmd(&hci_read_local_supported_features); 804 break; 805 case 6: 806 if (hci_le_supported()){ 807 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 808 } else { 809 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 810 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 811 } 812 813 // skip Classic init commands for LE only chipsets 814 if (!hci_classic_supported()){ 815 if (hci_le_supported()){ 816 hci_stack->substate = 11 << 1; // skip all classic command 817 } else { 818 log_error("Neither BR/EDR nor LE supported"); 819 hci_stack->substate = 14 << 1; // skip all 820 } 821 } 822 break; 823 case 7: 824 if (hci_ssp_supported()){ 825 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 826 break; 827 } 828 hci_stack->substate += 2; 829 // break missing here for fall through 830 831 case 8: 832 // ca. 15 sec 833 hci_send_cmd(&hci_write_page_timeout, 0x6000); 834 break; 835 case 9: 836 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 837 break; 838 case 10: 839 if (hci_stack->local_name){ 840 hci_send_cmd(&hci_write_local_name, hci_stack->local_name); 841 } else { 842 char hostname[30]; 843 #ifdef EMBEDDED 844 // BTstack-11:22:33:44:55:66 845 strcpy(hostname, "BTstack "); 846 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr)); 847 log_info("---> Name %s", hostname); 848 #else 849 // hostname for POSIX systems 850 gethostname(hostname, 30); 851 hostname[29] = '\0'; 852 #endif 853 hci_send_cmd(&hci_write_local_name, hostname); 854 } 855 break; 856 case 11: 857 hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan 858 if (!hci_le_supported()){ 859 // SKIP LE init for Classic only configuration 860 hci_stack->substate = 14 << 1; 861 } 862 break; 863 864 #ifdef HAVE_BLE 865 // LE INIT 866 case 12: 867 hci_send_cmd(&hci_le_read_buffer_size); 868 break; 869 case 13: 870 // LE Supported Host = 1, Simultaneous Host = 0 871 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 872 break; 873 case 14: 874 // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs 875 hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0); 876 break; 877 #endif 878 879 // DONE 880 case 15: 881 // done. 882 hci_stack->state = HCI_STATE_WORKING; 883 hci_emit_state(); 884 break; 885 default: 886 break; 887 } 888 hci_stack->substate++; 889 } 890 891 // avoid huge local variables 892 #ifndef EMBEDDED 893 static device_name_t device_name; 894 #endif 895 static void event_handler(uint8_t *packet, int size){ 896 897 uint16_t event_length = packet[1]; 898 899 // assert packet is complete 900 if (size != event_length + 2){ 901 log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2); 902 return; 903 } 904 905 bd_addr_t addr; 906 bd_addr_type_t addr_type; 907 uint8_t link_type; 908 hci_con_handle_t handle; 909 hci_connection_t * conn; 910 int i; 911 912 // log_info("HCI:EVENT:%02x", packet[0]); 913 914 switch (packet[0]) { 915 916 case HCI_EVENT_COMMAND_COMPLETE: 917 // get num cmd packets 918 // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]); 919 hci_stack->num_cmd_packets = packet[2]; 920 921 if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ 922 // from offset 5 923 // status 924 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 925 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6); 926 // ignore: SCO data packet len (8) 927 hci_stack->acl_packets_total_num = packet[9]; 928 // ignore: total num SCO packets 929 if (hci_stack->state == HCI_STATE_INITIALIZING){ 930 // determine usable ACL payload size 931 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){ 932 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 933 } 934 log_info("hci_read_buffer_size: used size %u, count %u", 935 hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num); 936 } 937 } 938 #ifdef HAVE_BLE 939 if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){ 940 hci_stack->le_data_packets_length = READ_BT_16(packet, 6); 941 hci_stack->le_acl_packets_total_num = packet[8]; 942 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num); 943 } 944 #endif 945 // Dump local address 946 if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { 947 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); 948 log_info("Local Address, Status: 0x%02x: Addr: %s", 949 packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 950 } 951 if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 952 hci_emit_discoverable_enabled(hci_stack->discoverable); 953 } 954 // Note: HCI init checks 955 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){ 956 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8); 957 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x", 958 hci_stack->local_supported_features[0], hci_stack->local_supported_features[1], 959 hci_stack->local_supported_features[2], hci_stack->local_supported_features[3], 960 hci_stack->local_supported_features[4], hci_stack->local_supported_features[5], 961 hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]); 962 963 // determine usable ACL packet types based buffer size and supported features 964 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(hci_stack->acl_data_packet_length, &hci_stack->local_supported_features[0]); 965 log_info("packet types %04x", hci_stack->packet_types); 966 967 // Classic/LE 968 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 969 } 970 break; 971 972 case HCI_EVENT_COMMAND_STATUS: 973 // get num cmd packets 974 // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]); 975 hci_stack->num_cmd_packets = packet[3]; 976 break; 977 978 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{ 979 int offset = 3; 980 for (i=0; i<packet[2];i++){ 981 handle = READ_BT_16(packet, offset); 982 offset += 2; 983 uint16_t num_packets = READ_BT_16(packet, offset); 984 offset += 2; 985 986 conn = hci_connection_for_handle(handle); 987 if (!conn){ 988 log_error("hci_number_completed_packet lists unused con handle %u", handle); 989 continue; 990 } 991 992 if (conn->num_acl_packets_sent >= num_packets){ 993 conn->num_acl_packets_sent -= num_packets; 994 } else { 995 log_error("hci_number_completed_packets, more slots freed then sent."); 996 conn->num_acl_packets_sent = 0; 997 } 998 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent); 999 } 1000 break; 1001 } 1002 case HCI_EVENT_CONNECTION_REQUEST: 1003 bt_flip_addr(addr, &packet[2]); 1004 // TODO: eval COD 8-10 1005 link_type = packet[11]; 1006 log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type); 1007 if (link_type == 1) { // ACL 1008 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1009 if (!conn) { 1010 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 1011 } 1012 if (!conn) { 1013 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 1014 hci_stack->decline_reason = 0x0d; 1015 BD_ADDR_COPY(hci_stack->decline_addr, addr); 1016 break; 1017 } 1018 conn->state = RECEIVED_CONNECTION_REQUEST; 1019 hci_run(); 1020 } else { 1021 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A) 1022 hci_stack->decline_reason = 0x0a; 1023 BD_ADDR_COPY(hci_stack->decline_addr, addr); 1024 } 1025 break; 1026 1027 case HCI_EVENT_CONNECTION_COMPLETE: 1028 // Connection management 1029 bt_flip_addr(addr, &packet[5]); 1030 log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr)); 1031 addr_type = BD_ADDR_TYPE_CLASSIC; 1032 conn = hci_connection_for_bd_addr_and_type(&addr, addr_type); 1033 if (conn) { 1034 if (!packet[2]){ 1035 conn->state = OPEN; 1036 conn->con_handle = READ_BT_16(packet, 3); 1037 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES; 1038 1039 // restart timer 1040 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 1041 run_loop_add_timer(&conn->timeout); 1042 1043 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 1044 1045 hci_emit_nr_connections_changed(); 1046 } else { 1047 int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED; 1048 uint8_t status = packet[2]; 1049 bd_addr_t bd_address; 1050 memcpy(&bd_address, conn->address, 6); 1051 1052 // connection failed, remove entry 1053 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 1054 btstack_memory_hci_connection_free( conn ); 1055 1056 // notify client if dedicated bonding 1057 if (notify_dedicated_bonding_failed){ 1058 log_info("hci notify_dedicated_bonding_failed"); 1059 hci_emit_dedicated_bonding_result(bd_address, status); 1060 } 1061 1062 // if authentication error, also delete link key 1063 if (packet[2] == 0x05) { 1064 hci_drop_link_key_for_bd_addr(&addr); 1065 } 1066 } 1067 } 1068 break; 1069 1070 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 1071 handle = READ_BT_16(packet, 3); 1072 conn = hci_connection_for_handle(handle); 1073 if (!conn) break; 1074 if (!packet[2]){ 1075 uint8_t * features = &packet[5]; 1076 if (features[6] & (1 << 3)){ 1077 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP; 1078 } 1079 } 1080 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 1081 log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags); 1082 if (conn->bonding_flags & BONDING_DEDICATED){ 1083 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 1084 } 1085 break; 1086 1087 case HCI_EVENT_LINK_KEY_REQUEST: 1088 log_info("HCI_EVENT_LINK_KEY_REQUEST"); 1089 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 1090 // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST 1091 if (hci_stack->bondable && !hci_stack->remote_device_db) break; 1092 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 1093 hci_run(); 1094 // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set 1095 return; 1096 1097 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 1098 bt_flip_addr(addr, &packet[2]); 1099 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1100 if (!conn) break; 1101 conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION; 1102 link_key_type_t link_key_type = (link_key_type_t)packet[24]; 1103 // Change Connection Encryption keeps link key type 1104 if (link_key_type != CHANGED_COMBINATION_KEY){ 1105 conn->link_key_type = link_key_type; 1106 } 1107 if (!hci_stack->remote_device_db) break; 1108 hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type); 1109 // still forward event to allow dismiss of pairing dialog 1110 break; 1111 } 1112 1113 case HCI_EVENT_PIN_CODE_REQUEST: 1114 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE); 1115 // non-bondable mode: pin code negative reply will be sent 1116 if (!hci_stack->bondable){ 1117 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST); 1118 hci_run(); 1119 return; 1120 } 1121 // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key 1122 if (!hci_stack->remote_device_db) break; 1123 bt_flip_addr(addr, &packet[2]); 1124 hci_stack->remote_device_db->delete_link_key(&addr); 1125 break; 1126 1127 case HCI_EVENT_IO_CAPABILITY_REQUEST: 1128 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST); 1129 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY); 1130 break; 1131 1132 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 1133 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 1134 if (!hci_stack->ssp_auto_accept) break; 1135 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY); 1136 break; 1137 1138 case HCI_EVENT_USER_PASSKEY_REQUEST: 1139 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 1140 if (!hci_stack->ssp_auto_accept) break; 1141 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY); 1142 break; 1143 1144 case HCI_EVENT_ENCRYPTION_CHANGE: 1145 handle = READ_BT_16(packet, 3); 1146 conn = hci_connection_for_handle(handle); 1147 if (!conn) break; 1148 if (packet[2] == 0) { 1149 if (packet[5]){ 1150 conn->authentication_flags |= CONNECTION_ENCRYPTED; 1151 } else { 1152 conn->authentication_flags &= ~CONNECTION_ENCRYPTED; 1153 } 1154 } 1155 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 1156 break; 1157 1158 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 1159 handle = READ_BT_16(packet, 3); 1160 conn = hci_connection_for_handle(handle); 1161 if (!conn) break; 1162 1163 // dedicated bonding: send result and disconnect 1164 if (conn->bonding_flags & BONDING_DEDICATED){ 1165 conn->bonding_flags &= ~BONDING_DEDICATED; 1166 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 1167 conn->bonding_status = packet[2]; 1168 break; 1169 } 1170 1171 if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){ 1172 // link key sufficient for requested security 1173 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 1174 break; 1175 } 1176 // not enough 1177 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 1178 break; 1179 1180 #ifndef EMBEDDED 1181 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 1182 if (!hci_stack->remote_device_db) break; 1183 if (packet[2]) break; // status not ok 1184 bt_flip_addr(addr, &packet[3]); 1185 // fix for invalid remote names - terminate on 0xff 1186 for (i=0; i<248;i++){ 1187 if (packet[9+i] == 0xff){ 1188 packet[9+i] = 0; 1189 break; 1190 } 1191 } 1192 memset(&device_name, 0, sizeof(device_name_t)); 1193 strncpy((char*) device_name, (char*) &packet[9], 248); 1194 hci_stack->remote_device_db->put_name(&addr, &device_name); 1195 break; 1196 1197 case HCI_EVENT_INQUIRY_RESULT: 1198 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{ 1199 if (!hci_stack->remote_device_db) break; 1200 // first send inq result packet 1201 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 1202 // then send cached remote names 1203 int offset = 3; 1204 for (i=0; i<packet[2];i++){ 1205 bt_flip_addr(addr, &packet[offset]); 1206 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2; 1207 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){ 1208 hci_emit_remote_name_cached(&addr, &device_name); 1209 } 1210 } 1211 return; 1212 } 1213 #endif 1214 1215 // HCI_EVENT_DISCONNECTION_COMPLETE 1216 // has been moved down, to first notify stack before shutting connection down 1217 1218 case HCI_EVENT_HARDWARE_ERROR: 1219 if(hci_stack->control && hci_stack->control->hw_error){ 1220 (*hci_stack->control->hw_error)(); 1221 } else { 1222 // if no special requests, just reboot stack 1223 hci_power_control_off(); 1224 hci_power_control_on(); 1225 } 1226 break; 1227 1228 case DAEMON_EVENT_HCI_PACKET_SENT: 1229 // free packet buffer for asynchronous transport 1230 if (hci_transport_synchronous()) break; 1231 hci_stack->hci_packet_buffer_reserved = 0; 1232 break; 1233 1234 #ifdef HAVE_BLE 1235 case HCI_EVENT_LE_META: 1236 switch (packet[2]){ 1237 case HCI_SUBEVENT_LE_ADVERTISING_REPORT: 1238 log_info("advertising report received"); 1239 if (hci_stack->le_scanning_state != LE_SCANNING) break; 1240 le_handle_advertisement_report(packet, size); 1241 break; 1242 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 1243 // Connection management 1244 bt_flip_addr(addr, &packet[8]); 1245 addr_type = (bd_addr_type_t)packet[7]; 1246 log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr)); 1247 // LE connections are auto-accepted, so just create a connection if there isn't one already 1248 conn = hci_connection_for_bd_addr_and_type(&addr, addr_type); 1249 if (packet[3]){ 1250 if (conn){ 1251 // outgoing connection failed, remove entry 1252 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 1253 btstack_memory_hci_connection_free( conn ); 1254 } 1255 // if authentication error, also delete link key 1256 if (packet[3] == 0x05) { 1257 hci_drop_link_key_for_bd_addr(&addr); 1258 } 1259 break; 1260 } 1261 if (!conn){ 1262 conn = create_connection_for_bd_addr_and_type(addr, addr_type); 1263 } 1264 if (!conn){ 1265 // no memory 1266 break; 1267 } 1268 1269 conn->state = OPEN; 1270 conn->con_handle = READ_BT_16(packet, 4); 1271 1272 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 1273 1274 // restart timer 1275 // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 1276 // run_loop_add_timer(&conn->timeout); 1277 1278 log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address)); 1279 1280 hci_emit_nr_connections_changed(); 1281 break; 1282 1283 // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]); 1284 1285 default: 1286 break; 1287 } 1288 break; 1289 #endif 1290 default: 1291 break; 1292 } 1293 1294 // handle BT initialization 1295 if (hci_stack->state == HCI_STATE_INITIALIZING){ 1296 hci_initializing_event_handler(packet, size); 1297 } 1298 1299 // help with BT sleep 1300 if (hci_stack->state == HCI_STATE_FALLING_ASLEEP 1301 && hci_stack->substate == 1 1302 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 1303 hci_stack->substate++; 1304 } 1305 1306 // notify upper stack 1307 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 1308 1309 // moved here to give upper stack a chance to close down everything with hci_connection_t intact 1310 if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){ 1311 if (!packet[2]){ 1312 handle = READ_BT_16(packet, 3); 1313 hci_connection_t * conn = hci_connection_for_handle(handle); 1314 if (conn) { 1315 uint8_t status = conn->bonding_status; 1316 bd_addr_t bd_address; 1317 memcpy(&bd_address, conn->address, 6); 1318 hci_shutdown_connection(conn); 1319 if (conn->bonding_flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){ 1320 hci_emit_dedicated_bonding_result(bd_address, status); 1321 } 1322 } 1323 } 1324 } 1325 1326 // execute main loop 1327 hci_run(); 1328 } 1329 1330 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 1331 switch (packet_type) { 1332 case HCI_EVENT_PACKET: 1333 event_handler(packet, size); 1334 break; 1335 case HCI_ACL_DATA_PACKET: 1336 acl_handler(packet, size); 1337 break; 1338 default: 1339 break; 1340 } 1341 } 1342 1343 /** Register HCI packet handlers */ 1344 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 1345 hci_stack->packet_handler = handler; 1346 } 1347 1348 static void hci_state_reset(){ 1349 // no connections yet 1350 hci_stack->connections = NULL; 1351 1352 // keep discoverable/connectable as this has been requested by the client(s) 1353 // hci_stack->discoverable = 0; 1354 // hci_stack->connectable = 0; 1355 // hci_stack->bondable = 1; 1356 1357 // buffer is free 1358 hci_stack->hci_packet_buffer_reserved = 0; 1359 1360 // no pending cmds 1361 hci_stack->decline_reason = 0; 1362 hci_stack->new_scan_enable_value = 0xff; 1363 1364 // LE 1365 hci_stack->adv_addr_type = 0; 1366 memset(hci_stack->adv_address, 0, 6); 1367 hci_stack->le_scanning_state = LE_SCAN_IDLE; 1368 hci_stack->le_scan_type = 0xff; 1369 } 1370 1371 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){ 1372 1373 #ifdef HAVE_MALLOC 1374 if (!hci_stack) { 1375 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 1376 } 1377 #else 1378 hci_stack = &hci_stack_static; 1379 #endif 1380 memset(hci_stack, 0, sizeof(hci_stack_t)); 1381 1382 // reference to use transport layer implementation 1383 hci_stack->hci_transport = transport; 1384 1385 // references to used control implementation 1386 hci_stack->control = control; 1387 1388 // reference to used config 1389 hci_stack->config = config; 1390 1391 // higher level handler 1392 hci_stack->packet_handler = dummy_handler; 1393 1394 // store and open remote device db 1395 hci_stack->remote_device_db = remote_device_db; 1396 if (hci_stack->remote_device_db) { 1397 hci_stack->remote_device_db->open(); 1398 } 1399 1400 // max acl payload size defined in config.h 1401 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 1402 1403 // register packet handlers with transport 1404 transport->register_packet_handler(&packet_handler); 1405 1406 hci_stack->state = HCI_STATE_OFF; 1407 1408 // class of device 1409 hci_stack->class_of_device = 0x007a020c; // Smartphone 1410 1411 // bondable by default 1412 hci_stack->bondable = 1; 1413 1414 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 1415 hci_stack->ssp_enable = 1; 1416 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 1417 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 1418 hci_stack->ssp_auto_accept = 1; 1419 1420 hci_state_reset(); 1421 } 1422 1423 void hci_close(){ 1424 // close remote device db 1425 if (hci_stack->remote_device_db) { 1426 hci_stack->remote_device_db->close(); 1427 } 1428 while (hci_stack->connections) { 1429 // cancel all l2cap connections 1430 hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host 1431 hci_shutdown_connection((hci_connection_t *) hci_stack->connections); 1432 } 1433 hci_power_control(HCI_POWER_OFF); 1434 1435 #ifdef HAVE_MALLOC 1436 free(hci_stack); 1437 #endif 1438 hci_stack = NULL; 1439 } 1440 1441 void hci_set_class_of_device(uint32_t class_of_device){ 1442 hci_stack->class_of_device = class_of_device; 1443 } 1444 1445 void hci_disable_l2cap_timeout_check(){ 1446 disable_l2cap_timeouts = 1; 1447 } 1448 // State-Module-Driver overview 1449 // state module low-level 1450 // HCI_STATE_OFF off close 1451 // HCI_STATE_INITIALIZING, on open 1452 // HCI_STATE_WORKING, on open 1453 // HCI_STATE_HALTING, on open 1454 // HCI_STATE_SLEEPING, off/sleep close 1455 // HCI_STATE_FALLING_ASLEEP on open 1456 1457 static int hci_power_control_on(void){ 1458 1459 // power on 1460 int err = 0; 1461 if (hci_stack->control && hci_stack->control->on){ 1462 err = (*hci_stack->control->on)(hci_stack->config); 1463 } 1464 if (err){ 1465 log_error( "POWER_ON failed"); 1466 hci_emit_hci_open_failed(); 1467 return err; 1468 } 1469 1470 // open low-level device 1471 err = hci_stack->hci_transport->open(hci_stack->config); 1472 if (err){ 1473 log_error( "HCI_INIT failed, turning Bluetooth off again"); 1474 if (hci_stack->control && hci_stack->control->off){ 1475 (*hci_stack->control->off)(hci_stack->config); 1476 } 1477 hci_emit_hci_open_failed(); 1478 return err; 1479 } 1480 return 0; 1481 } 1482 1483 static void hci_power_control_off(void){ 1484 1485 log_info("hci_power_control_off"); 1486 1487 // close low-level device 1488 hci_stack->hci_transport->close(hci_stack->config); 1489 1490 log_info("hci_power_control_off - hci_transport closed"); 1491 1492 // power off 1493 if (hci_stack->control && hci_stack->control->off){ 1494 (*hci_stack->control->off)(hci_stack->config); 1495 } 1496 1497 log_info("hci_power_control_off - control closed"); 1498 1499 hci_stack->state = HCI_STATE_OFF; 1500 } 1501 1502 static void hci_power_control_sleep(void){ 1503 1504 log_info("hci_power_control_sleep"); 1505 1506 #if 0 1507 // don't close serial port during sleep 1508 1509 // close low-level device 1510 hci_stack->hci_transport->close(hci_stack->config); 1511 #endif 1512 1513 // sleep mode 1514 if (hci_stack->control && hci_stack->control->sleep){ 1515 (*hci_stack->control->sleep)(hci_stack->config); 1516 } 1517 1518 hci_stack->state = HCI_STATE_SLEEPING; 1519 } 1520 1521 static int hci_power_control_wake(void){ 1522 1523 log_info("hci_power_control_wake"); 1524 1525 // wake on 1526 if (hci_stack->control && hci_stack->control->wake){ 1527 (*hci_stack->control->wake)(hci_stack->config); 1528 } 1529 1530 #if 0 1531 // open low-level device 1532 int err = hci_stack->hci_transport->open(hci_stack->config); 1533 if (err){ 1534 log_error( "HCI_INIT failed, turning Bluetooth off again"); 1535 if (hci_stack->control && hci_stack->control->off){ 1536 (*hci_stack->control->off)(hci_stack->config); 1537 } 1538 hci_emit_hci_open_failed(); 1539 return err; 1540 } 1541 #endif 1542 1543 return 0; 1544 } 1545 1546 static void hci_power_transition_to_initializing(void){ 1547 // set up state machine 1548 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 1549 hci_stack->hci_packet_buffer_reserved = 0; 1550 hci_stack->state = HCI_STATE_INITIALIZING; 1551 hci_stack->substate = 0; 1552 } 1553 1554 int hci_power_control(HCI_POWER_MODE power_mode){ 1555 1556 log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state); 1557 1558 int err = 0; 1559 switch (hci_stack->state){ 1560 1561 case HCI_STATE_OFF: 1562 switch (power_mode){ 1563 case HCI_POWER_ON: 1564 err = hci_power_control_on(); 1565 if (err) { 1566 log_error("hci_power_control_on() error %u", err); 1567 return err; 1568 } 1569 hci_power_transition_to_initializing(); 1570 break; 1571 case HCI_POWER_OFF: 1572 // do nothing 1573 break; 1574 case HCI_POWER_SLEEP: 1575 // do nothing (with SLEEP == OFF) 1576 break; 1577 } 1578 break; 1579 1580 case HCI_STATE_INITIALIZING: 1581 switch (power_mode){ 1582 case HCI_POWER_ON: 1583 // do nothing 1584 break; 1585 case HCI_POWER_OFF: 1586 // no connections yet, just turn it off 1587 hci_power_control_off(); 1588 break; 1589 case HCI_POWER_SLEEP: 1590 // no connections yet, just turn it off 1591 hci_power_control_sleep(); 1592 break; 1593 } 1594 break; 1595 1596 case HCI_STATE_WORKING: 1597 switch (power_mode){ 1598 case HCI_POWER_ON: 1599 // do nothing 1600 break; 1601 case HCI_POWER_OFF: 1602 // see hci_run 1603 hci_stack->state = HCI_STATE_HALTING; 1604 break; 1605 case HCI_POWER_SLEEP: 1606 // see hci_run 1607 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1608 hci_stack->substate = 0; 1609 break; 1610 } 1611 break; 1612 1613 case HCI_STATE_HALTING: 1614 switch (power_mode){ 1615 case HCI_POWER_ON: 1616 hci_power_transition_to_initializing(); 1617 break; 1618 case HCI_POWER_OFF: 1619 // do nothing 1620 break; 1621 case HCI_POWER_SLEEP: 1622 // see hci_run 1623 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1624 hci_stack->substate = 0; 1625 break; 1626 } 1627 break; 1628 1629 case HCI_STATE_FALLING_ASLEEP: 1630 switch (power_mode){ 1631 case HCI_POWER_ON: 1632 1633 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1634 // nothing to do, if H4 supports power management 1635 if (bt_control_iphone_power_management_enabled()){ 1636 hci_stack->state = HCI_STATE_INITIALIZING; 1637 hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1638 break; 1639 } 1640 #endif 1641 hci_power_transition_to_initializing(); 1642 break; 1643 case HCI_POWER_OFF: 1644 // see hci_run 1645 hci_stack->state = HCI_STATE_HALTING; 1646 break; 1647 case HCI_POWER_SLEEP: 1648 // do nothing 1649 break; 1650 } 1651 break; 1652 1653 case HCI_STATE_SLEEPING: 1654 switch (power_mode){ 1655 case HCI_POWER_ON: 1656 1657 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1658 // nothing to do, if H4 supports power management 1659 if (bt_control_iphone_power_management_enabled()){ 1660 hci_stack->state = HCI_STATE_INITIALIZING; 1661 hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1662 hci_update_scan_enable(); 1663 break; 1664 } 1665 #endif 1666 err = hci_power_control_wake(); 1667 if (err) return err; 1668 hci_power_transition_to_initializing(); 1669 break; 1670 case HCI_POWER_OFF: 1671 hci_stack->state = HCI_STATE_HALTING; 1672 break; 1673 case HCI_POWER_SLEEP: 1674 // do nothing 1675 break; 1676 } 1677 break; 1678 } 1679 1680 // create internal event 1681 hci_emit_state(); 1682 1683 // trigger next/first action 1684 hci_run(); 1685 1686 return 0; 1687 } 1688 1689 static void hci_update_scan_enable(void){ 1690 // 2 = page scan, 1 = inq scan 1691 hci_stack->new_scan_enable_value = hci_stack->connectable << 1 | hci_stack->discoverable; 1692 hci_run(); 1693 } 1694 1695 void hci_discoverable_control(uint8_t enable){ 1696 if (enable) enable = 1; // normalize argument 1697 1698 if (hci_stack->discoverable == enable){ 1699 hci_emit_discoverable_enabled(hci_stack->discoverable); 1700 return; 1701 } 1702 1703 hci_stack->discoverable = enable; 1704 hci_update_scan_enable(); 1705 } 1706 1707 void hci_connectable_control(uint8_t enable){ 1708 if (enable) enable = 1; // normalize argument 1709 1710 // don't emit event 1711 if (hci_stack->connectable == enable) return; 1712 1713 hci_stack->connectable = enable; 1714 hci_update_scan_enable(); 1715 } 1716 1717 bd_addr_t * hci_local_bd_addr(void){ 1718 return &hci_stack->local_bd_addr; 1719 } 1720 1721 void hci_run(){ 1722 1723 hci_connection_t * connection; 1724 linked_item_t * it; 1725 1726 if (!hci_can_send_command_packet_now()) return; 1727 1728 // global/non-connection oriented commands 1729 1730 // decline incoming connections 1731 if (hci_stack->decline_reason){ 1732 uint8_t reason = hci_stack->decline_reason; 1733 hci_stack->decline_reason = 0; 1734 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 1735 return; 1736 } 1737 1738 // send scan enable 1739 if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){ 1740 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 1741 hci_stack->new_scan_enable_value = 0xff; 1742 return; 1743 } 1744 1745 #ifdef HAVE_BLE 1746 // handle le scan 1747 if (hci_stack->state == HCI_STATE_WORKING){ 1748 switch(hci_stack->le_scanning_state){ 1749 case LE_START_SCAN: 1750 hci_stack->le_scanning_state = LE_SCANNING; 1751 hci_send_cmd(&hci_le_set_scan_enable, 1, 0); 1752 return; 1753 1754 case LE_STOP_SCAN: 1755 hci_stack->le_scanning_state = LE_SCAN_IDLE; 1756 hci_send_cmd(&hci_le_set_scan_enable, 0, 0); 1757 return; 1758 default: 1759 break; 1760 } 1761 if (hci_stack->le_scan_type != 0xff){ 1762 // defaults: active scanning, accept all advertisement packets 1763 int scan_type = hci_stack->le_scan_type; 1764 hci_stack->le_scan_type = 0xff; 1765 hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->adv_addr_type, 0); 1766 return; 1767 } 1768 } 1769 #endif 1770 1771 // send pending HCI commands 1772 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 1773 connection = (hci_connection_t *) it; 1774 1775 switch(connection->state){ 1776 case SEND_CREATE_CONNECTION: 1777 switch(connection->address_type){ 1778 case BD_ADDR_TYPE_CLASSIC: 1779 log_info("sending hci_create_connection"); 1780 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 1781 break; 1782 default: 1783 #ifdef HAVE_BLE 1784 log_info("sending hci_le_create_connection"); 1785 hci_send_cmd(&hci_le_create_connection, 1786 0x0060, // scan interval: 60 ms 1787 0x0030, // scan interval: 30 ms 1788 0, // don't use whitelist 1789 connection->address_type, // peer address type 1790 connection->address, // peer bd addr 1791 hci_stack->adv_addr_type, // our addr type: 1792 0x0008, // conn interval min 1793 0x0018, // conn interval max 1794 0, // conn latency 1795 0x0048, // supervision timeout 1796 0x0001, // min ce length 1797 0x0001 // max ce length 1798 ); 1799 1800 connection->state = SENT_CREATE_CONNECTION; 1801 #endif 1802 break; 1803 } 1804 return; 1805 1806 case RECEIVED_CONNECTION_REQUEST: 1807 log_info("sending hci_accept_connection_request"); 1808 connection->state = ACCEPTED_CONNECTION_REQUEST; 1809 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 1810 return; 1811 1812 #ifdef HAVE_BLE 1813 case SEND_CANCEL_CONNECTION: 1814 connection->state = SENT_CANCEL_CONNECTION; 1815 hci_send_cmd(&hci_le_create_connection_cancel); 1816 return; 1817 #endif 1818 case SEND_DISCONNECT: 1819 connection->state = SENT_DISCONNECT; 1820 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1821 return; 1822 1823 default: 1824 break; 1825 } 1826 1827 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 1828 log_info("responding to link key request"); 1829 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 1830 link_key_t link_key; 1831 link_key_type_t link_key_type; 1832 if ( hci_stack->remote_device_db 1833 && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type) 1834 && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){ 1835 connection->link_key_type = link_key_type; 1836 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 1837 } else { 1838 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 1839 } 1840 return; 1841 } 1842 1843 if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){ 1844 log_info("denying to pin request"); 1845 connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST); 1846 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 1847 return; 1848 } 1849 1850 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 1851 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 1852 log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability); 1853 if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){ 1854 // tweak authentication requirements 1855 uint8_t authreq = hci_stack->ssp_authentication_requirement; 1856 if (connection->bonding_flags & BONDING_DEDICATED){ 1857 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 1858 } 1859 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 1860 authreq |= 1; 1861 } 1862 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq); 1863 } else { 1864 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 1865 } 1866 return; 1867 } 1868 1869 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 1870 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 1871 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 1872 return; 1873 } 1874 1875 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 1876 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 1877 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 1878 return; 1879 } 1880 1881 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){ 1882 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES; 1883 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 1884 return; 1885 } 1886 1887 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 1888 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 1889 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005); // authentication failure 1890 return; 1891 } 1892 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 1893 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 1894 connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT; 1895 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // authentication done 1896 return; 1897 } 1898 if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){ 1899 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 1900 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 1901 return; 1902 } 1903 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 1904 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 1905 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 1906 return; 1907 } 1908 #ifdef HAVE_BLE 1909 if (connection->le_conn_interval_min){ 1910 uint16_t connection_interval_min = connection->le_conn_interval_min; 1911 connection->le_conn_interval_min = 0; 1912 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min, 1913 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout, 1914 0x0000, 0xffff); 1915 } 1916 #endif 1917 } 1918 1919 // send continuation fragments 1920 if (hci_stack->acl_fragmentation_total_size > 0) { 1921 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer); 1922 if (hci_can_send_prepared_acl_packet_now(con_handle)){ 1923 hci_connection_t *connection = hci_connection_for_handle(con_handle); 1924 if (connection) { 1925 hci_send_acl_packet_fragments(connection); 1926 return; 1927 } 1928 // connection gone -> discard further fragments 1929 hci_stack->acl_fragmentation_total_size = 0; 1930 hci_stack->acl_fragmentation_pos = 0; 1931 } 1932 } 1933 1934 switch (hci_stack->state){ 1935 case HCI_STATE_INITIALIZING: 1936 hci_initializing_state_machine(); 1937 break; 1938 1939 case HCI_STATE_HALTING: 1940 1941 log_info("HCI_STATE_HALTING"); 1942 // close all open connections 1943 connection = (hci_connection_t *) hci_stack->connections; 1944 if (connection){ 1945 1946 // send disconnect 1947 if (!hci_can_send_command_packet_now()) return; 1948 1949 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 1950 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1951 1952 // send disconnected event right away - causes higher layer connections to get closed, too. 1953 hci_shutdown_connection(connection); 1954 return; 1955 } 1956 log_info("HCI_STATE_HALTING, calling off"); 1957 1958 // switch mode 1959 hci_power_control_off(); 1960 1961 log_info("HCI_STATE_HALTING, emitting state"); 1962 hci_emit_state(); 1963 log_info("HCI_STATE_HALTING, done"); 1964 break; 1965 1966 case HCI_STATE_FALLING_ASLEEP: 1967 switch(hci_stack->substate) { 1968 case 0: 1969 log_info("HCI_STATE_FALLING_ASLEEP"); 1970 // close all open connections 1971 connection = (hci_connection_t *) hci_stack->connections; 1972 1973 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1974 // don't close connections, if H4 supports power management 1975 if (bt_control_iphone_power_management_enabled()){ 1976 connection = NULL; 1977 } 1978 #endif 1979 if (connection){ 1980 1981 // send disconnect 1982 if (!hci_can_send_command_packet_now()) return; 1983 1984 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle); 1985 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1986 1987 // send disconnected event right away - causes higher layer connections to get closed, too. 1988 hci_shutdown_connection(connection); 1989 return; 1990 } 1991 1992 if (hci_classic_supported()){ 1993 // disable page and inquiry scan 1994 if (!hci_can_send_command_packet_now()) return; 1995 1996 log_info("HCI_STATE_HALTING, disabling inq scans"); 1997 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 1998 1999 // continue in next sub state 2000 hci_stack->substate++; 2001 break; 2002 } 2003 // fall through for ble-only chips 2004 2005 case 2: 2006 log_info("HCI_STATE_HALTING, calling sleep"); 2007 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 2008 // don't actually go to sleep, if H4 supports power management 2009 if (bt_control_iphone_power_management_enabled()){ 2010 // SLEEP MODE reached 2011 hci_stack->state = HCI_STATE_SLEEPING; 2012 hci_emit_state(); 2013 break; 2014 } 2015 #endif 2016 // switch mode 2017 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 2018 hci_emit_state(); 2019 break; 2020 2021 default: 2022 break; 2023 } 2024 break; 2025 2026 default: 2027 break; 2028 } 2029 } 2030 2031 int hci_send_cmd_packet(uint8_t *packet, int size){ 2032 bd_addr_t addr; 2033 hci_connection_t * conn; 2034 // house-keeping 2035 2036 // create_connection? 2037 if (IS_COMMAND(packet, hci_create_connection)){ 2038 bt_flip_addr(addr, &packet[3]); 2039 log_info("Create_connection to %s", bd_addr_to_str(addr)); 2040 2041 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 2042 if (!conn){ 2043 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 2044 if (!conn){ 2045 // notify client that alloc failed 2046 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 2047 return 0; // don't sent packet to controller 2048 } 2049 conn->state = SEND_CREATE_CONNECTION; 2050 } 2051 log_info("conn state %u", conn->state); 2052 switch (conn->state){ 2053 // if connection active exists 2054 case OPEN: 2055 // and OPEN, emit connection complete command, don't send to controller 2056 hci_emit_connection_complete(conn, 0); 2057 return 0; 2058 case SEND_CREATE_CONNECTION: 2059 // connection created by hci, e.g. dedicated bonding 2060 break; 2061 default: 2062 // otherwise, just ignore as it is already in the open process 2063 return 0; 2064 } 2065 conn->state = SENT_CREATE_CONNECTION; 2066 } 2067 2068 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 2069 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 2070 } 2071 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 2072 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 2073 } 2074 2075 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 2076 if (hci_stack->remote_device_db){ 2077 bt_flip_addr(addr, &packet[3]); 2078 hci_stack->remote_device_db->delete_link_key(&addr); 2079 } 2080 } 2081 2082 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply) 2083 || IS_COMMAND(packet, hci_pin_code_request_reply)){ 2084 bt_flip_addr(addr, &packet[3]); 2085 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 2086 if (conn){ 2087 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 2088 } 2089 } 2090 2091 if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply) 2092 || IS_COMMAND(packet, hci_user_confirmation_request_reply) 2093 || IS_COMMAND(packet, hci_user_passkey_request_negative_reply) 2094 || IS_COMMAND(packet, hci_user_passkey_request_reply)) { 2095 bt_flip_addr(addr, &packet[3]); 2096 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 2097 if (conn){ 2098 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 2099 } 2100 } 2101 2102 #ifdef HAVE_BLE 2103 if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){ 2104 hci_stack->adv_addr_type = packet[8]; 2105 } 2106 if (IS_COMMAND(packet, hci_le_set_random_address)){ 2107 bt_flip_addr(hci_stack->adv_address, &packet[3]); 2108 } 2109 #endif 2110 2111 hci_stack->num_cmd_packets--; 2112 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 2113 2114 // free packet buffer for synchronous transport implementations 2115 if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){ 2116 hci_stack->hci_packet_buffer_reserved = 0; 2117 } 2118 2119 return err; 2120 } 2121 2122 // disconnect because of security block 2123 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 2124 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2125 if (!connection) return; 2126 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 2127 } 2128 2129 2130 // Configure Secure Simple Pairing 2131 2132 // enable will enable SSP during init 2133 void hci_ssp_set_enable(int enable){ 2134 hci_stack->ssp_enable = enable; 2135 } 2136 2137 int hci_local_ssp_activated(){ 2138 return hci_ssp_supported() && hci_stack->ssp_enable; 2139 } 2140 2141 // if set, BTstack will respond to io capability request using authentication requirement 2142 void hci_ssp_set_io_capability(int io_capability){ 2143 hci_stack->ssp_io_capability = io_capability; 2144 } 2145 void hci_ssp_set_authentication_requirement(int authentication_requirement){ 2146 hci_stack->ssp_authentication_requirement = authentication_requirement; 2147 } 2148 2149 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 2150 void hci_ssp_set_auto_accept(int auto_accept){ 2151 hci_stack->ssp_auto_accept = auto_accept; 2152 } 2153 2154 /** 2155 * pre: numcmds >= 0 - it's allowed to send a command to the controller 2156 */ 2157 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 2158 2159 if (!hci_can_send_command_packet_now()){ 2160 log_error("hci_send_cmd called but cannot send packet now"); 2161 return 0; 2162 } 2163 2164 // for HCI INITIALIZATION 2165 // log_info("hci_send_cmd: opcode %04x", cmd->opcode); 2166 hci_stack->last_cmd_opcode = cmd->opcode; 2167 2168 hci_reserve_packet_buffer(); 2169 uint8_t * packet = hci_stack->hci_packet_buffer; 2170 2171 va_list argptr; 2172 va_start(argptr, cmd); 2173 uint16_t size = hci_create_cmd_internal(packet, cmd, argptr); 2174 va_end(argptr); 2175 2176 return hci_send_cmd_packet(packet, size); 2177 } 2178 2179 // Create various non-HCI events. 2180 // TODO: generalize, use table similar to hci_create_command 2181 2182 void hci_emit_state(){ 2183 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 2184 uint8_t event[3]; 2185 event[0] = BTSTACK_EVENT_STATE; 2186 event[1] = sizeof(event) - 2; 2187 event[2] = hci_stack->state; 2188 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2189 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2190 } 2191 2192 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 2193 uint8_t event[13]; 2194 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 2195 event[1] = sizeof(event) - 2; 2196 event[2] = status; 2197 bt_store_16(event, 3, conn->con_handle); 2198 bt_flip_addr(&event[5], conn->address); 2199 event[11] = 1; // ACL connection 2200 event[12] = 0; // encryption disabled 2201 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2202 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2203 } 2204 2205 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){ 2206 uint8_t event[21]; 2207 event[0] = HCI_EVENT_LE_META; 2208 event[1] = sizeof(event) - 2; 2209 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 2210 event[3] = status; 2211 bt_store_16(event, 4, conn->con_handle); 2212 event[6] = 0; // TODO: role 2213 event[7] = conn->address_type; 2214 bt_flip_addr(&event[8], conn->address); 2215 bt_store_16(event, 14, 0); // interval 2216 bt_store_16(event, 16, 0); // latency 2217 bt_store_16(event, 18, 0); // supervision timeout 2218 event[20] = 0; // master clock accuracy 2219 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2220 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2221 } 2222 2223 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 2224 uint8_t event[6]; 2225 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 2226 event[1] = sizeof(event) - 2; 2227 event[2] = 0; // status = OK 2228 bt_store_16(event, 3, handle); 2229 event[5] = reason; 2230 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2231 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2232 } 2233 2234 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 2235 if (disable_l2cap_timeouts) return; 2236 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 2237 uint8_t event[4]; 2238 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 2239 event[1] = sizeof(event) - 2; 2240 bt_store_16(event, 2, conn->con_handle); 2241 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 2242 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2243 } 2244 2245 void hci_emit_nr_connections_changed(){ 2246 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 2247 uint8_t event[3]; 2248 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 2249 event[1] = sizeof(event) - 2; 2250 event[2] = nr_hci_connections(); 2251 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2252 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2253 } 2254 2255 void hci_emit_hci_open_failed(){ 2256 log_info("BTSTACK_EVENT_POWERON_FAILED"); 2257 uint8_t event[2]; 2258 event[0] = BTSTACK_EVENT_POWERON_FAILED; 2259 event[1] = sizeof(event) - 2; 2260 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2261 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2262 } 2263 2264 #ifndef EMBEDDED 2265 void hci_emit_btstack_version() { 2266 log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 2267 uint8_t event[6]; 2268 event[0] = BTSTACK_EVENT_VERSION; 2269 event[1] = sizeof(event) - 2; 2270 event[2] = BTSTACK_MAJOR; 2271 event[3] = BTSTACK_MINOR; 2272 bt_store_16(event, 4, BTSTACK_REVISION); 2273 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2274 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2275 } 2276 #endif 2277 2278 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 2279 log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 2280 uint8_t event[3]; 2281 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 2282 event[1] = sizeof(event) - 2; 2283 event[2] = enabled; 2284 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2285 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2286 } 2287 2288 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 2289 uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info 2290 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 2291 event[1] = sizeof(event) - 2 - 1; 2292 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 2293 bt_flip_addr(&event[3], *addr); 2294 memcpy(&event[9], name, 248); 2295 2296 event[9+248] = 0; // assert \0 for log_info 2297 log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]); 2298 2299 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1); 2300 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1); 2301 } 2302 2303 void hci_emit_discoverable_enabled(uint8_t enabled){ 2304 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 2305 uint8_t event[3]; 2306 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 2307 event[1] = sizeof(event) - 2; 2308 event[2] = enabled; 2309 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2310 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2311 } 2312 2313 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 2314 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 2315 uint8_t event[5]; 2316 int pos = 0; 2317 event[pos++] = GAP_SECURITY_LEVEL; 2318 event[pos++] = sizeof(event) - 2; 2319 bt_store_16(event, 2, con_handle); 2320 pos += 2; 2321 event[pos++] = level; 2322 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2323 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2324 } 2325 2326 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){ 2327 log_info("hci_emit_dedicated_bonding_result %u ", status); 2328 uint8_t event[9]; 2329 int pos = 0; 2330 event[pos++] = GAP_DEDICATED_BONDING_COMPLETED; 2331 event[pos++] = sizeof(event) - 2; 2332 event[pos++] = status; 2333 bt_flip_addr( * (bd_addr_t *) &event[pos], address); 2334 pos += 6; 2335 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2336 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2337 } 2338 2339 // query if remote side supports SSP 2340 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 2341 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2342 if (!connection) return 0; 2343 return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0; 2344 } 2345 2346 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){ 2347 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 2348 } 2349 2350 // GAP API 2351 /** 2352 * @bbrief enable/disable bonding. default is enabled 2353 * @praram enabled 2354 */ 2355 void gap_set_bondable_mode(int enable){ 2356 hci_stack->bondable = enable ? 1 : 0; 2357 } 2358 2359 /** 2360 * @brief map link keys to security levels 2361 */ 2362 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 2363 switch (link_key_type){ 2364 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 2365 return LEVEL_4; 2366 case COMBINATION_KEY: 2367 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 2368 return LEVEL_3; 2369 default: 2370 return LEVEL_2; 2371 } 2372 } 2373 2374 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 2375 if (!connection) return LEVEL_0; 2376 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 2377 return gap_security_level_for_link_key_type(connection->link_key_type); 2378 } 2379 2380 2381 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 2382 log_info("gap_mitm_protection_required_for_security_level %u", level); 2383 return level > LEVEL_2; 2384 } 2385 2386 /** 2387 * @brief get current security level 2388 */ 2389 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 2390 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2391 if (!connection) return LEVEL_0; 2392 return gap_security_level_for_connection(connection); 2393 } 2394 2395 /** 2396 * @brief request connection to device to 2397 * @result GAP_AUTHENTICATION_RESULT 2398 */ 2399 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 2400 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2401 if (!connection){ 2402 hci_emit_security_level(con_handle, LEVEL_0); 2403 return; 2404 } 2405 gap_security_level_t current_level = gap_security_level(con_handle); 2406 log_info("gap_request_security_level %u, current level %u", requested_level, current_level); 2407 if (current_level >= requested_level){ 2408 hci_emit_security_level(con_handle, current_level); 2409 return; 2410 } 2411 2412 connection->requested_security_level = requested_level; 2413 2414 // would enabling ecnryption suffice (>= LEVEL_2)? 2415 if (hci_stack->remote_device_db){ 2416 link_key_type_t link_key_type; 2417 link_key_t link_key; 2418 if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){ 2419 if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){ 2420 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 2421 return; 2422 } 2423 } 2424 } 2425 2426 // try to authenticate connection 2427 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2428 hci_run(); 2429 } 2430 2431 /** 2432 * @brief start dedicated bonding with device. disconnect after bonding 2433 * @param device 2434 * @param request MITM protection 2435 * @result GAP_DEDICATED_BONDING_COMPLETE 2436 */ 2437 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 2438 2439 // create connection state machine 2440 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC); 2441 2442 if (!connection){ 2443 return BTSTACK_MEMORY_ALLOC_FAILED; 2444 } 2445 2446 // delete linkn key 2447 hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device); 2448 2449 // configure LEVEL_2/3, dedicated bonding 2450 connection->state = SEND_CREATE_CONNECTION; 2451 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 2452 log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level); 2453 connection->bonding_flags = BONDING_DEDICATED; 2454 2455 // wait for GAP Security Result and send GAP Dedicated Bonding complete 2456 2457 // handle: connnection failure (connection complete != ok) 2458 // handle: authentication failure 2459 // handle: disconnect on done 2460 2461 hci_run(); 2462 2463 return 0; 2464 } 2465 2466 void gap_set_local_name(const char * local_name){ 2467 hci_stack->local_name = local_name; 2468 } 2469 2470 le_command_status_t le_central_start_scan(){ 2471 if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK; 2472 hci_stack->le_scanning_state = LE_START_SCAN; 2473 hci_run(); 2474 return BLE_PERIPHERAL_OK; 2475 } 2476 2477 le_command_status_t le_central_stop_scan(){ 2478 if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK; 2479 hci_stack->le_scanning_state = LE_STOP_SCAN; 2480 hci_run(); 2481 return BLE_PERIPHERAL_OK; 2482 } 2483 2484 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 2485 hci_stack->le_scan_type = scan_type; 2486 hci_stack->le_scan_interval = scan_interval; 2487 hci_stack->le_scan_window = scan_window; 2488 hci_run(); 2489 } 2490 2491 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){ 2492 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2493 if (!conn){ 2494 log_info("le_central_connect: no connection exists yet, creating context"); 2495 conn = create_connection_for_bd_addr_and_type(*addr, addr_type); 2496 if (!conn){ 2497 // notify client that alloc failed 2498 hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 2499 log_info("le_central_connect: failed to alloc context"); 2500 return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller 2501 } 2502 conn->state = SEND_CREATE_CONNECTION; 2503 log_info("le_central_connect: send create connection next"); 2504 hci_run(); 2505 return BLE_PERIPHERAL_OK; 2506 } 2507 2508 if (!hci_is_le_connection(conn) || 2509 conn->state == SEND_CREATE_CONNECTION || 2510 conn->state == SENT_CREATE_CONNECTION) { 2511 hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED); 2512 log_error("le_central_connect: classic connection or connect is already being created"); 2513 return BLE_PERIPHERAL_IN_WRONG_STATE; 2514 } 2515 2516 log_info("le_central_connect: context exists with state %u", conn->state); 2517 hci_emit_le_connection_complete(conn, 0); 2518 hci_run(); 2519 return BLE_PERIPHERAL_OK; 2520 } 2521 2522 // @assumption: only a single outgoing LE Connection exists 2523 static hci_connection_t * le_central_get_outgoing_connection(){ 2524 linked_item_t *it; 2525 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 2526 hci_connection_t * conn = (hci_connection_t *) it; 2527 if (!hci_is_le_connection(conn)) continue; 2528 switch (conn->state){ 2529 case SEND_CREATE_CONNECTION: 2530 case SENT_CREATE_CONNECTION: 2531 return conn; 2532 default: 2533 break; 2534 }; 2535 } 2536 return NULL; 2537 } 2538 2539 le_command_status_t le_central_connect_cancel(){ 2540 hci_connection_t * conn = le_central_get_outgoing_connection(); 2541 switch (conn->state){ 2542 case SEND_CREATE_CONNECTION: 2543 // skip sending create connection and emit event instead 2544 hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 2545 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 2546 btstack_memory_hci_connection_free( conn ); 2547 break; 2548 case SENT_CREATE_CONNECTION: 2549 // request to send cancel connection 2550 conn->state = SEND_CANCEL_CONNECTION; 2551 hci_run(); 2552 break; 2553 default: 2554 break; 2555 } 2556 return BLE_PERIPHERAL_OK; 2557 } 2558 2559 /** 2560 * @brief Updates the connection parameters for a given LE connection 2561 * @param handle 2562 * @param conn_interval_min (unit: 1.25ms) 2563 * @param conn_interval_max (unit: 1.25ms) 2564 * @param conn_latency 2565 * @param supervision_timeout (unit: 10ms) 2566 * @returns 0 if ok 2567 */ 2568 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min, 2569 uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){ 2570 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2571 if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER; 2572 connection->le_conn_interval_min = conn_interval_min; 2573 connection->le_conn_interval_max = conn_interval_max; 2574 connection->le_conn_latency = conn_latency; 2575 connection->le_supervision_timeout = supervision_timeout; 2576 return 0; 2577 } 2578 2579 le_command_status_t gap_disconnect(hci_con_handle_t handle){ 2580 hci_connection_t * conn = hci_connection_for_handle(handle); 2581 if (!conn){ 2582 hci_emit_disconnection_complete(handle, 0); 2583 return BLE_PERIPHERAL_OK; 2584 } 2585 conn->state = SEND_DISCONNECT; 2586 hci_run(); 2587 return BLE_PERIPHERAL_OK; 2588 } 2589 2590 void hci_disconnect_all(){ 2591 linked_list_iterator_t it; 2592 linked_list_iterator_init(&it, &hci_stack->connections); 2593 while (linked_list_iterator_has_next(&it)){ 2594 hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it); 2595 if (con->state == SENT_DISCONNECT) continue; 2596 con->state = SEND_DISCONNECT; 2597 } 2598 hci_run(); 2599 } 2600