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