1 /* 2 * Copyright (C) 2009-2012 by Matthias Ringwald 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at [email protected] 34 * 35 */ 36 37 /* 38 * hci.c 39 * 40 * Created by Matthias Ringwald on 4/29/09. 41 * 42 */ 43 44 #include "btstack-config.h" 45 46 #include "hci.h" 47 #include "gap.h" 48 49 #include <stdarg.h> 50 #include <string.h> 51 #include <stdio.h> 52 53 #ifndef EMBEDDED 54 #include <unistd.h> // gethostbyname 55 #include <btstack/version.h> 56 #endif 57 58 #include "btstack_memory.h" 59 #include "debug.h" 60 #include "hci_dump.h" 61 62 #include <btstack/hci_cmds.h> 63 64 #define HCI_CONNECTION_TIMEOUT_MS 10000 65 66 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11 67 68 #ifdef USE_BLUETOOL 69 #include "bt_control_iphone.h" 70 #endif 71 72 static void hci_update_scan_enable(void); 73 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection); 74 75 // the STACK is here 76 #ifndef HAVE_MALLOC 77 static hci_stack_t hci_stack_static; 78 #endif 79 static hci_stack_t * hci_stack = NULL; 80 81 // test helper 82 static uint8_t disable_l2cap_timeouts = 0; 83 84 85 /** 86 * get connection for a given handle 87 * 88 * @return connection OR NULL, if not found 89 */ 90 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){ 91 linked_item_t *it; 92 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 93 if ( ((hci_connection_t *) it)->con_handle == con_handle){ 94 return (hci_connection_t *) it; 95 } 96 } 97 return NULL; 98 } 99 100 hci_connection_t * hci_connection_for_bd_addr(bd_addr_t * addr){ 101 linked_item_t *it; 102 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 103 hci_connection_t * connection = (hci_connection_t *) it; 104 if (memcmp(addr, connection->address, 6) == 0) { 105 return connection; 106 } 107 } 108 return NULL; 109 } 110 111 static void hci_connection_timeout_handler(timer_source_t *timer){ 112 hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item); 113 #ifdef HAVE_TIME 114 struct timeval tv; 115 gettimeofday(&tv, NULL); 116 if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) { 117 // connections might be timed out 118 hci_emit_l2cap_check_timeout(connection); 119 } 120 #endif 121 #ifdef HAVE_TICK 122 if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){ 123 // connections might be timed out 124 hci_emit_l2cap_check_timeout(connection); 125 } 126 #endif 127 run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS); 128 run_loop_add_timer(timer); 129 } 130 131 static void hci_connection_timestamp(hci_connection_t *connection){ 132 #ifdef HAVE_TIME 133 gettimeofday(&connection->timestamp, NULL); 134 #endif 135 #ifdef HAVE_TICK 136 connection->timestamp = embedded_get_ticks(); 137 #endif 138 } 139 140 /** 141 * create connection for given address 142 * 143 * @return connection OR NULL, if no memory left 144 */ 145 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){ 146 147 printf("create_connection_for_addr %s\n", bd_addr_to_str(addr)); 148 hci_connection_t * conn = (hci_connection_t *) btstack_memory_hci_connection_get(); 149 if (!conn) return NULL; 150 BD_ADDR_COPY(conn->address, addr); 151 conn->con_handle = 0xffff; 152 conn->authentication_flags = AUTH_FLAGS_NONE; 153 conn->bonding_flags = 0; 154 conn->requested_security_level = LEVEL_0; 155 linked_item_set_user(&conn->timeout.item, conn); 156 conn->timeout.process = hci_connection_timeout_handler; 157 hci_connection_timestamp(conn); 158 conn->acl_recombination_length = 0; 159 conn->acl_recombination_pos = 0; 160 conn->num_acl_packets_sent = 0; 161 linked_list_add(&hci_stack->connections, (linked_item_t *) conn); 162 return conn; 163 } 164 165 /** 166 * get connection for given address 167 * 168 * @return connection OR NULL, if not found 169 */ 170 static hci_connection_t * connection_for_address(bd_addr_t address){ 171 linked_item_t *it; 172 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 173 if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){ 174 return (hci_connection_t *) it; 175 } 176 } 177 return NULL; 178 } 179 180 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 181 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags); 182 } 183 184 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){ 185 conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags); 186 } 187 188 189 /** 190 * add authentication flags and reset timer 191 */ 192 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){ 193 bd_addr_t addr; 194 bt_flip_addr(addr, *(bd_addr_t *) bd_addr); 195 hci_connection_t * conn = connection_for_address(addr); 196 if (conn) { 197 connectionSetAuthenticationFlags(conn, flags); 198 hci_connection_timestamp(conn); 199 } 200 } 201 202 int hci_authentication_active_for_handle(hci_con_handle_t handle){ 203 hci_connection_t * conn = hci_connection_for_handle(handle); 204 if (!conn) return 0; 205 if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1; 206 if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1; 207 return 0; 208 } 209 210 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){ 211 if (hci_stack->remote_device_db) { 212 hci_stack->remote_device_db->delete_link_key(addr); 213 } 214 } 215 216 217 /** 218 * count connections 219 */ 220 static int nr_hci_connections(void){ 221 int count = 0; 222 linked_item_t *it; 223 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++); 224 return count; 225 } 226 227 /** 228 * Dummy handler called by HCI 229 */ 230 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 231 } 232 233 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){ 234 hci_connection_t * connection = hci_connection_for_handle(handle); 235 if (!connection) { 236 log_error("hci_number_outgoing_packets connectino for handle %u does not exist!\n", handle); 237 return 0; 238 } 239 return connection->num_acl_packets_sent; 240 } 241 242 uint8_t hci_number_free_acl_slots(){ 243 uint8_t free_slots = hci_stack->total_num_acl_packets; 244 linked_item_t *it; 245 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 246 hci_connection_t * connection = (hci_connection_t *) it; 247 if (free_slots < connection->num_acl_packets_sent) { 248 log_error("hci_number_free_acl_slots: sum of outgoing packets > total acl packets!\n"); 249 return 0; 250 } 251 free_slots -= connection->num_acl_packets_sent; 252 } 253 return free_slots; 254 } 255 256 int hci_can_send_packet_now(uint8_t packet_type){ 257 258 // check for async hci transport implementations 259 if (hci_stack->hci_transport->can_send_packet_now){ 260 if (!hci_stack->hci_transport->can_send_packet_now(packet_type)){ 261 return 0; 262 } 263 } 264 265 // check regular Bluetooth flow control 266 switch (packet_type) { 267 case HCI_ACL_DATA_PACKET: 268 return hci_number_free_acl_slots(); 269 case HCI_COMMAND_DATA_PACKET: 270 return hci_stack->num_cmd_packets; 271 default: 272 return 0; 273 } 274 } 275 276 // same as hci_can_send_packet_now, but also checks if packet buffer is free for use 277 int hci_can_send_packet_now_using_packet_buffer(uint8_t packet_type){ 278 if (hci_stack->hci_packet_buffer_reserved) return 0; 279 return hci_can_send_packet_now(packet_type); 280 } 281 282 // used for internal checks in l2cap[-le].c 283 int hci_is_packet_buffer_reserved(void){ 284 return hci_stack->hci_packet_buffer_reserved; 285 } 286 287 // reserves outgoing packet buffer. @returns 1 if successful 288 int hci_reserve_packet_buffer(void){ 289 if (hci_stack->hci_packet_buffer_reserved) return 0; 290 hci_stack->hci_packet_buffer_reserved = 1; 291 return 1; 292 } 293 294 void hci_release_packet_buffer(void){ 295 hci_stack->hci_packet_buffer_reserved = 0; 296 } 297 298 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call 299 int hci_transport_synchronous(void){ 300 return hci_stack->hci_transport->can_send_packet_now == NULL; 301 } 302 303 int hci_send_acl_packet(uint8_t *packet, int size){ 304 305 // check for free places on BT module 306 if (!hci_number_free_acl_slots()) return BTSTACK_ACL_BUFFERS_FULL; 307 308 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 309 hci_connection_t *connection = hci_connection_for_handle( con_handle); 310 if (!connection) return 0; 311 hci_connection_timestamp(connection); 312 313 // count packet 314 connection->num_acl_packets_sent++; 315 // log_info("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent); 316 317 // send packet 318 int err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size); 319 320 // free packet buffer for synchronous transport implementations 321 if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){ 322 hci_stack->hci_packet_buffer_reserved = 0; 323 } 324 325 return err; 326 } 327 328 static void acl_handler(uint8_t *packet, int size){ 329 330 // log_info("acl_handler: size %u", size); 331 332 // get info 333 hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); 334 hci_connection_t *conn = hci_connection_for_handle(con_handle); 335 uint8_t acl_flags = READ_ACL_FLAGS(packet); 336 uint16_t acl_length = READ_ACL_LENGTH(packet); 337 338 // ignore non-registered handle 339 if (!conn){ 340 log_error( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle); 341 return; 342 } 343 344 // assert packet is complete 345 if (acl_length + 4 != size){ 346 log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4); 347 return; 348 } 349 350 // update idle timestamp 351 hci_connection_timestamp(conn); 352 353 // handle different packet types 354 switch (acl_flags & 0x03) { 355 356 case 0x01: // continuation fragment 357 358 // sanity check 359 if (conn->acl_recombination_pos == 0) { 360 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle); 361 return; 362 } 363 364 // append fragment payload (header already stored) 365 memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length ); 366 conn->acl_recombination_pos += acl_length; 367 368 // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n", acl_length, 369 // conn->acl_recombination_pos, conn->acl_recombination_length); 370 371 // forward complete L2CAP packet if complete. 372 if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header 373 374 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos); 375 // reset recombination buffer 376 conn->acl_recombination_length = 0; 377 conn->acl_recombination_pos = 0; 378 } 379 break; 380 381 case 0x02: { // first fragment 382 383 // sanity check 384 if (conn->acl_recombination_pos) { 385 log_error( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle); 386 return; 387 } 388 389 // peek into L2CAP packet! 390 uint16_t l2cap_length = READ_L2CAP_LENGTH( packet ); 391 392 // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length); 393 394 // compare fragment size to L2CAP packet size 395 if (acl_length >= l2cap_length + 4){ 396 397 // forward fragment as L2CAP packet 398 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4); 399 400 } else { 401 // store first fragment and tweak acl length for complete package 402 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4); 403 conn->acl_recombination_pos = acl_length + 4; 404 conn->acl_recombination_length = l2cap_length; 405 bt_store_16(conn->acl_recombination_buffer, 2, l2cap_length +4); 406 } 407 break; 408 409 } 410 default: 411 log_error( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03); 412 return; 413 } 414 415 // execute main loop 416 hci_run(); 417 } 418 419 static void hci_shutdown_connection(hci_connection_t *conn){ 420 log_info("Connection closed: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 421 422 // cancel all l2cap connections 423 hci_emit_disconnection_complete(conn->con_handle, 0x16); // terminated by local host 424 425 run_loop_remove_timer(&conn->timeout); 426 427 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 428 btstack_memory_hci_connection_free( conn ); 429 430 // now it's gone 431 hci_emit_nr_connections_changed(); 432 } 433 434 static const uint16_t packet_type_sizes[] = { 435 0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE, 436 HCI_ACL_DH1_SIZE, 0, 0, 0, 437 HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE, 438 HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE 439 }; 440 static const uint8_t packet_type_feature_requirement_bit[] = { 441 0, // 3 slot packets 442 1, // 5 slot packets 443 25, // EDR 2 mpbs 444 26, // EDR 3 mbps 445 39, // 3 slot EDR packts 446 40, // 5 slot EDR packet 447 }; 448 static const uint16_t packet_type_feature_packet_mask[] = { 449 0x0f00, // 3 slot packets 450 0xf000, // 5 slot packets 451 0x1102, // EDR 2 mpbs 452 0x2204, // EDR 3 mbps 453 0x0300, // 3 slot EDR packts 454 0x3000, // 5 slot EDR packet 455 }; 456 457 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){ 458 // enable packet types based on size 459 uint16_t packet_types = 0; 460 int i; 461 for (i=0;i<16;i++){ 462 if (packet_type_sizes[i] == 0) continue; 463 if (packet_type_sizes[i] <= buffer_size){ 464 packet_types |= 1 << i; 465 } 466 } 467 // disable packet types due to missing local supported features 468 for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){ 469 int bit_idx = packet_type_feature_requirement_bit[i]; 470 int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0; 471 if (feature_set) continue; 472 log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]); 473 packet_types &= ~packet_type_feature_packet_mask[i]; 474 } 475 // flip bits for "may not be used" 476 packet_types ^= 0x3306; 477 return packet_types; 478 } 479 480 uint16_t hci_usable_acl_packet_types(void){ 481 return hci_stack->packet_types; 482 } 483 484 uint8_t* hci_get_outgoing_packet_buffer(void){ 485 // hci packet buffer is >= acl data packet length 486 return hci_stack->hci_packet_buffer; 487 } 488 489 uint16_t hci_max_acl_data_packet_length(void){ 490 return hci_stack->acl_data_packet_length; 491 } 492 493 int hci_ssp_supported(void){ 494 // No 51, byte 6, bit 3 495 return (hci_stack->local_supported_features[6] & (1 << 3)) != 0; 496 } 497 498 int hci_classic_supported(void){ 499 // No 37, byte 4, bit 5, = No BR/EDR Support 500 return (hci_stack->local_supported_features[4] & (1 << 5)) == 0; 501 } 502 503 int hci_le_supported(void){ 504 // No 37, byte 4, bit 6 = LE Supported (Controller) 505 #ifdef HAVE_BLE 506 return (hci_stack->local_supported_features[4] & (1 << 6)) != 0; 507 #else 508 return 0; 509 #endif 510 } 511 512 // get addr type and address used in advertisement packets 513 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){ 514 *addr_type = hci_stack->adv_addr_type; 515 if (hci_stack->adv_addr_type){ 516 memcpy(addr, hci_stack->adv_address, 6); 517 } else { 518 memcpy(addr, hci_stack->local_bd_addr, 6); 519 } 520 } 521 522 // avoid huge local variables 523 #ifndef EMBEDDED 524 static device_name_t device_name; 525 #endif 526 static void event_handler(uint8_t *packet, int size){ 527 528 uint16_t event_length = packet[1]; 529 530 // assert packet is complete 531 if (size != event_length + 2){ 532 log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2); 533 return; 534 } 535 536 bd_addr_t addr; 537 uint8_t link_type; 538 hci_con_handle_t handle; 539 hci_connection_t * conn; 540 int i; 541 542 // printf("HCI:EVENT:%02x\n", packet[0]); 543 544 switch (packet[0]) { 545 546 case HCI_EVENT_COMMAND_COMPLETE: 547 // get num cmd packets 548 // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack->num_cmd_packets, packet[2]); 549 hci_stack->num_cmd_packets = packet[2]; 550 551 if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ 552 // from offset 5 553 // status 554 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" 555 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6); 556 // ignore: SCO data packet len (8) 557 hci_stack->total_num_acl_packets = packet[9]; 558 // ignore: total num SCO packets 559 if (hci_stack->state == HCI_STATE_INITIALIZING){ 560 // determine usable ACL payload size 561 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){ 562 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 563 } 564 log_info("hci_read_buffer_size: used size %u, count %u\n", 565 hci_stack->acl_data_packet_length, hci_stack->total_num_acl_packets); 566 } 567 } 568 #ifdef HAVE_BLE 569 if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){ 570 hci_stack->le_data_packet_length = READ_BT_16(packet, 6); 571 hci_stack->total_num_le_packets = packet[8]; 572 log_info("hci_le_read_buffer_size: size %u, count %u\n", hci_stack->le_data_packet_length, hci_stack->total_num_le_packets); 573 } 574 #endif 575 // Dump local address 576 if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { 577 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); 578 log_info("Local Address, Status: 0x%02x: Addr: %s\n", 579 packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr)); 580 } 581 if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 582 hci_emit_discoverable_enabled(hci_stack->discoverable); 583 } 584 // Note: HCI init checks 585 if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){ 586 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8); 587 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x", 588 hci_stack->local_supported_features[0], hci_stack->local_supported_features[1], 589 hci_stack->local_supported_features[2], hci_stack->local_supported_features[3], 590 hci_stack->local_supported_features[4], hci_stack->local_supported_features[5], 591 hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]); 592 593 // determine usable ACL packet types based buffer size and supported features 594 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(hci_stack->acl_data_packet_length, &hci_stack->local_supported_features[0]); 595 log_info("packet types %04x", hci_stack->packet_types); 596 597 // Classic/LE 598 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported()); 599 } 600 break; 601 602 case HCI_EVENT_COMMAND_STATUS: 603 // get num cmd packets 604 // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack->num_cmd_packets, packet[3]); 605 hci_stack->num_cmd_packets = packet[3]; 606 break; 607 608 case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: 609 for (i=0; i<packet[2];i++){ 610 handle = READ_BT_16(packet, 3 + 2*i); 611 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i); 612 conn = hci_connection_for_handle(handle); 613 if (!conn){ 614 log_error("hci_number_completed_packet lists unused con handle %u\n", handle); 615 continue; 616 } 617 conn->num_acl_packets_sent -= num_packets; 618 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent); 619 } 620 break; 621 622 case HCI_EVENT_CONNECTION_REQUEST: 623 bt_flip_addr(addr, &packet[2]); 624 // TODO: eval COD 8-10 625 link_type = packet[11]; 626 log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type); 627 if (link_type == 1) { // ACL 628 conn = connection_for_address(addr); 629 if (!conn) { 630 conn = create_connection_for_addr(addr); 631 } 632 if (!conn) { 633 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) 634 hci_stack->decline_reason = 0x0d; 635 BD_ADDR_COPY(hci_stack->decline_addr, addr); 636 break; 637 } 638 conn->state = RECEIVED_CONNECTION_REQUEST; 639 hci_run(); 640 } else { 641 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A) 642 hci_stack->decline_reason = 0x0a; 643 BD_ADDR_COPY(hci_stack->decline_addr, addr); 644 } 645 break; 646 647 case HCI_EVENT_CONNECTION_COMPLETE: 648 // Connection management 649 bt_flip_addr(addr, &packet[5]); 650 log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr)); 651 conn = connection_for_address(addr); 652 if (conn) { 653 if (!packet[2]){ 654 conn->state = OPEN; 655 conn->con_handle = READ_BT_16(packet, 3); 656 conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES; 657 658 // restart timer 659 run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 660 run_loop_add_timer(&conn->timeout); 661 662 log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 663 664 hci_emit_nr_connections_changed(); 665 } else { 666 // notify client if dedicated bonding 667 if (conn->bonding_flags & BONDING_DEDICATED){ 668 hci_emit_dedicated_bonding_result(conn, packet[2]); 669 } 670 671 // connection failed, remove entry 672 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 673 btstack_memory_hci_connection_free( conn ); 674 675 // if authentication error, also delete link key 676 if (packet[2] == 0x05) { 677 hci_drop_link_key_for_bd_addr(&addr); 678 } 679 } 680 } 681 break; 682 683 case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 684 handle = READ_BT_16(packet, 3); 685 conn = hci_connection_for_handle(handle); 686 if (!conn) break; 687 if (!packet[2]){ 688 uint8_t * features = &packet[5]; 689 if (features[6] & (1 << 3)){ 690 conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP; 691 } 692 } 693 conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES; 694 log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags); 695 if (conn->bonding_flags & BONDING_DEDICATED){ 696 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 697 } 698 break; 699 700 case HCI_EVENT_LINK_KEY_REQUEST: 701 log_info("HCI_EVENT_LINK_KEY_REQUEST\n"); 702 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); 703 // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST 704 if (hci_stack->bondable && !hci_stack->remote_device_db) break; 705 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); 706 hci_run(); 707 // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set 708 return; 709 710 case HCI_EVENT_LINK_KEY_NOTIFICATION: { 711 bt_flip_addr(addr, &packet[2]); 712 conn = connection_for_address(addr); 713 if (!conn) break; 714 conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION; 715 link_key_type_t link_key_type = packet[24]; 716 // Change Connection Encryption keeps link key type 717 if (link_key_type != CHANGED_COMBINATION_KEY){ 718 conn->link_key_type = link_key_type; 719 } 720 if (!hci_stack->remote_device_db) break; 721 hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type); 722 // still forward event to allow dismiss of pairing dialog 723 break; 724 } 725 726 case HCI_EVENT_PIN_CODE_REQUEST: 727 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE); 728 // non-bondable mode: pin code negative reply will be sent 729 if (!hci_stack->bondable){ 730 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST); 731 hci_run(); 732 return; 733 } 734 // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key 735 if (!hci_stack->remote_device_db) break; 736 bt_flip_addr(addr, &packet[2]); 737 hci_stack->remote_device_db->delete_link_key(&addr); 738 break; 739 740 case HCI_EVENT_IO_CAPABILITY_REQUEST: 741 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST); 742 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY); 743 break; 744 745 case HCI_EVENT_USER_CONFIRMATION_REQUEST: 746 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 747 if (!hci_stack->ssp_auto_accept) break; 748 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY); 749 break; 750 751 case HCI_EVENT_USER_PASSKEY_REQUEST: 752 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE); 753 if (!hci_stack->ssp_auto_accept) break; 754 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY); 755 break; 756 757 case HCI_EVENT_ENCRYPTION_CHANGE: 758 handle = READ_BT_16(packet, 3); 759 conn = hci_connection_for_handle(handle); 760 if (!conn) break; 761 if (packet[2] == 0) { 762 if (packet[5]){ 763 conn->authentication_flags |= CONNECTION_ENCRYPTED; 764 } else { 765 conn->authentication_flags &= ~CONNECTION_ENCRYPTED; 766 } 767 } 768 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 769 break; 770 771 case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT: 772 handle = READ_BT_16(packet, 3); 773 conn = hci_connection_for_handle(handle); 774 if (!conn) break; 775 776 // dedicated bonding: send result and disconnect 777 if (conn->bonding_flags & BONDING_DEDICATED){ 778 conn->bonding_flags &= ~BONDING_DEDICATED; 779 hci_emit_dedicated_bonding_result( conn, packet[2]); 780 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE; 781 break; 782 } 783 784 if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){ 785 // link key sufficient for requested security 786 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 787 break; 788 } 789 // not enough 790 hci_emit_security_level(handle, gap_security_level_for_connection(conn)); 791 break; 792 793 #ifndef EMBEDDED 794 case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: 795 if (!hci_stack->remote_device_db) break; 796 if (packet[2]) break; // status not ok 797 bt_flip_addr(addr, &packet[3]); 798 // fix for invalid remote names - terminate on 0xff 799 for (i=0; i<248;i++){ 800 if (packet[9+i] == 0xff){ 801 packet[9+i] = 0; 802 break; 803 } 804 } 805 memset(&device_name, 0, sizeof(device_name_t)); 806 strncpy((char*) device_name, (char*) &packet[9], 248); 807 hci_stack->remote_device_db->put_name(&addr, &device_name); 808 break; 809 810 case HCI_EVENT_INQUIRY_RESULT: 811 case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: 812 if (!hci_stack->remote_device_db) break; 813 // first send inq result packet 814 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 815 // then send cached remote names 816 for (i=0; i<packet[2];i++){ 817 bt_flip_addr(addr, &packet[3+i*6]); 818 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){ 819 hci_emit_remote_name_cached(&addr, &device_name); 820 } 821 } 822 return; 823 #endif 824 825 case HCI_EVENT_DISCONNECTION_COMPLETE: 826 if (!packet[2]){ 827 handle = READ_BT_16(packet, 3); 828 hci_connection_t * conn = hci_connection_for_handle(handle); 829 if (conn) { 830 hci_shutdown_connection(conn); 831 } 832 } 833 break; 834 835 case HCI_EVENT_HARDWARE_ERROR: 836 if(hci_stack->control && hci_stack->control->hw_error){ 837 (*hci_stack->control->hw_error)(); 838 } 839 break; 840 841 case DAEMON_EVENT_HCI_PACKET_SENT: 842 // free packet buffer for asynchronous transport 843 if (hci_transport_synchronous()) break; 844 hci_stack->hci_packet_buffer_reserved = 0; 845 break; 846 847 #ifdef HAVE_BLE 848 case HCI_EVENT_LE_META: 849 switch (packet[2]) { 850 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: 851 // Connection management 852 bt_flip_addr(addr, &packet[8]); 853 log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr)); 854 // LE connections are auto-accepted, so just create a connection if there isn't one already 855 conn = connection_for_address(addr); 856 if (packet[3]){ 857 if (conn){ 858 // outgoing connection failed, remove entry 859 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 860 btstack_memory_hci_connection_free( conn ); 861 862 } 863 // if authentication error, also delete link key 864 if (packet[3] == 0x05) { 865 hci_drop_link_key_for_bd_addr(&addr); 866 } 867 break; 868 } 869 if (!conn){ 870 conn = create_connection_for_addr(addr); 871 } 872 if (!conn){ 873 // no memory 874 break; 875 } 876 877 conn->state = OPEN; 878 conn->con_handle = READ_BT_16(packet, 4); 879 880 // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock 881 882 // restart timer 883 // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); 884 // run_loop_add_timer(&conn->timeout); 885 886 log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); 887 888 hci_emit_nr_connections_changed(); 889 break; 890 891 // printf("LE buffer size: %u, count %u\n", READ_BT_16(packet,6), packet[8]); 892 893 default: 894 break; 895 } 896 break; 897 #endif 898 899 default: 900 break; 901 } 902 903 // handle BT initialization 904 if (hci_stack->state == HCI_STATE_INITIALIZING){ 905 if (hci_stack->substate % 2){ 906 // odd: waiting for event 907 if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){ 908 // wait for explicit COMMAND COMPLETE on RESET 909 if (hci_stack->substate > 1 || COMMAND_COMPLETE_EVENT(packet, hci_reset)) { 910 hci_stack->substate++; 911 } 912 } 913 } 914 } 915 916 // help with BT sleep 917 if (hci_stack->state == HCI_STATE_FALLING_ASLEEP 918 && hci_stack->substate == 1 919 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ 920 hci_stack->substate++; 921 } 922 923 hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size); 924 925 // execute main loop 926 hci_run(); 927 } 928 929 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){ 930 switch (packet_type) { 931 case HCI_EVENT_PACKET: 932 event_handler(packet, size); 933 break; 934 case HCI_ACL_DATA_PACKET: 935 acl_handler(packet, size); 936 break; 937 default: 938 break; 939 } 940 } 941 942 /** Register HCI packet handlers */ 943 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){ 944 hci_stack->packet_handler = handler; 945 } 946 947 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){ 948 949 #ifdef HAVE_MALLOC 950 if (!hci_stack) { 951 hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t)); 952 } 953 #else 954 hci_stack = &hci_stack_static; 955 #endif 956 memset(hci_stack, 0, sizeof(hci_stack_t)); 957 958 // reference to use transport layer implementation 959 hci_stack->hci_transport = transport; 960 961 // references to used control implementation 962 hci_stack->control = control; 963 964 // reference to used config 965 hci_stack->config = config; 966 967 // no connections yet 968 hci_stack->connections = NULL; 969 hci_stack->discoverable = 0; 970 hci_stack->connectable = 0; 971 hci_stack->bondable = 1; 972 973 // no pending cmds 974 hci_stack->decline_reason = 0; 975 hci_stack->new_scan_enable_value = 0xff; 976 977 // higher level handler 978 hci_stack->packet_handler = dummy_handler; 979 980 // store and open remote device db 981 hci_stack->remote_device_db = remote_device_db; 982 if (hci_stack->remote_device_db) { 983 hci_stack->remote_device_db->open(); 984 } 985 986 // max acl payload size defined in config.h 987 hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; 988 989 // register packet handlers with transport 990 transport->register_packet_handler(&packet_handler); 991 992 hci_stack->state = HCI_STATE_OFF; 993 994 // class of device 995 hci_stack->class_of_device = 0x007a020c; // Smartphone 996 997 // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept 998 hci_stack->ssp_enable = 1; 999 hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT; 1000 hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING; 1001 hci_stack->ssp_auto_accept = 1; 1002 1003 // LE 1004 hci_stack->adv_addr_type = 0; 1005 memset(hci_stack->adv_address, 0, 6); 1006 } 1007 1008 void hci_close(){ 1009 // close remote device db 1010 if (hci_stack->remote_device_db) { 1011 hci_stack->remote_device_db->close(); 1012 } 1013 while (hci_stack->connections) { 1014 hci_shutdown_connection((hci_connection_t *) hci_stack->connections); 1015 } 1016 hci_power_control(HCI_POWER_OFF); 1017 1018 #ifdef HAVE_MALLOC 1019 free(hci_stack); 1020 #endif 1021 hci_stack = NULL; 1022 } 1023 1024 void hci_set_class_of_device(uint32_t class_of_device){ 1025 hci_stack->class_of_device = class_of_device; 1026 } 1027 1028 void hci_disable_l2cap_timeout_check(){ 1029 disable_l2cap_timeouts = 1; 1030 } 1031 // State-Module-Driver overview 1032 // state module low-level 1033 // HCI_STATE_OFF off close 1034 // HCI_STATE_INITIALIZING, on open 1035 // HCI_STATE_WORKING, on open 1036 // HCI_STATE_HALTING, on open 1037 // HCI_STATE_SLEEPING, off/sleep close 1038 // HCI_STATE_FALLING_ASLEEP on open 1039 1040 static int hci_power_control_on(void){ 1041 1042 // power on 1043 int err = 0; 1044 if (hci_stack->control && hci_stack->control->on){ 1045 err = (*hci_stack->control->on)(hci_stack->config); 1046 } 1047 if (err){ 1048 log_error( "POWER_ON failed\n"); 1049 hci_emit_hci_open_failed(); 1050 return err; 1051 } 1052 1053 // open low-level device 1054 err = hci_stack->hci_transport->open(hci_stack->config); 1055 if (err){ 1056 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 1057 if (hci_stack->control && hci_stack->control->off){ 1058 (*hci_stack->control->off)(hci_stack->config); 1059 } 1060 hci_emit_hci_open_failed(); 1061 return err; 1062 } 1063 return 0; 1064 } 1065 1066 static void hci_power_control_off(void){ 1067 1068 log_info("hci_power_control_off\n"); 1069 1070 // close low-level device 1071 hci_stack->hci_transport->close(hci_stack->config); 1072 1073 log_info("hci_power_control_off - hci_transport closed\n"); 1074 1075 // power off 1076 if (hci_stack->control && hci_stack->control->off){ 1077 (*hci_stack->control->off)(hci_stack->config); 1078 } 1079 1080 log_info("hci_power_control_off - control closed\n"); 1081 1082 hci_stack->state = HCI_STATE_OFF; 1083 } 1084 1085 static void hci_power_control_sleep(void){ 1086 1087 log_info("hci_power_control_sleep\n"); 1088 1089 #if 0 1090 // don't close serial port during sleep 1091 1092 // close low-level device 1093 hci_stack->hci_transport->close(hci_stack->config); 1094 #endif 1095 1096 // sleep mode 1097 if (hci_stack->control && hci_stack->control->sleep){ 1098 (*hci_stack->control->sleep)(hci_stack->config); 1099 } 1100 1101 hci_stack->state = HCI_STATE_SLEEPING; 1102 } 1103 1104 static int hci_power_control_wake(void){ 1105 1106 log_info("hci_power_control_wake\n"); 1107 1108 // wake on 1109 if (hci_stack->control && hci_stack->control->wake){ 1110 (*hci_stack->control->wake)(hci_stack->config); 1111 } 1112 1113 #if 0 1114 // open low-level device 1115 int err = hci_stack->hci_transport->open(hci_stack->config); 1116 if (err){ 1117 log_error( "HCI_INIT failed, turning Bluetooth off again\n"); 1118 if (hci_stack->control && hci_stack->control->off){ 1119 (*hci_stack->control->off)(hci_stack->config); 1120 } 1121 hci_emit_hci_open_failed(); 1122 return err; 1123 } 1124 #endif 1125 1126 return 0; 1127 } 1128 1129 1130 int hci_power_control(HCI_POWER_MODE power_mode){ 1131 1132 log_info("hci_power_control: %u, current mode %u\n", power_mode, hci_stack->state); 1133 1134 int err = 0; 1135 switch (hci_stack->state){ 1136 1137 case HCI_STATE_OFF: 1138 switch (power_mode){ 1139 case HCI_POWER_ON: 1140 err = hci_power_control_on(); 1141 if (err) return err; 1142 // set up state machine 1143 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 1144 hci_stack->state = HCI_STATE_INITIALIZING; 1145 hci_stack->substate = 0; 1146 break; 1147 case HCI_POWER_OFF: 1148 // do nothing 1149 break; 1150 case HCI_POWER_SLEEP: 1151 // do nothing (with SLEEP == OFF) 1152 break; 1153 } 1154 break; 1155 1156 case HCI_STATE_INITIALIZING: 1157 switch (power_mode){ 1158 case HCI_POWER_ON: 1159 // do nothing 1160 break; 1161 case HCI_POWER_OFF: 1162 // no connections yet, just turn it off 1163 hci_power_control_off(); 1164 break; 1165 case HCI_POWER_SLEEP: 1166 // no connections yet, just turn it off 1167 hci_power_control_sleep(); 1168 break; 1169 } 1170 break; 1171 1172 case HCI_STATE_WORKING: 1173 switch (power_mode){ 1174 case HCI_POWER_ON: 1175 // do nothing 1176 break; 1177 case HCI_POWER_OFF: 1178 // see hci_run 1179 hci_stack->state = HCI_STATE_HALTING; 1180 break; 1181 case HCI_POWER_SLEEP: 1182 // see hci_run 1183 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1184 hci_stack->substate = 0; 1185 break; 1186 } 1187 break; 1188 1189 case HCI_STATE_HALTING: 1190 switch (power_mode){ 1191 case HCI_POWER_ON: 1192 // set up state machine 1193 hci_stack->state = HCI_STATE_INITIALIZING; 1194 hci_stack->substate = 0; 1195 break; 1196 case HCI_POWER_OFF: 1197 // do nothing 1198 break; 1199 case HCI_POWER_SLEEP: 1200 // see hci_run 1201 hci_stack->state = HCI_STATE_FALLING_ASLEEP; 1202 hci_stack->substate = 0; 1203 break; 1204 } 1205 break; 1206 1207 case HCI_STATE_FALLING_ASLEEP: 1208 switch (power_mode){ 1209 case HCI_POWER_ON: 1210 1211 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1212 // nothing to do, if H4 supports power management 1213 if (bt_control_iphone_power_management_enabled()){ 1214 hci_stack->state = HCI_STATE_INITIALIZING; 1215 hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1216 break; 1217 } 1218 #endif 1219 // set up state machine 1220 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 1221 hci_stack->state = HCI_STATE_INITIALIZING; 1222 hci_stack->substate = 0; 1223 break; 1224 case HCI_POWER_OFF: 1225 // see hci_run 1226 hci_stack->state = HCI_STATE_HALTING; 1227 break; 1228 case HCI_POWER_SLEEP: 1229 // do nothing 1230 break; 1231 } 1232 break; 1233 1234 case HCI_STATE_SLEEPING: 1235 switch (power_mode){ 1236 case HCI_POWER_ON: 1237 1238 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1239 // nothing to do, if H4 supports power management 1240 if (bt_control_iphone_power_management_enabled()){ 1241 hci_stack->state = HCI_STATE_INITIALIZING; 1242 hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP; 1243 hci_update_scan_enable(); 1244 break; 1245 } 1246 #endif 1247 err = hci_power_control_wake(); 1248 if (err) return err; 1249 // set up state machine 1250 hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent 1251 hci_stack->state = HCI_STATE_INITIALIZING; 1252 hci_stack->substate = 0; 1253 break; 1254 case HCI_POWER_OFF: 1255 hci_stack->state = HCI_STATE_HALTING; 1256 break; 1257 case HCI_POWER_SLEEP: 1258 // do nothing 1259 break; 1260 } 1261 break; 1262 } 1263 1264 // create internal event 1265 hci_emit_state(); 1266 1267 // trigger next/first action 1268 hci_run(); 1269 1270 return 0; 1271 } 1272 1273 static void hci_update_scan_enable(void){ 1274 // 2 = page scan, 1 = inq scan 1275 hci_stack->new_scan_enable_value = hci_stack->connectable << 1 | hci_stack->discoverable; 1276 hci_run(); 1277 } 1278 1279 void hci_discoverable_control(uint8_t enable){ 1280 if (enable) enable = 1; // normalize argument 1281 1282 if (hci_stack->discoverable == enable){ 1283 hci_emit_discoverable_enabled(hci_stack->discoverable); 1284 return; 1285 } 1286 1287 hci_stack->discoverable = enable; 1288 hci_update_scan_enable(); 1289 } 1290 1291 void hci_connectable_control(uint8_t enable){ 1292 if (enable) enable = 1; // normalize argument 1293 1294 // don't emit event 1295 if (hci_stack->connectable == enable) return; 1296 1297 hci_stack->connectable = enable; 1298 hci_update_scan_enable(); 1299 } 1300 1301 bd_addr_t * hci_local_bd_addr(void){ 1302 return &hci_stack->local_bd_addr; 1303 } 1304 1305 void hci_run(){ 1306 1307 hci_connection_t * connection; 1308 linked_item_t * it; 1309 1310 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return; 1311 1312 // global/non-connection oriented commands 1313 1314 // decline incoming connections 1315 if (hci_stack->decline_reason){ 1316 uint8_t reason = hci_stack->decline_reason; 1317 hci_stack->decline_reason = 0; 1318 hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason); 1319 return; 1320 } 1321 1322 // send scan enable 1323 if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){ 1324 hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value); 1325 hci_stack->new_scan_enable_value = 0xff; 1326 return; 1327 } 1328 1329 // send pending HCI commands 1330 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 1331 1332 connection = (hci_connection_t *) it; 1333 1334 if (connection->state == SEND_CREATE_CONNECTION){ 1335 log_info("sending hci_create_connection\n"); 1336 hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1); 1337 return; 1338 } 1339 1340 if (connection->state == RECEIVED_CONNECTION_REQUEST){ 1341 log_info("sending hci_accept_connection_request\n"); 1342 connection->state = ACCEPTED_CONNECTION_REQUEST; 1343 hci_send_cmd(&hci_accept_connection_request, connection->address, 1); 1344 return; 1345 } 1346 1347 if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){ 1348 log_info("responding to link key request\n"); 1349 connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST); 1350 link_key_t link_key; 1351 link_key_type_t link_key_type; 1352 if ( hci_stack->remote_device_db 1353 && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type) 1354 && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){ 1355 connection->link_key_type = link_key_type; 1356 hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key); 1357 } else { 1358 hci_send_cmd(&hci_link_key_request_negative_reply, connection->address); 1359 } 1360 return; 1361 } 1362 1363 if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){ 1364 log_info("denying to pin request\n"); 1365 connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST); 1366 hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address); 1367 return; 1368 } 1369 1370 if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){ 1371 connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY); 1372 log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability); 1373 if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){ 1374 // tweak authentication requirements 1375 uint8_t authreq = hci_stack->ssp_authentication_requirement; 1376 if (connection->bonding_flags & BONDING_DEDICATED){ 1377 authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING; 1378 } 1379 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){ 1380 authreq |= 1; 1381 } 1382 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq); 1383 } else { 1384 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED); 1385 } 1386 return; 1387 } 1388 1389 if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){ 1390 connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY); 1391 hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address); 1392 return; 1393 } 1394 1395 if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){ 1396 connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY); 1397 hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000); 1398 return; 1399 } 1400 1401 if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){ 1402 connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES; 1403 hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle); 1404 return; 1405 } 1406 1407 if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){ 1408 connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK; 1409 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005); // authentication failure 1410 return; 1411 } 1412 if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){ 1413 connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE; 1414 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // authentication done 1415 return; 1416 } 1417 if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){ 1418 connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST; 1419 hci_send_cmd(&hci_authentication_requested, connection->con_handle); 1420 return; 1421 } 1422 if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){ 1423 connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST; 1424 hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1); 1425 return; 1426 } 1427 } 1428 1429 switch (hci_stack->state){ 1430 case HCI_STATE_INITIALIZING: 1431 // log_info("hci_init: substate %u\n", hci_stack->substate); 1432 if (hci_stack->substate % 2) { 1433 // odd: waiting for command completion 1434 return; 1435 } 1436 switch (hci_stack->substate >> 1){ 1437 case 0: // RESET 1438 hci_send_cmd(&hci_reset); 1439 1440 if (hci_stack->config == 0 || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){ 1441 // skip baud change 1442 hci_stack->substate = 4; // >> 1 = 2 1443 } 1444 break; 1445 case 1: // SEND BAUD CHANGE 1446 hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer); 1447 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]); 1448 break; 1449 case 2: // LOCAL BAUD CHANGE 1450 hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main); 1451 hci_stack->substate += 2; 1452 // break missing here for fall through 1453 1454 case 3: 1455 // Custom initialization 1456 if (hci_stack->control && hci_stack->control->next_cmd){ 1457 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer); 1458 if (valid_cmd){ 1459 int size = 3 + hci_stack->hci_packet_buffer[2]; 1460 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 1461 hci_stack->substate = 4; // more init commands 1462 break; 1463 } 1464 log_info("hci_run: init script done\n\r"); 1465 } 1466 // otherwise continue 1467 hci_send_cmd(&hci_read_bd_addr); 1468 break; 1469 case 4: 1470 hci_send_cmd(&hci_read_buffer_size); 1471 break; 1472 case 5: 1473 hci_send_cmd(&hci_read_local_supported_features); 1474 break; 1475 case 6: 1476 if (hci_le_supported()){ 1477 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 1478 } else { 1479 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 1480 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 1481 } 1482 1483 // skip Classic init commands for LE only chipsets 1484 if (!hci_classic_supported()){ 1485 if (hci_le_supported()){ 1486 hci_stack->substate = 11 << 1; // skip all classic command 1487 } else { 1488 log_error("Neither BR/EDR nor LE supported"); 1489 hci_stack->substate = 13 << 1; // skip all 1490 } 1491 } 1492 break; 1493 case 7: 1494 if (hci_ssp_supported()){ 1495 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 1496 break; 1497 } 1498 hci_stack->substate += 2; 1499 // break missing here for fall through 1500 1501 case 8: 1502 // ca. 15 sec 1503 hci_send_cmd(&hci_write_page_timeout, 0x6000); 1504 break; 1505 case 9: 1506 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 1507 break; 1508 case 10: 1509 if (hci_stack->local_name){ 1510 hci_send_cmd(&hci_write_local_name, hci_stack->local_name); 1511 } else { 1512 char hostname[30]; 1513 #ifdef EMBEDDED 1514 // BTstack-11:22:33:44:55:66 1515 strcpy(hostname, "BTstack "); 1516 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr)); 1517 printf("---> Name %s\n", hostname); 1518 #else 1519 // hostname for POSIX systems 1520 gethostname(hostname, 30); 1521 hostname[29] = '\0'; 1522 #endif 1523 hci_send_cmd(&hci_write_local_name, hostname); 1524 } 1525 break; 1526 case 11: 1527 hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan 1528 if (!hci_le_supported()){ 1529 // SKIP LE init for Classic only configuration 1530 hci_stack->substate = 13 << 1; 1531 } 1532 break; 1533 1534 #ifdef HAVE_BLE 1535 // LE INIT 1536 case 12: 1537 hci_send_cmd(&hci_le_read_buffer_size); 1538 break; 1539 case 13: 1540 // LE Supported Host = 1, Simultaneous Host = 0 1541 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 1542 break; 1543 #endif 1544 1545 // DONE 1546 case 14: 1547 // done. 1548 hci_stack->state = HCI_STATE_WORKING; 1549 hci_emit_state(); 1550 break; 1551 default: 1552 break; 1553 } 1554 hci_stack->substate++; 1555 break; 1556 1557 case HCI_STATE_HALTING: 1558 1559 log_info("HCI_STATE_HALTING\n"); 1560 // close all open connections 1561 connection = (hci_connection_t *) hci_stack->connections; 1562 if (connection){ 1563 1564 // send disconnect 1565 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return; 1566 1567 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1568 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1569 1570 // send disconnected event right away - causes higher layer connections to get closed, too. 1571 hci_shutdown_connection(connection); 1572 return; 1573 } 1574 log_info("HCI_STATE_HALTING, calling off\n"); 1575 1576 // switch mode 1577 hci_power_control_off(); 1578 1579 log_info("HCI_STATE_HALTING, emitting state\n"); 1580 hci_emit_state(); 1581 log_info("HCI_STATE_HALTING, done\n"); 1582 break; 1583 1584 case HCI_STATE_FALLING_ASLEEP: 1585 switch(hci_stack->substate) { 1586 case 0: 1587 log_info("HCI_STATE_FALLING_ASLEEP\n"); 1588 // close all open connections 1589 connection = (hci_connection_t *) hci_stack->connections; 1590 1591 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1592 // don't close connections, if H4 supports power management 1593 if (bt_control_iphone_power_management_enabled()){ 1594 connection = NULL; 1595 } 1596 #endif 1597 if (connection){ 1598 1599 // send disconnect 1600 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1601 1602 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1603 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1604 1605 // send disconnected event right away - causes higher layer connections to get closed, too. 1606 hci_shutdown_connection(connection); 1607 return; 1608 } 1609 1610 if (hci_classic_supported()){ 1611 // disable page and inquiry scan 1612 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return; 1613 1614 log_info("HCI_STATE_HALTING, disabling inq scans\n"); 1615 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 1616 1617 // continue in next sub state 1618 hci_stack->substate++; 1619 break; 1620 } 1621 // fall through for ble-only chips 1622 1623 case 2: 1624 log_info("HCI_STATE_HALTING, calling sleep\n"); 1625 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1626 // don't actually go to sleep, if H4 supports power management 1627 if (bt_control_iphone_power_management_enabled()){ 1628 // SLEEP MODE reached 1629 hci_stack->state = HCI_STATE_SLEEPING; 1630 hci_emit_state(); 1631 break; 1632 } 1633 #endif 1634 // switch mode 1635 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 1636 hci_emit_state(); 1637 break; 1638 1639 default: 1640 break; 1641 } 1642 break; 1643 1644 default: 1645 break; 1646 } 1647 } 1648 1649 int hci_send_cmd_packet(uint8_t *packet, int size){ 1650 bd_addr_t addr; 1651 hci_connection_t * conn; 1652 // house-keeping 1653 1654 // create_connection? 1655 if (IS_COMMAND(packet, hci_create_connection)){ 1656 bt_flip_addr(addr, &packet[3]); 1657 log_info("Create_connection to %s\n", bd_addr_to_str(addr)); 1658 1659 conn = connection_for_address(addr); 1660 if (!conn){ 1661 conn = create_connection_for_addr(addr); 1662 if (!conn){ 1663 // notify client that alloc failed 1664 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 1665 return 0; // don't sent packet to controller 1666 } 1667 conn->state = SEND_CREATE_CONNECTION; 1668 } 1669 log_info("conn state %u", conn->state); 1670 switch (conn->state){ 1671 // if connection active exists 1672 case OPEN: 1673 // and OPEN, emit connection complete command, don't send to controller 1674 hci_emit_connection_complete(conn, 0); 1675 return 0; 1676 case SEND_CREATE_CONNECTION: 1677 // connection created by hci, e.g. dedicated bonding 1678 break; 1679 default: 1680 // otherwise, just ignore as it is already in the open process 1681 return 0; 1682 } 1683 conn->state = SENT_CREATE_CONNECTION; 1684 } 1685 1686 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1687 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1688 } 1689 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1690 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1691 } 1692 1693 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1694 if (hci_stack->remote_device_db){ 1695 bt_flip_addr(addr, &packet[3]); 1696 hci_stack->remote_device_db->delete_link_key(&addr); 1697 } 1698 } 1699 1700 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply) 1701 || IS_COMMAND(packet, hci_pin_code_request_reply)){ 1702 bt_flip_addr(addr, &packet[3]); 1703 conn = connection_for_address(addr); 1704 if (conn){ 1705 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 1706 } 1707 } 1708 1709 if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply) 1710 || IS_COMMAND(packet, hci_user_confirmation_request_reply) 1711 || IS_COMMAND(packet, hci_user_passkey_request_negative_reply) 1712 || IS_COMMAND(packet, hci_user_passkey_request_reply)) { 1713 bt_flip_addr(addr, &packet[3]); 1714 conn = connection_for_address(addr); 1715 if (conn){ 1716 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 1717 } 1718 } 1719 1720 #ifdef HAVE_BLE 1721 if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){ 1722 hci_stack->adv_addr_type = packet[8]; 1723 } 1724 if (IS_COMMAND(packet, hci_le_set_random_address)){ 1725 bt_flip_addr(hci_stack->adv_address, &packet[3]); 1726 } 1727 #endif 1728 1729 hci_stack->num_cmd_packets--; 1730 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 1731 1732 // free packet buffer for synchronous transport implementations 1733 if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){ 1734 hci_stack->hci_packet_buffer_reserved = 0; 1735 } 1736 1737 return err; 1738 } 1739 1740 // disconnect because of security block 1741 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 1742 hci_connection_t * connection = hci_connection_for_handle(con_handle); 1743 if (!connection) return; 1744 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 1745 } 1746 1747 1748 // Configure Secure Simple Pairing 1749 1750 // enable will enable SSP during init 1751 void hci_ssp_set_enable(int enable){ 1752 hci_stack->ssp_enable = enable; 1753 } 1754 1755 int hci_local_ssp_activated(){ 1756 return hci_ssp_supported() && hci_stack->ssp_enable; 1757 } 1758 1759 // if set, BTstack will respond to io capability request using authentication requirement 1760 void hci_ssp_set_io_capability(int io_capability){ 1761 hci_stack->ssp_io_capability = io_capability; 1762 } 1763 void hci_ssp_set_authentication_requirement(int authentication_requirement){ 1764 hci_stack->ssp_authentication_requirement = authentication_requirement; 1765 } 1766 1767 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 1768 void hci_ssp_set_auto_accept(int auto_accept){ 1769 hci_stack->ssp_auto_accept = auto_accept; 1770 } 1771 1772 /** 1773 * pre: numcmds >= 0 - it's allowed to send a command to the controller 1774 */ 1775 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 1776 va_list argptr; 1777 va_start(argptr, cmd); 1778 uint16_t size = hci_create_cmd_internal(hci_stack->hci_packet_buffer, cmd, argptr); 1779 va_end(argptr); 1780 return hci_send_cmd_packet(hci_stack->hci_packet_buffer, size); 1781 } 1782 1783 // Create various non-HCI events. 1784 // TODO: generalize, use table similar to hci_create_command 1785 1786 void hci_emit_state(){ 1787 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 1788 uint8_t event[3]; 1789 event[0] = BTSTACK_EVENT_STATE; 1790 event[1] = sizeof(event) - 2; 1791 event[2] = hci_stack->state; 1792 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1793 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1794 } 1795 1796 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 1797 uint8_t event[13]; 1798 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 1799 event[1] = sizeof(event) - 2; 1800 event[2] = status; 1801 bt_store_16(event, 3, conn->con_handle); 1802 bt_flip_addr(&event[5], conn->address); 1803 event[11] = 1; // ACL connection 1804 event[12] = 0; // encryption disabled 1805 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1806 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1807 } 1808 1809 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 1810 uint8_t event[6]; 1811 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 1812 event[1] = sizeof(event) - 2; 1813 event[2] = 0; // status = OK 1814 bt_store_16(event, 3, handle); 1815 event[5] = reason; 1816 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1817 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1818 } 1819 1820 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 1821 if (disable_l2cap_timeouts) return; 1822 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 1823 uint8_t event[4]; 1824 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 1825 event[1] = sizeof(event) - 2; 1826 bt_store_16(event, 2, conn->con_handle); 1827 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1828 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1829 } 1830 1831 void hci_emit_nr_connections_changed(){ 1832 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 1833 uint8_t event[3]; 1834 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 1835 event[1] = sizeof(event) - 2; 1836 event[2] = nr_hci_connections(); 1837 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1838 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1839 } 1840 1841 void hci_emit_hci_open_failed(){ 1842 log_info("BTSTACK_EVENT_POWERON_FAILED"); 1843 uint8_t event[2]; 1844 event[0] = BTSTACK_EVENT_POWERON_FAILED; 1845 event[1] = sizeof(event) - 2; 1846 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1847 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1848 } 1849 1850 #ifndef EMBEDDED 1851 void hci_emit_btstack_version() { 1852 log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 1853 uint8_t event[6]; 1854 event[0] = BTSTACK_EVENT_VERSION; 1855 event[1] = sizeof(event) - 2; 1856 event[2] = BTSTACK_MAJOR; 1857 event[3] = BTSTACK_MINOR; 1858 bt_store_16(event, 4, BTSTACK_REVISION); 1859 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1860 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1861 } 1862 #endif 1863 1864 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 1865 log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 1866 uint8_t event[3]; 1867 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 1868 event[1] = sizeof(event) - 2; 1869 event[2] = enabled; 1870 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1871 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1872 } 1873 1874 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 1875 uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info 1876 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 1877 event[1] = sizeof(event) - 2 - 1; 1878 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 1879 bt_flip_addr(&event[3], *addr); 1880 memcpy(&event[9], name, 248); 1881 1882 event[9+248] = 0; // assert \0 for log_info 1883 log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]); 1884 1885 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1); 1886 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1); 1887 } 1888 1889 void hci_emit_discoverable_enabled(uint8_t enabled){ 1890 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 1891 uint8_t event[3]; 1892 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 1893 event[1] = sizeof(event) - 2; 1894 event[2] = enabled; 1895 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1896 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1897 } 1898 1899 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 1900 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 1901 uint8_t event[5]; 1902 int pos = 0; 1903 event[pos++] = GAP_SECURITY_LEVEL; 1904 event[pos++] = sizeof(event) - 2; 1905 bt_store_16(event, 2, con_handle); 1906 pos += 2; 1907 event[pos++] = level; 1908 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1909 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1910 } 1911 1912 void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){ 1913 log_info("hci_emit_dedicated_bonding_result %u ", status); 1914 uint8_t event[9]; 1915 int pos = 0; 1916 event[pos++] = GAP_DEDICATED_BONDING_COMPLETED; 1917 event[pos++] = sizeof(event) - 2; 1918 event[pos++] = status; 1919 bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address); 1920 pos += 6; 1921 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1922 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1923 } 1924 1925 // query if remote side supports SSP 1926 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 1927 hci_connection_t * connection = hci_connection_for_handle(con_handle); 1928 if (!connection) return 0; 1929 return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0; 1930 } 1931 1932 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){ 1933 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 1934 } 1935 1936 // GAP API 1937 /** 1938 * @bbrief enable/disable bonding. default is enabled 1939 * @praram enabled 1940 */ 1941 void gap_set_bondable_mode(int enable){ 1942 hci_stack->bondable = enable ? 1 : 0; 1943 } 1944 1945 /** 1946 * @brief map link keys to security levels 1947 */ 1948 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 1949 switch (link_key_type){ 1950 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 1951 return LEVEL_4; 1952 case COMBINATION_KEY: 1953 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 1954 return LEVEL_3; 1955 default: 1956 return LEVEL_2; 1957 } 1958 } 1959 1960 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 1961 if (!connection) return LEVEL_0; 1962 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 1963 return gap_security_level_for_link_key_type(connection->link_key_type); 1964 } 1965 1966 1967 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 1968 printf("gap_mitm_protection_required_for_security_level %u\n", level); 1969 return level > LEVEL_2; 1970 } 1971 1972 /** 1973 * @brief get current security level 1974 */ 1975 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 1976 hci_connection_t * connection = hci_connection_for_handle(con_handle); 1977 if (!connection) return LEVEL_0; 1978 return gap_security_level_for_connection(connection); 1979 } 1980 1981 /** 1982 * @brief request connection to device to 1983 * @result GAP_AUTHENTICATION_RESULT 1984 */ 1985 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 1986 hci_connection_t * connection = hci_connection_for_handle(con_handle); 1987 if (!connection){ 1988 hci_emit_security_level(con_handle, LEVEL_0); 1989 return; 1990 } 1991 gap_security_level_t current_level = gap_security_level(con_handle); 1992 log_info("gap_request_security_level %u, current level %u", requested_level, current_level); 1993 if (current_level >= requested_level){ 1994 hci_emit_security_level(con_handle, current_level); 1995 return; 1996 } 1997 1998 connection->requested_security_level = requested_level; 1999 2000 // would enabling ecnryption suffice (>= LEVEL_2)? 2001 if (hci_stack->remote_device_db){ 2002 link_key_type_t link_key_type; 2003 link_key_t link_key; 2004 if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){ 2005 if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){ 2006 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 2007 return; 2008 } 2009 } 2010 } 2011 2012 // try to authenticate connection 2013 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2014 hci_run(); 2015 } 2016 2017 /** 2018 * @brief start dedicated bonding with device. disconnect after bonding 2019 * @param device 2020 * @param request MITM protection 2021 * @result GAP_DEDICATED_BONDING_COMPLETE 2022 */ 2023 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 2024 2025 // create connection state machine 2026 hci_connection_t * connection = create_connection_for_addr(device); 2027 2028 if (!connection){ 2029 return BTSTACK_MEMORY_ALLOC_FAILED; 2030 } 2031 2032 // delete linkn key 2033 hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device); 2034 2035 // configure LEVEL_2/3, dedicated bonding 2036 connection->state = SEND_CREATE_CONNECTION; 2037 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 2038 printf("gap_dedicated_bonding, mitm %u -> level %u\n", mitm_protection_required, connection->requested_security_level); 2039 connection->bonding_flags = BONDING_DEDICATED; 2040 2041 // wait for GAP Security Result and send GAP Dedicated Bonding complete 2042 2043 // handle: connnection failure (connection complete != ok) 2044 // handle: authentication failure 2045 // handle: disconnect on done 2046 2047 hci_run(); 2048 2049 return 0; 2050 } 2051 2052 void gap_set_local_name(const char * local_name){ 2053 hci_stack->local_name = local_name; 2054 } 2055 2056 2057