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