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