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