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