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 %u, %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 hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main); 1597 hci_stack->substate += 2; 1598 // break missing here for fall through 1599 1600 case 3: 1601 // Custom initialization 1602 if (hci_stack->control && hci_stack->control->next_cmd){ 1603 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer); 1604 if (valid_cmd){ 1605 int size = 3 + hci_stack->hci_packet_buffer[2]; 1606 hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size); 1607 hci_stack->substate = 4; // more init commands 1608 break; 1609 } 1610 log_info("hci_run: init script done\n\r"); 1611 } 1612 // otherwise continue 1613 hci_send_cmd(&hci_read_bd_addr); 1614 break; 1615 case 4: 1616 hci_send_cmd(&hci_read_buffer_size); 1617 break; 1618 case 5: 1619 hci_send_cmd(&hci_read_local_supported_features); 1620 break; 1621 case 6: 1622 if (hci_le_supported()){ 1623 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF); 1624 } else { 1625 // Kensington Bluetoot 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff... 1626 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF); 1627 } 1628 1629 // skip Classic init commands for LE only chipsets 1630 if (!hci_classic_supported()){ 1631 if (hci_le_supported()){ 1632 hci_stack->substate = 11 << 1; // skip all classic command 1633 } else { 1634 log_error("Neither BR/EDR nor LE supported"); 1635 hci_stack->substate = 14 << 1; // skip all 1636 } 1637 } 1638 break; 1639 case 7: 1640 if (hci_ssp_supported()){ 1641 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable); 1642 break; 1643 } 1644 hci_stack->substate += 2; 1645 // break missing here for fall through 1646 1647 case 8: 1648 // ca. 15 sec 1649 hci_send_cmd(&hci_write_page_timeout, 0x6000); 1650 break; 1651 case 9: 1652 hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device); 1653 break; 1654 case 10: 1655 if (hci_stack->local_name){ 1656 hci_send_cmd(&hci_write_local_name, hci_stack->local_name); 1657 } else { 1658 char hostname[30]; 1659 #ifdef EMBEDDED 1660 // BTstack-11:22:33:44:55:66 1661 strcpy(hostname, "BTstack "); 1662 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr)); 1663 printf("---> Name %s\n", hostname); 1664 #else 1665 // hostname for POSIX systems 1666 gethostname(hostname, 30); 1667 hostname[29] = '\0'; 1668 #endif 1669 hci_send_cmd(&hci_write_local_name, hostname); 1670 } 1671 break; 1672 case 11: 1673 hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan 1674 if (!hci_le_supported()){ 1675 // SKIP LE init for Classic only configuration 1676 hci_stack->substate = 14 << 1; 1677 } 1678 break; 1679 1680 #ifdef HAVE_BLE 1681 // LE INIT 1682 case 12: 1683 hci_send_cmd(&hci_le_read_buffer_size); 1684 break; 1685 case 13: 1686 // LE Supported Host = 1, Simultaneous Host = 0 1687 hci_send_cmd(&hci_write_le_host_supported, 1, 0); 1688 break; 1689 case 14: 1690 // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs 1691 hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0); 1692 break; 1693 #endif 1694 1695 // DONE 1696 case 15: 1697 // done. 1698 hci_stack->state = HCI_STATE_WORKING; 1699 hci_emit_state(); 1700 break; 1701 default: 1702 break; 1703 } 1704 hci_stack->substate++; 1705 break; 1706 1707 case HCI_STATE_HALTING: 1708 1709 log_info("HCI_STATE_HALTING\n"); 1710 // close all open connections 1711 connection = (hci_connection_t *) hci_stack->connections; 1712 if (connection){ 1713 1714 // send disconnect 1715 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return; 1716 1717 log_info("HCI_STATE_HALTING, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1718 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1719 1720 // send disconnected event right away - causes higher layer connections to get closed, too. 1721 hci_shutdown_connection(connection); 1722 return; 1723 } 1724 log_info("HCI_STATE_HALTING, calling off\n"); 1725 1726 // switch mode 1727 hci_power_control_off(); 1728 1729 log_info("HCI_STATE_HALTING, emitting state\n"); 1730 hci_emit_state(); 1731 log_info("HCI_STATE_HALTING, done\n"); 1732 break; 1733 1734 case HCI_STATE_FALLING_ASLEEP: 1735 switch(hci_stack->substate) { 1736 case 0: 1737 log_info("HCI_STATE_FALLING_ASLEEP\n"); 1738 // close all open connections 1739 connection = (hci_connection_t *) hci_stack->connections; 1740 1741 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1742 // don't close connections, if H4 supports power management 1743 if (bt_control_iphone_power_management_enabled()){ 1744 connection = NULL; 1745 } 1746 #endif 1747 if (connection){ 1748 1749 // send disconnect 1750 if (!hci_can_send_packet_now(HCI_COMMAND_DATA_PACKET)) return; 1751 1752 log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u\n", connection, (uint16_t)connection->con_handle); 1753 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection 1754 1755 // send disconnected event right away - causes higher layer connections to get closed, too. 1756 hci_shutdown_connection(connection); 1757 return; 1758 } 1759 1760 if (hci_classic_supported()){ 1761 // disable page and inquiry scan 1762 if (!hci_can_send_packet_now_using_packet_buffer(HCI_COMMAND_DATA_PACKET)) return; 1763 1764 log_info("HCI_STATE_HALTING, disabling inq scans\n"); 1765 hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan 1766 1767 // continue in next sub state 1768 hci_stack->substate++; 1769 break; 1770 } 1771 // fall through for ble-only chips 1772 1773 case 2: 1774 log_info("HCI_STATE_HALTING, calling sleep\n"); 1775 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL) 1776 // don't actually go to sleep, if H4 supports power management 1777 if (bt_control_iphone_power_management_enabled()){ 1778 // SLEEP MODE reached 1779 hci_stack->state = HCI_STATE_SLEEPING; 1780 hci_emit_state(); 1781 break; 1782 } 1783 #endif 1784 // switch mode 1785 hci_power_control_sleep(); // changes hci_stack->state to SLEEP 1786 hci_emit_state(); 1787 break; 1788 1789 default: 1790 break; 1791 } 1792 break; 1793 1794 default: 1795 break; 1796 } 1797 } 1798 1799 int hci_send_cmd_packet(uint8_t *packet, int size){ 1800 bd_addr_t addr; 1801 hci_connection_t * conn; 1802 // house-keeping 1803 1804 // create_connection? 1805 if (IS_COMMAND(packet, hci_create_connection)){ 1806 bt_flip_addr(addr, &packet[3]); 1807 log_info("Create_connection to %s\n", bd_addr_to_str(addr)); 1808 1809 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1810 if (!conn){ 1811 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC); 1812 if (!conn){ 1813 // notify client that alloc failed 1814 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 1815 return 0; // don't sent packet to controller 1816 } 1817 conn->state = SEND_CREATE_CONNECTION; 1818 } 1819 log_info("conn state %u", conn->state); 1820 switch (conn->state){ 1821 // if connection active exists 1822 case OPEN: 1823 // and OPEN, emit connection complete command, don't send to controller 1824 hci_emit_connection_complete(conn, 0); 1825 return 0; 1826 case SEND_CREATE_CONNECTION: 1827 // connection created by hci, e.g. dedicated bonding 1828 break; 1829 default: 1830 // otherwise, just ignore as it is already in the open process 1831 return 0; 1832 } 1833 conn->state = SENT_CREATE_CONNECTION; 1834 } 1835 1836 if (IS_COMMAND(packet, hci_link_key_request_reply)){ 1837 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY); 1838 } 1839 if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){ 1840 hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST); 1841 } 1842 1843 if (IS_COMMAND(packet, hci_delete_stored_link_key)){ 1844 if (hci_stack->remote_device_db){ 1845 bt_flip_addr(addr, &packet[3]); 1846 hci_stack->remote_device_db->delete_link_key(&addr); 1847 } 1848 } 1849 1850 if (IS_COMMAND(packet, hci_pin_code_request_negative_reply) 1851 || IS_COMMAND(packet, hci_pin_code_request_reply)){ 1852 bt_flip_addr(addr, &packet[3]); 1853 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1854 if (conn){ 1855 connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE); 1856 } 1857 } 1858 1859 if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply) 1860 || IS_COMMAND(packet, hci_user_confirmation_request_reply) 1861 || IS_COMMAND(packet, hci_user_passkey_request_negative_reply) 1862 || IS_COMMAND(packet, hci_user_passkey_request_reply)) { 1863 bt_flip_addr(addr, &packet[3]); 1864 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC); 1865 if (conn){ 1866 connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE); 1867 } 1868 } 1869 1870 #ifdef HAVE_BLE 1871 if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){ 1872 hci_stack->adv_addr_type = packet[8]; 1873 } 1874 if (IS_COMMAND(packet, hci_le_set_random_address)){ 1875 bt_flip_addr(hci_stack->adv_address, &packet[3]); 1876 } 1877 #endif 1878 1879 hci_stack->num_cmd_packets--; 1880 int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size); 1881 1882 // free packet buffer for synchronous transport implementations 1883 if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){ 1884 hci_stack->hci_packet_buffer_reserved = 0; 1885 } 1886 1887 return err; 1888 } 1889 1890 // disconnect because of security block 1891 void hci_disconnect_security_block(hci_con_handle_t con_handle){ 1892 hci_connection_t * connection = hci_connection_for_handle(con_handle); 1893 if (!connection) return; 1894 connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK; 1895 } 1896 1897 1898 // Configure Secure Simple Pairing 1899 1900 // enable will enable SSP during init 1901 void hci_ssp_set_enable(int enable){ 1902 hci_stack->ssp_enable = enable; 1903 } 1904 1905 int hci_local_ssp_activated(){ 1906 return hci_ssp_supported() && hci_stack->ssp_enable; 1907 } 1908 1909 // if set, BTstack will respond to io capability request using authentication requirement 1910 void hci_ssp_set_io_capability(int io_capability){ 1911 hci_stack->ssp_io_capability = io_capability; 1912 } 1913 void hci_ssp_set_authentication_requirement(int authentication_requirement){ 1914 hci_stack->ssp_authentication_requirement = authentication_requirement; 1915 } 1916 1917 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested 1918 void hci_ssp_set_auto_accept(int auto_accept){ 1919 hci_stack->ssp_auto_accept = auto_accept; 1920 } 1921 1922 /** 1923 * pre: numcmds >= 0 - it's allowed to send a command to the controller 1924 */ 1925 int hci_send_cmd(const hci_cmd_t *cmd, ...){ 1926 va_list argptr; 1927 va_start(argptr, cmd); 1928 uint16_t size = hci_create_cmd_internal(hci_stack->hci_packet_buffer, cmd, argptr); 1929 va_end(argptr); 1930 return hci_send_cmd_packet(hci_stack->hci_packet_buffer, size); 1931 } 1932 1933 // Create various non-HCI events. 1934 // TODO: generalize, use table similar to hci_create_command 1935 1936 void hci_emit_state(){ 1937 log_info("BTSTACK_EVENT_STATE %u", hci_stack->state); 1938 uint8_t event[3]; 1939 event[0] = BTSTACK_EVENT_STATE; 1940 event[1] = sizeof(event) - 2; 1941 event[2] = hci_stack->state; 1942 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 1943 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1944 } 1945 1946 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){ 1947 uint8_t event[13]; 1948 event[0] = HCI_EVENT_CONNECTION_COMPLETE; 1949 event[1] = sizeof(event) - 2; 1950 event[2] = status; 1951 bt_store_16(event, 3, conn->con_handle); 1952 bt_flip_addr(&event[5], conn->address); 1953 event[11] = 1; // ACL connection 1954 event[12] = 0; // encryption disabled 1955 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1956 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1957 } 1958 1959 void hci_emit_le_connection_complete(hci_connection_t *conn, uint8_t status){ 1960 uint8_t event[21]; 1961 event[0] = HCI_EVENT_LE_META; 1962 event[1] = sizeof(event) - 2; 1963 event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE; 1964 event[3] = status; 1965 bt_store_16(event, 4, conn->con_handle); 1966 event[6] = 0; // TODO: role 1967 event[7] = conn->address_type; 1968 bt_flip_addr(&event[8], conn->address); 1969 bt_store_16(event, 14, 0); // interval 1970 bt_store_16(event, 16, 0); // latency 1971 bt_store_16(event, 18, 0); // supervision timeout 1972 event[20] = 0; // master clock accuracy 1973 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1974 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1975 } 1976 1977 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){ 1978 uint8_t event[6]; 1979 event[0] = HCI_EVENT_DISCONNECTION_COMPLETE; 1980 event[1] = sizeof(event) - 2; 1981 event[2] = 0; // status = OK 1982 bt_store_16(event, 3, handle); 1983 event[5] = reason; 1984 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1985 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1986 } 1987 1988 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){ 1989 if (disable_l2cap_timeouts) return; 1990 log_info("L2CAP_EVENT_TIMEOUT_CHECK"); 1991 uint8_t event[4]; 1992 event[0] = L2CAP_EVENT_TIMEOUT_CHECK; 1993 event[1] = sizeof(event) - 2; 1994 bt_store_16(event, 2, conn->con_handle); 1995 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)); 1996 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 1997 } 1998 1999 void hci_emit_nr_connections_changed(){ 2000 log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections()); 2001 uint8_t event[3]; 2002 event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED; 2003 event[1] = sizeof(event) - 2; 2004 event[2] = nr_hci_connections(); 2005 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2006 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2007 } 2008 2009 void hci_emit_hci_open_failed(){ 2010 log_info("BTSTACK_EVENT_POWERON_FAILED"); 2011 uint8_t event[2]; 2012 event[0] = BTSTACK_EVENT_POWERON_FAILED; 2013 event[1] = sizeof(event) - 2; 2014 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2015 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2016 } 2017 2018 #ifndef EMBEDDED 2019 void hci_emit_btstack_version() { 2020 log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR); 2021 uint8_t event[6]; 2022 event[0] = BTSTACK_EVENT_VERSION; 2023 event[1] = sizeof(event) - 2; 2024 event[2] = BTSTACK_MAJOR; 2025 event[3] = BTSTACK_MINOR; 2026 bt_store_16(event, 4, BTSTACK_REVISION); 2027 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2028 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2029 } 2030 #endif 2031 2032 void hci_emit_system_bluetooth_enabled(uint8_t enabled){ 2033 log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled); 2034 uint8_t event[3]; 2035 event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED; 2036 event[1] = sizeof(event) - 2; 2037 event[2] = enabled; 2038 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2039 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2040 } 2041 2042 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){ 2043 uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info 2044 event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED; 2045 event[1] = sizeof(event) - 2 - 1; 2046 event[2] = 0; // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE 2047 bt_flip_addr(&event[3], *addr); 2048 memcpy(&event[9], name, 248); 2049 2050 event[9+248] = 0; // assert \0 for log_info 2051 log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]); 2052 2053 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1); 2054 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1); 2055 } 2056 2057 void hci_emit_discoverable_enabled(uint8_t enabled){ 2058 log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled); 2059 uint8_t event[3]; 2060 event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED; 2061 event[1] = sizeof(event) - 2; 2062 event[2] = enabled; 2063 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2064 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2065 } 2066 2067 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){ 2068 log_info("hci_emit_security_level %u for handle %x", level, con_handle); 2069 uint8_t event[5]; 2070 int pos = 0; 2071 event[pos++] = GAP_SECURITY_LEVEL; 2072 event[pos++] = sizeof(event) - 2; 2073 bt_store_16(event, 2, con_handle); 2074 pos += 2; 2075 event[pos++] = level; 2076 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2077 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2078 } 2079 2080 void hci_emit_dedicated_bonding_result(hci_connection_t * connection, uint8_t status){ 2081 log_info("hci_emit_dedicated_bonding_result %u ", status); 2082 uint8_t event[9]; 2083 int pos = 0; 2084 event[pos++] = GAP_DEDICATED_BONDING_COMPLETED; 2085 event[pos++] = sizeof(event) - 2; 2086 event[pos++] = status; 2087 bt_flip_addr( * (bd_addr_t *) &event[pos], connection->address); 2088 pos += 6; 2089 hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event)); 2090 hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)); 2091 } 2092 2093 // query if remote side supports SSP 2094 int hci_remote_ssp_supported(hci_con_handle_t con_handle){ 2095 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2096 if (!connection) return 0; 2097 return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0; 2098 } 2099 2100 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){ 2101 return hci_local_ssp_activated() && hci_remote_ssp_supported(handle); 2102 } 2103 2104 // GAP API 2105 /** 2106 * @bbrief enable/disable bonding. default is enabled 2107 * @praram enabled 2108 */ 2109 void gap_set_bondable_mode(int enable){ 2110 hci_stack->bondable = enable ? 1 : 0; 2111 } 2112 2113 /** 2114 * @brief map link keys to security levels 2115 */ 2116 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){ 2117 switch (link_key_type){ 2118 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256: 2119 return LEVEL_4; 2120 case COMBINATION_KEY: 2121 case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192: 2122 return LEVEL_3; 2123 default: 2124 return LEVEL_2; 2125 } 2126 } 2127 2128 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){ 2129 if (!connection) return LEVEL_0; 2130 if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0; 2131 return gap_security_level_for_link_key_type(connection->link_key_type); 2132 } 2133 2134 2135 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){ 2136 printf("gap_mitm_protection_required_for_security_level %u\n", level); 2137 return level > LEVEL_2; 2138 } 2139 2140 /** 2141 * @brief get current security level 2142 */ 2143 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){ 2144 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2145 if (!connection) return LEVEL_0; 2146 return gap_security_level_for_connection(connection); 2147 } 2148 2149 /** 2150 * @brief request connection to device to 2151 * @result GAP_AUTHENTICATION_RESULT 2152 */ 2153 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){ 2154 hci_connection_t * connection = hci_connection_for_handle(con_handle); 2155 if (!connection){ 2156 hci_emit_security_level(con_handle, LEVEL_0); 2157 return; 2158 } 2159 gap_security_level_t current_level = gap_security_level(con_handle); 2160 log_info("gap_request_security_level %u, current level %u", requested_level, current_level); 2161 if (current_level >= requested_level){ 2162 hci_emit_security_level(con_handle, current_level); 2163 return; 2164 } 2165 2166 connection->requested_security_level = requested_level; 2167 2168 // would enabling ecnryption suffice (>= LEVEL_2)? 2169 if (hci_stack->remote_device_db){ 2170 link_key_type_t link_key_type; 2171 link_key_t link_key; 2172 if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){ 2173 if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){ 2174 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST; 2175 return; 2176 } 2177 } 2178 } 2179 2180 // try to authenticate connection 2181 connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST; 2182 hci_run(); 2183 } 2184 2185 /** 2186 * @brief start dedicated bonding with device. disconnect after bonding 2187 * @param device 2188 * @param request MITM protection 2189 * @result GAP_DEDICATED_BONDING_COMPLETE 2190 */ 2191 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){ 2192 2193 // create connection state machine 2194 hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC); 2195 2196 if (!connection){ 2197 return BTSTACK_MEMORY_ALLOC_FAILED; 2198 } 2199 2200 // delete linkn key 2201 hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device); 2202 2203 // configure LEVEL_2/3, dedicated bonding 2204 connection->state = SEND_CREATE_CONNECTION; 2205 connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2; 2206 printf("gap_dedicated_bonding, mitm %u -> level %u\n", mitm_protection_required, connection->requested_security_level); 2207 connection->bonding_flags = BONDING_DEDICATED; 2208 2209 // wait for GAP Security Result and send GAP Dedicated Bonding complete 2210 2211 // handle: connnection failure (connection complete != ok) 2212 // handle: authentication failure 2213 // handle: disconnect on done 2214 2215 hci_run(); 2216 2217 return 0; 2218 } 2219 2220 void gap_set_local_name(const char * local_name){ 2221 hci_stack->local_name = local_name; 2222 } 2223 2224 le_command_status_t le_central_start_scan(){ 2225 if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK; 2226 hci_stack->le_scanning_state = LE_START_SCAN; 2227 hci_run(); 2228 return BLE_PERIPHERAL_OK; 2229 } 2230 2231 le_command_status_t le_central_stop_scan(){ 2232 if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK; 2233 hci_stack->le_scanning_state = LE_STOP_SCAN; 2234 hci_run(); 2235 return BLE_PERIPHERAL_OK; 2236 } 2237 2238 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){ 2239 hci_stack->le_scan_type = scan_type; 2240 hci_stack->le_scan_interval = scan_interval; 2241 hci_stack->le_scan_window = scan_window; 2242 hci_run(); 2243 } 2244 2245 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){ 2246 hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type); 2247 log_info("le_central_connect, conn struct %p", conn); 2248 if (!conn){ 2249 conn = create_connection_for_bd_addr_and_type(*addr, addr_type); 2250 if (!conn){ 2251 // notify client that alloc failed 2252 hci_emit_le_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED); 2253 return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller 2254 } 2255 conn->state = SEND_CREATE_CONNECTION; 2256 log_info("le_central_connect, state %u", conn->state); 2257 hci_run(); 2258 return BLE_PERIPHERAL_OK; 2259 } 2260 2261 if (!hci_is_le_connection(conn) || 2262 conn->state == SEND_CREATE_CONNECTION || 2263 conn->state == SENT_CREATE_CONNECTION) { 2264 hci_emit_le_connection_complete(conn, ERROR_CODE_COMMAND_DISALLOWED); 2265 return BLE_PERIPHERAL_IN_WRONG_STATE; 2266 } 2267 2268 log_info("le_central_connect, state %u", conn->state); 2269 hci_emit_le_connection_complete(conn, 0); 2270 hci_run(); 2271 return BLE_PERIPHERAL_OK; 2272 } 2273 2274 // @assumption: only a single outgoing LE Connection exists 2275 static hci_connection_t * le_central_get_outgoing_connection(){ 2276 linked_item_t *it; 2277 for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){ 2278 hci_connection_t * conn = (hci_connection_t *) it; 2279 if (!hci_is_le_connection(conn)) continue; 2280 switch (conn->state){ 2281 case SEND_CREATE_CONNECTION: 2282 case SENT_CREATE_CONNECTION: 2283 return conn; 2284 default: 2285 break; 2286 }; 2287 } 2288 return NULL; 2289 } 2290 2291 le_command_status_t le_central_connect_cancel(){ 2292 hci_connection_t * conn = le_central_get_outgoing_connection(); 2293 switch (conn->state){ 2294 case SEND_CREATE_CONNECTION: 2295 // skip sending create connection and emit event instead 2296 hci_emit_le_connection_complete(conn, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER); 2297 linked_list_remove(&hci_stack->connections, (linked_item_t *) conn); 2298 btstack_memory_hci_connection_free( conn ); 2299 break; 2300 case SENT_CREATE_CONNECTION: 2301 // request to send cancel connection 2302 conn->state = SEND_CANCEL_CONNECTION; 2303 hci_run(); 2304 break; 2305 default: 2306 break; 2307 } 2308 return BLE_PERIPHERAL_OK; 2309 } 2310 2311 le_command_status_t gap_disconnect(hci_con_handle_t handle){ 2312 hci_connection_t * conn = hci_connection_for_handle(handle); 2313 if (!conn){ 2314 hci_emit_disconnection_complete(handle, 0); 2315 return BLE_PERIPHERAL_OK; 2316 } 2317 conn->state = SEND_DISCONNECT; 2318 hci_run(); 2319 return BLE_PERIPHERAL_OK; 2320 } 2321 2322 void hci_disconnect_all(){ 2323 linked_list_iterator_t it; 2324 linked_list_iterator_init(&it, &hci_stack->connections); 2325 while (linked_list_iterator_has_next(&it)){ 2326 hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it); 2327 if (con->state == SENT_DISCONNECT) continue; 2328 con->state = SEND_DISCONNECT; 2329 } 2330 hci_run(); 2331 } 2332