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