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