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