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