1 /* 2 * Copyright 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <atomic> 20 #include <memory> 21 #include <unordered_set> 22 23 #include "common/bind.h" 24 #include "hci/acl_manager/assembler.h" 25 #include "hci/acl_manager/event_checkers.h" 26 #include "hci/acl_manager/round_robin_scheduler.h" 27 #include "hci/controller.h" 28 #include "os/metrics.h" 29 #include "security/security_manager_listener.h" 30 #include "security/security_module.h" 31 32 namespace bluetooth { 33 namespace hci { 34 namespace acl_manager { 35 36 struct acl_connection { acl_connectionacl_connection37 acl_connection(AddressWithType address_with_type, AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler) 38 : address_with_type_(address_with_type), 39 assembler_(new acl_manager::assembler(address_with_type, queue_down_end, handler)) {} ~acl_connectionacl_connection40 ~acl_connection() { 41 delete assembler_; 42 } 43 AddressWithType address_with_type_; 44 struct acl_manager::assembler* assembler_; 45 ConnectionManagementCallbacks* connection_management_callbacks_ = nullptr; 46 }; 47 48 struct classic_impl : public security::ISecurityManagerListener { classic_implclassic_impl49 classic_impl( 50 HciLayer* hci_layer, 51 Controller* controller, 52 os::Handler* handler, 53 RoundRobinScheduler* round_robin_scheduler, 54 bool crash_on_unknown_handle) 55 : hci_layer_(hci_layer), controller_(controller), round_robin_scheduler_(round_robin_scheduler) { 56 hci_layer_ = hci_layer; 57 controller_ = controller; 58 handler_ = handler; 59 connections.crash_on_unknown_handle_ = crash_on_unknown_handle; 60 should_accept_connection_ = common::Bind([](Address, ClassOfDevice) { return true; }); 61 acl_connection_interface_ = hci_layer_->GetAclConnectionInterface( 62 handler_->BindOn(this, &classic_impl::on_classic_event), 63 handler_->BindOn(this, &classic_impl::on_classic_disconnect), 64 handler_->BindOn(this, &classic_impl::on_read_remote_version_information)); 65 } 66 ~classic_implclassic_impl67 ~classic_impl() { 68 hci_layer_->PutAclConnectionInterface(); 69 connections.reset(); 70 security_manager_.reset(); 71 } 72 on_classic_eventclassic_impl73 void on_classic_event(EventView event_packet) { 74 EventCode event_code = event_packet.GetEventCode(); 75 switch (event_code) { 76 case EventCode::CONNECTION_COMPLETE: 77 on_connection_complete(event_packet); 78 break; 79 case EventCode::CONNECTION_REQUEST: 80 on_incoming_connection(event_packet); 81 break; 82 case EventCode::CONNECTION_PACKET_TYPE_CHANGED: 83 on_connection_packet_type_changed(event_packet); 84 break; 85 case EventCode::AUTHENTICATION_COMPLETE: 86 on_authentication_complete(event_packet); 87 break; 88 case EventCode::READ_CLOCK_OFFSET_COMPLETE: 89 on_read_clock_offset_complete(event_packet); 90 break; 91 case EventCode::MODE_CHANGE: 92 on_mode_change(event_packet); 93 break; 94 case EventCode::SNIFF_SUBRATING: 95 on_sniff_subrating(event_packet); 96 break; 97 case EventCode::QOS_SETUP_COMPLETE: 98 on_qos_setup_complete(event_packet); 99 break; 100 case EventCode::ROLE_CHANGE: 101 on_role_change(event_packet); 102 break; 103 case EventCode::FLOW_SPECIFICATION_COMPLETE: 104 on_flow_specification_complete(event_packet); 105 break; 106 case EventCode::FLUSH_OCCURRED: 107 on_flush_occurred(event_packet); 108 break; 109 case EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 110 on_read_remote_supported_features_complete(event_packet); 111 break; 112 case EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE: 113 on_read_remote_extended_features_complete(event_packet); 114 break; 115 case EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED: 116 on_link_supervision_timeout_changed(event_packet); 117 break; 118 case EventCode::CENTRAL_LINK_KEY_COMPLETE: 119 on_central_link_key_complete(event_packet); 120 break; 121 default: 122 LOG_ALWAYS_FATAL("Unhandled event code %s", EventCodeText(event_code).c_str()); 123 } 124 } 125 126 private: 127 static constexpr uint16_t kIllegalConnectionHandle = 0xffff; 128 struct { 129 private: 130 std::map<uint16_t, acl_connection> acl_connections_; 131 mutable std::mutex acl_connections_guard_; find_callbacksclassic_impl::__anon24a5f2f90108132 ConnectionManagementCallbacks* find_callbacks(uint16_t handle) { 133 auto connection = acl_connections_.find(handle); 134 if (connection == acl_connections_.end()) return nullptr; 135 return connection->second.connection_management_callbacks_; 136 } find_callbacksclassic_impl::__anon24a5f2f90108137 ConnectionManagementCallbacks* find_callbacks(const Address& address) { 138 for (auto& connection_pair : acl_connections_) { 139 if (connection_pair.second.address_with_type_.GetAddress() == address) { 140 return connection_pair.second.connection_management_callbacks_; 141 } 142 } 143 return nullptr; 144 } removeclassic_impl::__anon24a5f2f90108145 void remove(uint16_t handle) { 146 auto connection = acl_connections_.find(handle); 147 if (connection != acl_connections_.end()) { 148 connection->second.connection_management_callbacks_ = nullptr; 149 acl_connections_.erase(handle); 150 } 151 } 152 153 public: 154 bool crash_on_unknown_handle_ = false; is_emptyclassic_impl::__anon24a5f2f90108155 bool is_empty() const { 156 std::unique_lock<std::mutex> lock(acl_connections_guard_); 157 return acl_connections_.empty(); 158 } resetclassic_impl::__anon24a5f2f90108159 void reset() { 160 std::unique_lock<std::mutex> lock(acl_connections_guard_); 161 acl_connections_.clear(); 162 } invalidateclassic_impl::__anon24a5f2f90108163 void invalidate(uint16_t handle) { 164 std::unique_lock<std::mutex> lock(acl_connections_guard_); 165 remove(handle); 166 } 167 void execute( 168 uint16_t handle, 169 std::function<void(ConnectionManagementCallbacks* callbacks)> execute, 170 bool remove_afterwards = false) { 171 std::unique_lock<std::mutex> lock(acl_connections_guard_); 172 auto callbacks = find_callbacks(handle); 173 if (callbacks != nullptr) 174 execute(callbacks); 175 else 176 ASSERT_LOG(!crash_on_unknown_handle_, "Received command for unknown handle:0x%x", handle); 177 if (remove_afterwards) remove(handle); 178 } executeclassic_impl::__anon24a5f2f90108179 void execute(const Address& address, std::function<void(ConnectionManagementCallbacks* callbacks)> execute) { 180 std::unique_lock<std::mutex> lock(acl_connections_guard_); 181 auto callbacks = find_callbacks(address); 182 if (callbacks != nullptr) execute(callbacks); 183 } send_packet_upwardclassic_impl::__anon24a5f2f90108184 bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) { 185 std::unique_lock<std::mutex> lock(acl_connections_guard_); 186 auto connection = acl_connections_.find(handle); 187 if (connection != acl_connections_.end()) cb(connection->second.assembler_); 188 return connection != acl_connections_.end(); 189 } addclassic_impl::__anon24a5f2f90108190 void add( 191 uint16_t handle, 192 const AddressWithType& remote_address, 193 AclConnection::QueueDownEnd* queue_end, 194 os::Handler* handler, 195 ConnectionManagementCallbacks* connection_management_callbacks) { 196 std::unique_lock<std::mutex> lock(acl_connections_guard_); 197 auto emplace_pair = acl_connections_.emplace( 198 std::piecewise_construct, 199 std::forward_as_tuple(handle), 200 std::forward_as_tuple(remote_address, queue_end, handler)); 201 ASSERT(emplace_pair.second); // Make sure the connection is unique 202 emplace_pair.first->second.connection_management_callbacks_ = connection_management_callbacks; 203 } HACK_get_handleclassic_impl::__anon24a5f2f90108204 uint16_t HACK_get_handle(const Address& address) const { 205 std::unique_lock<std::mutex> lock(acl_connections_guard_); 206 for (auto it = acl_connections_.begin(); it != acl_connections_.end(); it++) { 207 if (it->second.address_with_type_.GetAddress() == address) { 208 return it->first; 209 } 210 } 211 return kIllegalConnectionHandle; 212 } get_addressclassic_impl::__anon24a5f2f90108213 Address get_address(uint16_t handle) const { 214 std::unique_lock<std::mutex> lock(acl_connections_guard_); 215 auto connection = acl_connections_.find(handle); 216 if (connection == acl_connections_.end()) { 217 return Address::kEmpty; 218 } 219 return connection->second.address_with_type_.GetAddress(); 220 } is_classic_link_already_connectedclassic_impl::__anon24a5f2f90108221 bool is_classic_link_already_connected(const Address& address) const { 222 std::unique_lock<std::mutex> lock(acl_connections_guard_); 223 for (const auto& connection : acl_connections_) { 224 if (connection.second.address_with_type_.GetAddress() == address) { 225 return true; 226 } 227 } 228 return false; 229 } 230 } connections; 231 232 public: send_packet_upwardclassic_impl233 bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) { 234 return connections.send_packet_upward(handle, cb); 235 } 236 on_incoming_connectionclassic_impl237 void on_incoming_connection(EventView packet) { 238 ConnectionRequestView request = ConnectionRequestView::Create(packet); 239 ASSERT(request.IsValid()); 240 Address address = request.GetBdAddr(); 241 if (client_callbacks_ == nullptr) { 242 LOG_ERROR("No callbacks to call"); 243 auto reason = RejectConnectionReason::LIMITED_RESOURCES; 244 this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason)); 245 return; 246 } 247 248 switch (request.GetLinkType()) { 249 case ConnectionRequestLinkType::SCO: 250 client_handler_->CallOn( 251 client_callbacks_, &ConnectionCallbacks::HACK_OnScoConnectRequest, address, request.GetClassOfDevice()); 252 return; 253 254 case ConnectionRequestLinkType::ACL: 255 break; 256 257 case ConnectionRequestLinkType::ESCO: 258 client_handler_->CallOn( 259 client_callbacks_, &ConnectionCallbacks::HACK_OnEscoConnectRequest, address, request.GetClassOfDevice()); 260 return; 261 262 case ConnectionRequestLinkType::UNKNOWN: 263 LOG_ERROR("Request has unknown ConnectionRequestLinkType."); 264 return; 265 } 266 267 incoming_connecting_address_set_.insert(address); 268 if (is_classic_link_already_connected(address)) { 269 auto reason = RejectConnectionReason::UNACCEPTABLE_BD_ADDR; 270 this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason)); 271 } else if (should_accept_connection_.Run(address, request.GetClassOfDevice())) { 272 this->accept_connection(address); 273 } else { 274 auto reason = RejectConnectionReason::LIMITED_RESOURCES; // TODO: determine reason 275 this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason)); 276 } 277 } 278 is_classic_link_already_connectedclassic_impl279 bool is_classic_link_already_connected(Address address) { 280 return connections.is_classic_link_already_connected(address); 281 } 282 create_connectionclassic_impl283 void create_connection(Address address) { 284 // TODO: Configure default connection parameters? 285 uint16_t packet_type = 0x4408 /* DM 1,3,5 */ | 0x8810 /*DH 1,3,5 */; 286 PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R1; 287 uint16_t clock_offset = 0; 288 ClockOffsetValid clock_offset_valid = ClockOffsetValid::INVALID; 289 CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH; 290 ASSERT(client_callbacks_ != nullptr); 291 std::unique_ptr<CreateConnectionBuilder> packet = CreateConnectionBuilder::Create( 292 address, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch); 293 294 pending_outgoing_connections_.emplace(address, std::move(packet)); 295 dequeue_next_connection(); 296 } 297 dequeue_next_connectionclassic_impl298 void dequeue_next_connection() { 299 if (incoming_connecting_address_set_.empty() && outgoing_connecting_address_.IsEmpty()) { 300 while (!pending_outgoing_connections_.empty()) { 301 LOG_INFO("Pending connections is not empty; so sending next connection"); 302 auto create_connection_packet_and_address = std::move(pending_outgoing_connections_.front()); 303 pending_outgoing_connections_.pop(); 304 if (!is_classic_link_already_connected(create_connection_packet_and_address.first)) { 305 outgoing_connecting_address_ = create_connection_packet_and_address.first; 306 acl_connection_interface_->EnqueueCommand( 307 std::move(create_connection_packet_and_address.second), 308 handler_->BindOnceOn(this, &classic_impl::on_create_connection_status)); 309 break; 310 } 311 } 312 } 313 } 314 on_create_connection_statusclassic_impl315 void on_create_connection_status(CommandStatusView status) { 316 ASSERT(status.IsValid()); 317 ASSERT(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION); 318 if (status.GetStatus() != hci::ErrorCode::SUCCESS /* = pending */) { 319 // something went wrong, but unblock queue and report to caller 320 LOG_ERROR( 321 "Failed to create connection to %s, reporting failure and continuing", 322 outgoing_connecting_address_.ToString().c_str()); 323 ASSERT(client_callbacks_ != nullptr); 324 client_handler_->Post(common::BindOnce( 325 &ConnectionCallbacks::OnConnectFail, 326 common::Unretained(client_callbacks_), 327 outgoing_connecting_address_, 328 status.GetStatus())); 329 outgoing_connecting_address_ = Address::kEmpty; 330 dequeue_next_connection(); 331 } else { 332 // everything is good, resume when a connection_complete event arrives 333 return; 334 } 335 } 336 337 enum class Initiator { 338 LOCALLY_INITIATED, 339 REMOTE_INITIATED, 340 }; 341 create_and_announce_connectionclassic_impl342 void create_and_announce_connection( 343 ConnectionCompleteView connection_complete, Role current_role, Initiator initiator) { 344 auto status = connection_complete.GetStatus(); 345 auto address = connection_complete.GetBdAddr(); 346 if (client_callbacks_ == nullptr) { 347 LOG_WARN("No client callbacks registered for connection"); 348 return; 349 } 350 if (status != ErrorCode::SUCCESS) { 351 client_handler_->Post(common::BindOnce( 352 &ConnectionCallbacks::OnConnectFail, common::Unretained(client_callbacks_), address, status)); 353 return; 354 } 355 uint16_t handle = connection_complete.GetConnectionHandle(); 356 auto queue = std::make_shared<AclConnection::Queue>(10); 357 auto queue_down_end = queue->GetDownEnd(); 358 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, queue); 359 std::unique_ptr<ClassicAclConnection> connection( 360 new ClassicAclConnection(std::move(queue), acl_connection_interface_, handle, address)); 361 connection->locally_initiated_ = initiator == Initiator::LOCALLY_INITIATED; 362 connections.add( 363 handle, 364 AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS}, 365 queue_down_end, 366 handler_, 367 connection->GetEventCallbacks([this](uint16_t handle) { this->connections.invalidate(handle); })); 368 connections.execute(address, [=](ConnectionManagementCallbacks* callbacks) { 369 if (delayed_role_change_ == nullptr) { 370 callbacks->OnRoleChange(hci::ErrorCode::SUCCESS, current_role); 371 } else if (delayed_role_change_->GetBdAddr() == address) { 372 LOG_INFO("Sending delayed role change for %s", delayed_role_change_->GetBdAddr().ToString().c_str()); 373 callbacks->OnRoleChange(delayed_role_change_->GetStatus(), delayed_role_change_->GetNewRole()); 374 delayed_role_change_.reset(); 375 } 376 }); 377 client_handler_->Post(common::BindOnce( 378 &ConnectionCallbacks::OnConnectSuccess, common::Unretained(client_callbacks_), std::move(connection))); 379 } 380 on_connection_completeclassic_impl381 void on_connection_complete(EventView packet) { 382 ConnectionCompleteView connection_complete = ConnectionCompleteView::Create(packet); 383 ASSERT(connection_complete.IsValid()); 384 auto status = connection_complete.GetStatus(); 385 auto address = connection_complete.GetBdAddr(); 386 Role current_role = Role::CENTRAL; 387 auto initiator = Initiator::LOCALLY_INITIATED; 388 if (outgoing_connecting_address_ == address) { 389 outgoing_connecting_address_ = Address::kEmpty; 390 } else { 391 auto incoming_address = incoming_connecting_address_set_.find(address); 392 if (incoming_address == incoming_connecting_address_set_.end()) { 393 ASSERT_LOG( 394 status != ErrorCode::UNKNOWN_CONNECTION, 395 "No prior connection request for %s expecting:%s", 396 address.ToString().c_str(), 397 set_of_incoming_connecting_addresses().c_str()); 398 LOG_WARN("No matching connection to %s (%s)", address.ToString().c_str(), ErrorCodeText(status).c_str()); 399 LOG_WARN("Firmware error after RemoteNameRequestCancel?"); 400 return; 401 } 402 incoming_connecting_address_set_.erase(incoming_address); 403 current_role = Role::PERIPHERAL; 404 initiator = Initiator::REMOTE_INITIATED; 405 } 406 create_and_announce_connection(connection_complete, current_role, initiator); 407 dequeue_next_connection(); 408 } 409 cancel_connectclassic_impl410 void cancel_connect(Address address) { 411 if (outgoing_connecting_address_ == address) { 412 LOG_INFO("Cannot cancel non-existent connection to %s", address.ToString().c_str()); 413 return; 414 } 415 std::unique_ptr<CreateConnectionCancelBuilder> packet = CreateConnectionCancelBuilder::Create(address); 416 acl_connection_interface_->EnqueueCommand( 417 std::move(packet), handler_->BindOnce(&check_command_complete<CreateConnectionCancelCompleteView>)); 418 } 419 420 static constexpr bool kRemoveConnectionAfterwards = true; on_classic_disconnectclassic_impl421 void on_classic_disconnect(uint16_t handle, ErrorCode reason) { 422 bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_; 423 bluetooth::os::LogMetricBluetoothDisconnectionReasonReported( 424 static_cast<uint32_t>(reason), connections.get_address(handle), handle); 425 connections.crash_on_unknown_handle_ = false; 426 connections.execute( 427 handle, 428 [=](ConnectionManagementCallbacks* callbacks) { 429 round_robin_scheduler_->Unregister(handle); 430 callbacks->OnDisconnection(reason); 431 }, 432 kRemoveConnectionAfterwards); 433 // This handle is probably for SCO, so we use the callback workaround. 434 if (non_acl_disconnect_callback_ != nullptr) { 435 non_acl_disconnect_callback_(handle, static_cast<uint8_t>(reason)); 436 } 437 connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers; 438 } 439 on_connection_packet_type_changedclassic_impl440 void on_connection_packet_type_changed(EventView packet) { 441 ConnectionPacketTypeChangedView packet_type_changed = ConnectionPacketTypeChangedView::Create(packet); 442 if (!packet_type_changed.IsValid()) { 443 LOG_ERROR("Received on_connection_packet_type_changed with invalid packet"); 444 return; 445 } else if (packet_type_changed.GetStatus() != ErrorCode::SUCCESS) { 446 auto status = packet_type_changed.GetStatus(); 447 std::string error_code = ErrorCodeText(status); 448 LOG_ERROR("Received on_connection_packet_type_changed with error code %s", error_code.c_str()); 449 return; 450 } 451 uint16_t handle = packet_type_changed.GetConnectionHandle(); 452 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 453 // We don't handle this event; we didn't do this in legacy stack either. 454 }); 455 } 456 on_central_link_key_completeclassic_impl457 void on_central_link_key_complete(EventView packet) { 458 CentralLinkKeyCompleteView complete_view = CentralLinkKeyCompleteView::Create(packet); 459 if (!complete_view.IsValid()) { 460 LOG_ERROR("Received on_central_link_key_complete with invalid packet"); 461 return; 462 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 463 auto status = complete_view.GetStatus(); 464 std::string error_code = ErrorCodeText(status); 465 LOG_ERROR("Received on_central_link_key_complete with error code %s", error_code.c_str()); 466 return; 467 } 468 uint16_t handle = complete_view.GetConnectionHandle(); 469 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 470 KeyFlag key_flag = complete_view.GetKeyFlag(); 471 callbacks->OnCentralLinkKeyComplete(key_flag); 472 }); 473 } 474 on_authentication_completeclassic_impl475 void on_authentication_complete(EventView packet) { 476 AuthenticationCompleteView authentication_complete = AuthenticationCompleteView::Create(packet); 477 if (!authentication_complete.IsValid()) { 478 LOG_ERROR("Received on_authentication_complete with invalid packet"); 479 return; 480 } 481 uint16_t handle = authentication_complete.GetConnectionHandle(); 482 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 483 callbacks->OnAuthenticationComplete(authentication_complete.GetStatus()); 484 }); 485 } 486 on_change_connection_link_key_completeclassic_impl487 void on_change_connection_link_key_complete(EventView packet) { 488 ChangeConnectionLinkKeyCompleteView complete_view = ChangeConnectionLinkKeyCompleteView::Create(packet); 489 if (!complete_view.IsValid()) { 490 LOG_ERROR("Received on_change_connection_link_key_complete with invalid packet"); 491 return; 492 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 493 auto status = complete_view.GetStatus(); 494 std::string error_code = ErrorCodeText(status); 495 LOG_ERROR("Received on_change_connection_link_key_complete with error code %s", error_code.c_str()); 496 return; 497 } 498 uint16_t handle = complete_view.GetConnectionHandle(); 499 connections.execute( 500 handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnChangeConnectionLinkKeyComplete(); }); 501 } 502 on_read_clock_offset_completeclassic_impl503 void on_read_clock_offset_complete(EventView packet) { 504 ReadClockOffsetCompleteView complete_view = ReadClockOffsetCompleteView::Create(packet); 505 if (!complete_view.IsValid()) { 506 LOG_ERROR("Received on_read_clock_offset_complete with invalid packet"); 507 return; 508 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 509 auto status = complete_view.GetStatus(); 510 std::string error_code = ErrorCodeText(status); 511 LOG_ERROR("Received on_read_clock_offset_complete with error code %s", error_code.c_str()); 512 return; 513 } 514 uint16_t handle = complete_view.GetConnectionHandle(); 515 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 516 uint16_t clock_offset = complete_view.GetClockOffset(); 517 callbacks->OnReadClockOffsetComplete(clock_offset); 518 }); 519 } 520 on_mode_changeclassic_impl521 void on_mode_change(EventView packet) { 522 ModeChangeView mode_change_view = ModeChangeView::Create(packet); 523 if (!mode_change_view.IsValid()) { 524 LOG_ERROR("Received on_mode_change with invalid packet"); 525 return; 526 } 527 uint16_t handle = mode_change_view.GetConnectionHandle(); 528 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 529 callbacks->OnModeChange( 530 mode_change_view.GetStatus(), mode_change_view.GetCurrentMode(), mode_change_view.GetInterval()); 531 }); 532 } 533 on_sniff_subratingclassic_impl534 void on_sniff_subrating(EventView packet) { 535 SniffSubratingEventView sniff_subrating_view = SniffSubratingEventView::Create(packet); 536 if (!sniff_subrating_view.IsValid()) { 537 LOG_ERROR("Received on_sniff_subrating with invalid packet"); 538 return; 539 } 540 uint16_t handle = sniff_subrating_view.GetConnectionHandle(); 541 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 542 callbacks->OnSniffSubrating( 543 sniff_subrating_view.GetStatus(), 544 sniff_subrating_view.GetMaximumTransmitLatency(), 545 sniff_subrating_view.GetMaximumReceiveLatency(), 546 sniff_subrating_view.GetMinimumRemoteTimeout(), 547 sniff_subrating_view.GetMinimumLocalTimeout()); 548 }); 549 } 550 on_qos_setup_completeclassic_impl551 void on_qos_setup_complete(EventView packet) { 552 QosSetupCompleteView complete_view = QosSetupCompleteView::Create(packet); 553 if (!complete_view.IsValid()) { 554 LOG_ERROR("Received on_qos_setup_complete with invalid packet"); 555 return; 556 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 557 auto status = complete_view.GetStatus(); 558 std::string error_code = ErrorCodeText(status); 559 LOG_ERROR("Received on_qos_setup_complete with error code %s", error_code.c_str()); 560 return; 561 } 562 uint16_t handle = complete_view.GetConnectionHandle(); 563 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 564 ServiceType service_type = complete_view.GetServiceType(); 565 uint32_t token_rate = complete_view.GetTokenRate(); 566 uint32_t peak_bandwidth = complete_view.GetPeakBandwidth(); 567 uint32_t latency = complete_view.GetLatency(); 568 uint32_t delay_variation = complete_view.GetDelayVariation(); 569 callbacks->OnQosSetupComplete(service_type, token_rate, peak_bandwidth, latency, delay_variation); 570 }); 571 } 572 on_flow_specification_completeclassic_impl573 void on_flow_specification_complete(EventView packet) { 574 FlowSpecificationCompleteView complete_view = FlowSpecificationCompleteView::Create(packet); 575 if (!complete_view.IsValid()) { 576 LOG_ERROR("Received on_flow_specification_complete with invalid packet"); 577 return; 578 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 579 auto status = complete_view.GetStatus(); 580 std::string error_code = ErrorCodeText(status); 581 LOG_ERROR("Received on_flow_specification_complete with error code %s", error_code.c_str()); 582 return; 583 } 584 uint16_t handle = complete_view.GetConnectionHandle(); 585 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 586 FlowDirection flow_direction = complete_view.GetFlowDirection(); 587 ServiceType service_type = complete_view.GetServiceType(); 588 uint32_t token_rate = complete_view.GetTokenRate(); 589 uint32_t token_bucket_size = complete_view.GetTokenBucketSize(); 590 uint32_t peak_bandwidth = complete_view.GetPeakBandwidth(); 591 uint32_t access_latency = complete_view.GetAccessLatency(); 592 callbacks->OnFlowSpecificationComplete( 593 flow_direction, service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency); 594 }); 595 } 596 on_flush_occurredclassic_impl597 void on_flush_occurred(EventView packet) { 598 FlushOccurredView flush_occurred_view = FlushOccurredView::Create(packet); 599 if (!flush_occurred_view.IsValid()) { 600 LOG_ERROR("Received on_flush_occurred with invalid packet"); 601 return; 602 } 603 uint16_t handle = flush_occurred_view.GetConnectionHandle(); 604 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); }); 605 } 606 on_read_remote_version_informationclassic_impl607 void on_read_remote_version_information( 608 hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) { 609 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 610 callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version); 611 }); 612 } 613 on_read_remote_supported_features_completeclassic_impl614 void on_read_remote_supported_features_complete(EventView packet) { 615 auto view = ReadRemoteSupportedFeaturesCompleteView::Create(packet); 616 ASSERT_LOG(view.IsValid(), "Read remote supported features packet invalid"); 617 uint16_t handle = view.GetConnectionHandle(); 618 bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures( 619 connections.get_address(handle), 0, view.GetLmpFeatures(), handle); 620 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 621 callbacks->OnReadRemoteSupportedFeaturesComplete(view.GetLmpFeatures()); 622 }); 623 } 624 on_read_remote_extended_features_completeclassic_impl625 void on_read_remote_extended_features_complete(EventView packet) { 626 auto view = ReadRemoteExtendedFeaturesCompleteView::Create(packet); 627 ASSERT_LOG(view.IsValid(), "Read remote extended features packet invalid"); 628 uint16_t handle = view.GetConnectionHandle(); 629 bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures( 630 connections.get_address(handle), view.GetPageNumber(), view.GetExtendedLmpFeatures(), handle); 631 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 632 callbacks->OnReadRemoteExtendedFeaturesComplete( 633 view.GetPageNumber(), view.GetMaximumPageNumber(), view.GetExtendedLmpFeatures()); 634 }); 635 } 636 OnEncryptionStateChangedclassic_impl637 void OnEncryptionStateChanged(EncryptionChangeView encryption_change_view) override { 638 if (!encryption_change_view.IsValid()) { 639 LOG_ERROR("Invalid packet"); 640 return; 641 } else if (encryption_change_view.GetStatus() != ErrorCode::SUCCESS) { 642 auto status = encryption_change_view.GetStatus(); 643 std::string error_code = ErrorCodeText(status); 644 LOG_ERROR("error_code %s", error_code.c_str()); 645 return; 646 } 647 uint16_t handle = encryption_change_view.GetConnectionHandle(); 648 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 649 EncryptionEnabled enabled = encryption_change_view.GetEncryptionEnabled(); 650 callbacks->OnEncryptionChange(enabled); 651 }); 652 } 653 on_role_changeclassic_impl654 void on_role_change(EventView packet) { 655 RoleChangeView role_change_view = RoleChangeView::Create(packet); 656 if (!role_change_view.IsValid()) { 657 LOG_ERROR("Received on_role_change with invalid packet"); 658 return; 659 } 660 auto hci_status = role_change_view.GetStatus(); 661 Address bd_addr = role_change_view.GetBdAddr(); 662 Role new_role = role_change_view.GetNewRole(); 663 bool sent = false; 664 connections.execute(bd_addr, [=, &sent](ConnectionManagementCallbacks* callbacks) { 665 if (callbacks != nullptr) { 666 callbacks->OnRoleChange(hci_status, new_role); 667 sent = true; 668 } 669 }); 670 if (!sent) { 671 if (delayed_role_change_ != nullptr) { 672 LOG_WARN("Second delayed role change (@%s dropped)", delayed_role_change_->GetBdAddr().ToString().c_str()); 673 } 674 LOG_INFO( 675 "Role change for %s with no matching connection (new role: %s)", 676 role_change_view.GetBdAddr().ToString().c_str(), 677 RoleText(role_change_view.GetNewRole()).c_str()); 678 delayed_role_change_ = std::make_unique<RoleChangeView>(role_change_view); 679 } 680 } 681 on_link_supervision_timeout_changedclassic_impl682 void on_link_supervision_timeout_changed(EventView packet) { 683 auto view = LinkSupervisionTimeoutChangedView::Create(packet); 684 ASSERT_LOG(view.IsValid(), "Link supervision timeout changed packet invalid"); 685 LOG_INFO("UNIMPLEMENTED called"); 686 } 687 on_accept_connection_statusclassic_impl688 void on_accept_connection_status(Address address, CommandStatusView status) { 689 auto accept_status = AcceptConnectionRequestStatusView::Create(status); 690 ASSERT(accept_status.IsValid()); 691 if (status.GetStatus() != ErrorCode::SUCCESS) { 692 cancel_connect(address); 693 } 694 } 695 central_link_keyclassic_impl696 void central_link_key(KeyFlag key_flag) { 697 std::unique_ptr<CentralLinkKeyBuilder> packet = CentralLinkKeyBuilder::Create(key_flag); 698 acl_connection_interface_->EnqueueCommand( 699 std::move(packet), handler_->BindOnce(&check_command_status<CentralLinkKeyStatusView>)); 700 } 701 switch_roleclassic_impl702 void switch_role(Address address, Role role) { 703 std::unique_ptr<SwitchRoleBuilder> packet = SwitchRoleBuilder::Create(address, role); 704 acl_connection_interface_->EnqueueCommand( 705 std::move(packet), handler_->BindOnce(&check_command_status<SwitchRoleStatusView>)); 706 } 707 write_default_link_policy_settingsclassic_impl708 void write_default_link_policy_settings(uint16_t default_link_policy_settings) { 709 std::unique_ptr<WriteDefaultLinkPolicySettingsBuilder> packet = 710 WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings); 711 acl_connection_interface_->EnqueueCommand( 712 std::move(packet), handler_->BindOnce(&check_command_complete<WriteDefaultLinkPolicySettingsCompleteView>)); 713 } 714 accept_connectionclassic_impl715 void accept_connection(Address address) { 716 auto role = AcceptConnectionRequestRole::BECOME_CENTRAL; // We prefer to be central 717 acl_connection_interface_->EnqueueCommand( 718 AcceptConnectionRequestBuilder::Create(address, role), 719 handler_->BindOnceOn(this, &classic_impl::on_accept_connection_status, address)); 720 } 721 reject_connectionclassic_impl722 void reject_connection(std::unique_ptr<RejectConnectionRequestBuilder> builder) { 723 acl_connection_interface_->EnqueueCommand( 724 std::move(builder), handler_->BindOnce(&check_command_status<RejectConnectionRequestStatusView>)); 725 } 726 OnDeviceBondedclassic_impl727 void OnDeviceBonded(bluetooth::hci::AddressWithType device) override {} OnDeviceUnbondedclassic_impl728 void OnDeviceUnbonded(bluetooth::hci::AddressWithType device) override {} OnDeviceBondFailedclassic_impl729 void OnDeviceBondFailed(bluetooth::hci::AddressWithType device, security::PairingFailure status) override {} 730 set_security_moduleclassic_impl731 void set_security_module(security::SecurityModule* security_module) { 732 security_manager_ = security_module->GetSecurityManager(); 733 security_manager_->RegisterCallbackListener(this, handler_); 734 } 735 HACK_get_handleclassic_impl736 uint16_t HACK_get_handle(Address address) { 737 return connections.HACK_get_handle(address); 738 } 739 HACK_SetNonAclDisconnectCallbackclassic_impl740 void HACK_SetNonAclDisconnectCallback(std::function<void(uint16_t, uint8_t)> callback) { 741 non_acl_disconnect_callback_ = callback; 742 } 743 handle_register_callbacksclassic_impl744 void handle_register_callbacks(ConnectionCallbacks* callbacks, os::Handler* handler) { 745 ASSERT(client_callbacks_ == nullptr); 746 ASSERT(client_handler_ == nullptr); 747 client_callbacks_ = callbacks; 748 client_handler_ = handler; 749 } 750 handle_unregister_callbacksclassic_impl751 void handle_unregister_callbacks(ConnectionCallbacks* callbacks, std::promise<void> promise) { 752 ASSERT_LOG(client_callbacks_ == callbacks, "Registered callback entity is different then unregister request"); 753 client_callbacks_ = nullptr; 754 client_handler_ = nullptr; 755 promise.set_value(); 756 } 757 758 HciLayer* hci_layer_ = nullptr; 759 Controller* controller_ = nullptr; 760 RoundRobinScheduler* round_robin_scheduler_ = nullptr; 761 AclConnectionInterface* acl_connection_interface_ = nullptr; 762 os::Handler* handler_ = nullptr; 763 ConnectionCallbacks* client_callbacks_ = nullptr; 764 os::Handler* client_handler_ = nullptr; 765 Address outgoing_connecting_address_{Address::kEmpty}; 766 std::unordered_set<Address> incoming_connecting_address_set_; set_of_incoming_connecting_addressesclassic_impl767 const std::string set_of_incoming_connecting_addresses() const { 768 std::stringstream buffer; 769 for (const auto& c : incoming_connecting_address_set_) buffer << " " << c; 770 return buffer.str(); 771 } 772 773 common::Callback<bool(Address, ClassOfDevice)> should_accept_connection_; 774 std::queue<std::pair<Address, std::unique_ptr<CreateConnectionBuilder>>> pending_outgoing_connections_; 775 std::unique_ptr<RoleChangeView> delayed_role_change_ = nullptr; 776 777 std::unique_ptr<security::SecurityManager> security_manager_; 778 779 std::function<void(uint16_t, uint8_t)> non_acl_disconnect_callback_; 780 }; 781 782 } // namespace acl_manager 783 } // namespace hci 784 } // namespace bluetooth 785