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