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