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