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