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