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 <bluetooth/log.h> 20 21 #include <memory> 22 23 #include "common/bind.h" 24 #include "hci/acl_manager/acl_scheduler.h" 25 #include "hci/acl_manager/assembler.h" 26 #include "hci/acl_manager/connection_callbacks.h" 27 #include "hci/acl_manager/connection_management_callbacks.h" 28 #include "hci/acl_manager/round_robin_scheduler.h" 29 #include "hci/class_of_device.h" 30 #include "hci/controller.h" 31 #include "hci/event_checkers.h" 32 #include "hci/hci_layer.h" 33 #include "hci/remote_name_request.h" 34 #include "metrics/bluetooth_event.h" 35 #include "os/metrics.h" 36 37 namespace bluetooth { 38 namespace hci { 39 namespace acl_manager { 40 41 struct acl_connection { acl_connectionacl_connection42 acl_connection(AddressWithType address_with_type, AclConnection::QueueDownEnd* queue_down_end, 43 os::Handler* handler) 44 : address_with_type_(address_with_type), 45 assembler_(new acl_manager::assembler(address_with_type, queue_down_end, handler)) {} ~acl_connectionacl_connection46 ~acl_connection() { delete assembler_; } 47 AddressWithType address_with_type_; 48 struct acl_manager::assembler* assembler_; 49 ConnectionManagementCallbacks* connection_management_callbacks_ = nullptr; 50 }; 51 52 struct classic_impl { classic_implclassic_impl53 classic_impl(HciLayer* hci_layer, Controller* controller, os::Handler* handler, 54 RoundRobinScheduler* round_robin_scheduler, bool crash_on_unknown_handle, 55 AclScheduler* acl_scheduler, RemoteNameRequestModule* remote_name_request_module) 56 : hci_layer_(hci_layer), 57 controller_(controller), 58 round_robin_scheduler_(round_robin_scheduler), 59 acl_scheduler_(acl_scheduler), 60 remote_name_request_module_(remote_name_request_module) { 61 hci_layer_ = hci_layer; 62 controller_ = controller; 63 handler_ = handler; 64 connections.crash_on_unknown_handle_ = crash_on_unknown_handle; 65 should_accept_connection_ = common::Bind([](Address, ClassOfDevice) { return true; }); 66 acl_connection_interface_ = hci_layer_->GetAclConnectionInterface( 67 handler_->BindOn(this, &classic_impl::on_classic_event), 68 handler_->BindOn(this, &classic_impl::on_classic_disconnect), 69 handler_->BindOn(this, &classic_impl::on_incoming_connection), 70 handler_->BindOn(this, &classic_impl::on_read_remote_version_information)); 71 } 72 ~classic_implclassic_impl73 ~classic_impl() { 74 hci_layer_->PutAclConnectionInterface(); 75 connections.reset(); 76 } 77 on_classic_eventclassic_impl78 void on_classic_event(EventView event_packet) { 79 EventCode event_code = event_packet.GetEventCode(); 80 switch (event_code) { 81 case EventCode::CONNECTION_COMPLETE: 82 on_connection_complete(event_packet); 83 break; 84 case EventCode::CONNECTION_PACKET_TYPE_CHANGED: 85 on_connection_packet_type_changed(event_packet); 86 break; 87 case EventCode::AUTHENTICATION_COMPLETE: 88 on_authentication_complete(event_packet); 89 break; 90 case EventCode::READ_CLOCK_OFFSET_COMPLETE: 91 on_read_clock_offset_complete(event_packet); 92 break; 93 case EventCode::MODE_CHANGE: 94 on_mode_change(event_packet); 95 break; 96 case EventCode::SNIFF_SUBRATING: 97 on_sniff_subrating(event_packet); 98 break; 99 case EventCode::QOS_SETUP_COMPLETE: 100 on_qos_setup_complete(event_packet); 101 break; 102 case EventCode::ROLE_CHANGE: 103 on_role_change(event_packet); 104 break; 105 case EventCode::FLOW_SPECIFICATION_COMPLETE: 106 on_flow_specification_complete(event_packet); 107 break; 108 case EventCode::FLUSH_OCCURRED: 109 on_flush_occurred(event_packet); 110 break; 111 case EventCode::ENHANCED_FLUSH_COMPLETE: 112 on_enhanced_flush_complete(event_packet); 113 break; 114 case EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: 115 on_read_remote_supported_features_complete(event_packet); 116 break; 117 case EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE: 118 on_read_remote_extended_features_complete(event_packet); 119 break; 120 case EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED: 121 on_link_supervision_timeout_changed(event_packet); 122 break; 123 case EventCode::CENTRAL_LINK_KEY_COMPLETE: 124 on_central_link_key_complete(event_packet); 125 break; 126 default: 127 log::fatal("Unhandled event code {}", EventCodeText(event_code)); 128 } 129 } 130 131 private: 132 static constexpr uint16_t kIllegalConnectionHandle = 0xffff; 133 struct { 134 private: 135 std::map<uint16_t, acl_connection> acl_connections_; 136 mutable std::mutex acl_connections_guard_; find_callbacksclassic_impl::__anonab2abec30108137 ConnectionManagementCallbacks* find_callbacks(uint16_t handle) { 138 auto connection = acl_connections_.find(handle); 139 if (connection == acl_connections_.end()) { 140 return nullptr; 141 } 142 return connection->second.connection_management_callbacks_; 143 } find_callbacksclassic_impl::__anonab2abec30108144 ConnectionManagementCallbacks* find_callbacks(const Address& address) { 145 for (auto& connection_pair : acl_connections_) { 146 if (connection_pair.second.address_with_type_.GetAddress() == address) { 147 return connection_pair.second.connection_management_callbacks_; 148 } 149 } 150 return nullptr; 151 } removeclassic_impl::__anonab2abec30108152 void remove(uint16_t handle) { 153 auto connection = acl_connections_.find(handle); 154 if (connection != acl_connections_.end()) { 155 connection->second.connection_management_callbacks_ = nullptr; 156 acl_connections_.erase(handle); 157 } 158 } 159 160 public: 161 bool crash_on_unknown_handle_ = false; is_emptyclassic_impl::__anonab2abec30108162 bool is_empty() const { 163 std::unique_lock<std::mutex> lock(acl_connections_guard_); 164 return acl_connections_.empty(); 165 } resetclassic_impl::__anonab2abec30108166 void reset() { 167 std::unique_lock<std::mutex> lock(acl_connections_guard_); 168 acl_connections_.clear(); 169 } invalidateclassic_impl::__anonab2abec30108170 void invalidate(uint16_t handle) { 171 std::unique_lock<std::mutex> lock(acl_connections_guard_); 172 remove(handle); 173 } 174 void execute(uint16_t handle, 175 std::function<void(ConnectionManagementCallbacks* callbacks)> execute, 176 bool remove_afterwards = false) { 177 std::unique_lock<std::mutex> lock(acl_connections_guard_); 178 auto callbacks = find_callbacks(handle); 179 if (callbacks != nullptr) { 180 execute(callbacks); 181 } else { 182 log::assert_that(!crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}", 183 handle); 184 } 185 if (remove_afterwards) { 186 remove(handle); 187 } 188 } executeclassic_impl::__anonab2abec30108189 void execute(const Address& address, 190 std::function<void(ConnectionManagementCallbacks* callbacks)> execute) { 191 std::unique_lock<std::mutex> lock(acl_connections_guard_); 192 auto callbacks = find_callbacks(address); 193 if (callbacks != nullptr) { 194 execute(callbacks); 195 } 196 } send_packet_upwardclassic_impl::__anonab2abec30108197 bool send_packet_upward(uint16_t handle, 198 std::function<void(struct acl_manager::assembler* assembler)> cb) { 199 std::unique_lock<std::mutex> lock(acl_connections_guard_); 200 auto connection = acl_connections_.find(handle); 201 if (connection != acl_connections_.end()) { 202 cb(connection->second.assembler_); 203 } 204 return connection != acl_connections_.end(); 205 } addclassic_impl::__anonab2abec30108206 void add(uint16_t handle, const AddressWithType& remote_address, 207 AclConnection::QueueDownEnd* queue_end, os::Handler* handler, 208 ConnectionManagementCallbacks* connection_management_callbacks) { 209 std::unique_lock<std::mutex> lock(acl_connections_guard_); 210 auto emplace_pair = 211 acl_connections_.emplace(std::piecewise_construct, std::forward_as_tuple(handle), 212 std::forward_as_tuple(remote_address, queue_end, handler)); 213 log::assert_that(emplace_pair.second, 214 "assert failed: emplace_pair.second"); // Make sure the connection is unique 215 emplace_pair.first->second.connection_management_callbacks_ = connection_management_callbacks; 216 } HACK_get_handleclassic_impl::__anonab2abec30108217 uint16_t HACK_get_handle(const Address& address) const { 218 std::unique_lock<std::mutex> lock(acl_connections_guard_); 219 for (auto it = acl_connections_.begin(); it != acl_connections_.end(); it++) { 220 if (it->second.address_with_type_.GetAddress() == address) { 221 return it->first; 222 } 223 } 224 return kIllegalConnectionHandle; 225 } get_addressclassic_impl::__anonab2abec30108226 Address get_address(uint16_t handle) const { 227 std::unique_lock<std::mutex> lock(acl_connections_guard_); 228 auto connection = acl_connections_.find(handle); 229 if (connection == acl_connections_.end()) { 230 return Address::kEmpty; 231 } 232 return connection->second.address_with_type_.GetAddress(); 233 } is_classic_link_already_connectedclassic_impl::__anonab2abec30108234 bool is_classic_link_already_connected(const Address& address) const { 235 std::unique_lock<std::mutex> lock(acl_connections_guard_); 236 for (const auto& connection : acl_connections_) { 237 if (connection.second.address_with_type_.GetAddress() == address) { 238 return true; 239 } 240 } 241 return false; 242 } 243 } connections; 244 245 public: send_packet_upwardclassic_impl246 bool send_packet_upward(uint16_t handle, 247 std::function<void(struct acl_manager::assembler* assembler)> cb) { 248 return connections.send_packet_upward(handle, cb); 249 } 250 on_incoming_connectionclassic_impl251 void on_incoming_connection(Address address, ClassOfDevice cod) { 252 if (client_callbacks_ == nullptr) { 253 log::error("No callbacks to call"); 254 auto reason = RejectConnectionReason::LIMITED_RESOURCES; 255 this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason)); 256 return; 257 } 258 259 client_handler_->CallOn(client_callbacks_, &ConnectionCallbacks::OnConnectRequest, address, 260 cod); 261 262 bluetooth::metrics::LogIncomingAclStartEvent(address); 263 264 acl_scheduler_->RegisterPendingIncomingConnection(address); 265 266 if (is_classic_link_already_connected(address)) { 267 auto reason = RejectConnectionReason::UNACCEPTABLE_BD_ADDR; 268 this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason)); 269 } else if (should_accept_connection_.Run(address, cod)) { 270 this->accept_connection(address); 271 } else { 272 auto reason = RejectConnectionReason::LIMITED_RESOURCES; // TODO: determine reason 273 this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason)); 274 } 275 } 276 is_classic_link_already_connectedclassic_impl277 bool is_classic_link_already_connected(Address address) { 278 return connections.is_classic_link_already_connected(address); 279 } 280 create_connectionclassic_impl281 void create_connection(Address address) { 282 // TODO: Configure default connection parameters? 283 uint16_t packet_type = 0x4408 /* DM 1,3,5 */ | 0x8810 /*DH 1,3,5 */; 284 PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R1; 285 uint16_t clock_offset = 0; 286 ClockOffsetValid clock_offset_valid = ClockOffsetValid::INVALID; 287 CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH; 288 log::assert_that(client_callbacks_ != nullptr, "assert failed: client_callbacks_ != nullptr"); 289 std::unique_ptr<CreateConnectionBuilder> packet = 290 CreateConnectionBuilder::Create(address, packet_type, page_scan_repetition_mode, 291 clock_offset, clock_offset_valid, allow_role_switch); 292 293 acl_scheduler_->EnqueueOutgoingAclConnection( 294 address, handler_->BindOnceOn(this, &classic_impl::actually_create_connection, address, 295 std::move(packet))); 296 } 297 actually_create_connectionclassic_impl298 void actually_create_connection(Address address, 299 std::unique_ptr<CreateConnectionBuilder> packet) { 300 if (is_classic_link_already_connected(address)) { 301 log::warn("already connected: {}", address); 302 acl_scheduler_->ReportOutgoingAclConnectionFailure(); 303 return; 304 } 305 acl_connection_interface_->EnqueueCommand( 306 std::move(packet), 307 handler_->BindOnceOn(this, &classic_impl::on_create_connection_status, address)); 308 } 309 on_create_connection_statusclassic_impl310 void on_create_connection_status(Address address, CommandStatusView status) { 311 log::assert_that(status.IsValid(), "assert failed: status.IsValid()"); 312 log::assert_that(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION, 313 "assert failed: status.GetCommandOpCode() == OpCode::CREATE_CONNECTION"); 314 if (status.GetStatus() != hci::ErrorCode::SUCCESS /* = pending */) { 315 // something went wrong, but unblock queue and report to caller 316 log::error("Failed to create connection, reporting failure and continuing"); 317 log::assert_that(client_callbacks_ != nullptr, "assert failed: client_callbacks_ != nullptr"); 318 client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectFail, 319 common::Unretained(client_callbacks_), address, 320 status.GetStatus(), true /* locally initiated */)); 321 acl_scheduler_->ReportOutgoingAclConnectionFailure(); 322 } else { 323 // everything is good, resume when a connection_complete event arrives 324 return; 325 } 326 } 327 328 enum class Initiator { 329 LOCALLY_INITIATED, 330 REMOTE_INITIATED, 331 }; 332 create_and_announce_connectionclassic_impl333 void create_and_announce_connection(ConnectionCompleteView connection_complete, Role current_role, 334 Initiator initiator) { 335 auto status = connection_complete.GetStatus(); 336 auto address = connection_complete.GetBdAddr(); 337 if (client_callbacks_ == nullptr) { 338 log::warn("No client callbacks registered for connection"); 339 return; 340 } 341 if (status != ErrorCode::SUCCESS) { 342 client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectFail, 343 common::Unretained(client_callbacks_), address, status, 344 initiator == Initiator::LOCALLY_INITIATED)); 345 return; 346 } 347 uint16_t handle = connection_complete.GetConnectionHandle(); 348 auto queue = std::make_shared<AclConnection::Queue>(10); 349 auto queue_down_end = queue->GetDownEnd(); 350 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, queue); 351 std::unique_ptr<ClassicAclConnection> connection( 352 new ClassicAclConnection(std::move(queue), acl_connection_interface_, handle, address)); 353 connection->locally_initiated_ = initiator == Initiator::LOCALLY_INITIATED; 354 connections.add(handle, AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS}, 355 queue_down_end, handler_, 356 connection->GetEventCallbacks( 357 [this](uint16_t handle) { this->connections.invalidate(handle); })); 358 connections.execute(address, [=, this](ConnectionManagementCallbacks* callbacks) { 359 if (delayed_role_change_ == nullptr) { 360 callbacks->OnRoleChange(hci::ErrorCode::SUCCESS, current_role); 361 } else if (delayed_role_change_->GetBdAddr() == address) { 362 log::info("Sending delayed role change for {}", delayed_role_change_->GetBdAddr()); 363 callbacks->OnRoleChange(delayed_role_change_->GetStatus(), 364 delayed_role_change_->GetNewRole()); 365 delayed_role_change_.reset(); 366 } 367 }); 368 client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectSuccess, 369 common::Unretained(client_callbacks_), 370 std::move(connection))); 371 } 372 on_connection_completeclassic_impl373 void on_connection_complete(EventView packet) { 374 ConnectionCompleteView connection_complete = ConnectionCompleteView::Create(packet); 375 log::assert_that(connection_complete.IsValid(), "assert failed: connection_complete.IsValid()"); 376 auto status = connection_complete.GetStatus(); 377 auto address = connection_complete.GetBdAddr(); 378 379 acl_scheduler_->ReportAclConnectionCompletion( 380 address, 381 handler_->BindOnceOn(this, &classic_impl::create_and_announce_connection, 382 connection_complete, Role::CENTRAL, Initiator::LOCALLY_INITIATED), 383 handler_->BindOnceOn(this, &classic_impl::create_and_announce_connection, 384 connection_complete, Role::PERIPHERAL, 385 Initiator::REMOTE_INITIATED), 386 handler_->BindOnce( 387 [=](RemoteNameRequestModule* remote_name_request_module, Address address, 388 ErrorCode status, std::string valid_incoming_addresses) { 389 log::warn("No matching connection to {} ({})", address, 390 ErrorCodeText(status)); 391 log::assert_that(status != ErrorCode::SUCCESS, 392 "No prior connection request for {} expecting:{}", address, 393 valid_incoming_addresses.c_str()); 394 remote_name_request_module->ReportRemoteNameRequestCancellation(address); 395 }, 396 common::Unretained(remote_name_request_module_), address, status)); 397 } 398 cancel_connectclassic_impl399 void cancel_connect(Address address) { 400 acl_scheduler_->CancelAclConnection( 401 address, handler_->BindOnceOn(this, &classic_impl::actually_cancel_connect, address), 402 client_handler_->BindOnceOn(client_callbacks_, &ConnectionCallbacks::OnConnectFail, 403 address, ErrorCode::UNKNOWN_CONNECTION, 404 true /* locally initiated */)); 405 } 406 actually_cancel_connectclassic_impl407 void actually_cancel_connect(Address address) { 408 std::unique_ptr<CreateConnectionCancelBuilder> packet = 409 CreateConnectionCancelBuilder::Create(address); 410 acl_connection_interface_->EnqueueCommand( 411 std::move(packet), 412 handler_->BindOnce(check_complete<CreateConnectionCancelCompleteView>)); 413 } 414 415 static constexpr bool kRemoveConnectionAfterwards = true; on_classic_disconnectclassic_impl416 void on_classic_disconnect(uint16_t handle, ErrorCode reason) { 417 bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_; 418 bluetooth::os::LogMetricBluetoothDisconnectionReasonReported( 419 static_cast<uint32_t>(reason), connections.get_address(handle), handle); 420 connections.crash_on_unknown_handle_ = false; 421 connections.execute( 422 handle, 423 [=, this](ConnectionManagementCallbacks* callbacks) { 424 round_robin_scheduler_->Unregister(handle); 425 callbacks->OnDisconnection(reason); 426 }, 427 kRemoveConnectionAfterwards); 428 connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers; 429 } 430 on_connection_packet_type_changedclassic_impl431 void on_connection_packet_type_changed(EventView packet) { 432 ConnectionPacketTypeChangedView packet_type_changed = 433 ConnectionPacketTypeChangedView::Create(packet); 434 if (!packet_type_changed.IsValid()) { 435 log::error("Received on_connection_packet_type_changed with invalid packet"); 436 return; 437 } else if (packet_type_changed.GetStatus() != ErrorCode::SUCCESS) { 438 auto status = packet_type_changed.GetStatus(); 439 std::string error_code = ErrorCodeText(status); 440 log::error("Received on_connection_packet_type_changed with error code {}", error_code); 441 return; 442 } 443 uint16_t handle = packet_type_changed.GetConnectionHandle(); 444 connections.execute(handle, [=](ConnectionManagementCallbacks* /* callbacks */) { 445 // We don't handle this event; we didn't do this in legacy stack either. 446 }); 447 } 448 on_central_link_key_completeclassic_impl449 void on_central_link_key_complete(EventView packet) { 450 CentralLinkKeyCompleteView complete_view = CentralLinkKeyCompleteView::Create(packet); 451 if (!complete_view.IsValid()) { 452 log::error("Received on_central_link_key_complete with invalid packet"); 453 return; 454 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 455 auto status = complete_view.GetStatus(); 456 std::string error_code = ErrorCodeText(status); 457 log::error("Received on_central_link_key_complete with error code {}", error_code); 458 return; 459 } 460 uint16_t handle = complete_view.GetConnectionHandle(); 461 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 462 KeyFlag key_flag = complete_view.GetKeyFlag(); 463 callbacks->OnCentralLinkKeyComplete(key_flag); 464 }); 465 } 466 on_authentication_completeclassic_impl467 void on_authentication_complete(EventView packet) { 468 AuthenticationCompleteView authentication_complete = AuthenticationCompleteView::Create(packet); 469 if (!authentication_complete.IsValid()) { 470 log::error("Received on_authentication_complete with invalid packet"); 471 return; 472 } 473 uint16_t handle = authentication_complete.GetConnectionHandle(); 474 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 475 callbacks->OnAuthenticationComplete(authentication_complete.GetStatus()); 476 }); 477 } 478 on_change_connection_link_key_completeclassic_impl479 void on_change_connection_link_key_complete(EventView packet) { 480 ChangeConnectionLinkKeyCompleteView complete_view = 481 ChangeConnectionLinkKeyCompleteView::Create(packet); 482 if (!complete_view.IsValid()) { 483 log::error("Received on_change_connection_link_key_complete with invalid packet"); 484 return; 485 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 486 auto status = complete_view.GetStatus(); 487 std::string error_code = ErrorCodeText(status); 488 log::error("Received on_change_connection_link_key_complete with error code {}", error_code); 489 return; 490 } 491 uint16_t handle = complete_view.GetConnectionHandle(); 492 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 493 callbacks->OnChangeConnectionLinkKeyComplete(); 494 }); 495 } 496 on_read_clock_offset_completeclassic_impl497 void on_read_clock_offset_complete(EventView packet) { 498 ReadClockOffsetCompleteView complete_view = ReadClockOffsetCompleteView::Create(packet); 499 if (!complete_view.IsValid()) { 500 log::error("Received on_read_clock_offset_complete with invalid packet"); 501 return; 502 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 503 auto status = complete_view.GetStatus(); 504 std::string error_code = ErrorCodeText(status); 505 log::error("Received on_read_clock_offset_complete with error code {}", error_code); 506 return; 507 } 508 uint16_t handle = complete_view.GetConnectionHandle(); 509 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 510 uint16_t clock_offset = complete_view.GetClockOffset(); 511 callbacks->OnReadClockOffsetComplete(clock_offset); 512 }); 513 } 514 on_mode_changeclassic_impl515 void on_mode_change(EventView packet) { 516 ModeChangeView mode_change_view = ModeChangeView::Create(packet); 517 if (!mode_change_view.IsValid()) { 518 log::error("Received on_mode_change with invalid packet"); 519 return; 520 } 521 uint16_t handle = mode_change_view.GetConnectionHandle(); 522 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 523 callbacks->OnModeChange(mode_change_view.GetStatus(), mode_change_view.GetCurrentMode(), 524 mode_change_view.GetInterval()); 525 }); 526 } 527 on_sniff_subratingclassic_impl528 void on_sniff_subrating(EventView packet) { 529 SniffSubratingEventView sniff_subrating_view = SniffSubratingEventView::Create(packet); 530 if (!sniff_subrating_view.IsValid()) { 531 log::error("Received on_sniff_subrating with invalid packet"); 532 return; 533 } 534 uint16_t handle = sniff_subrating_view.GetConnectionHandle(); 535 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 536 callbacks->OnSniffSubrating(sniff_subrating_view.GetStatus(), 537 sniff_subrating_view.GetMaximumTransmitLatency(), 538 sniff_subrating_view.GetMaximumReceiveLatency(), 539 sniff_subrating_view.GetMinimumRemoteTimeout(), 540 sniff_subrating_view.GetMinimumLocalTimeout()); 541 }); 542 } 543 on_qos_setup_completeclassic_impl544 void on_qos_setup_complete(EventView packet) { 545 QosSetupCompleteView complete_view = QosSetupCompleteView::Create(packet); 546 if (!complete_view.IsValid()) { 547 log::error("Received on_qos_setup_complete with invalid packet"); 548 return; 549 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 550 auto status = complete_view.GetStatus(); 551 std::string error_code = ErrorCodeText(status); 552 log::error("Received on_qos_setup_complete with error code {}", error_code); 553 return; 554 } 555 uint16_t handle = complete_view.GetConnectionHandle(); 556 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 557 ServiceType service_type = complete_view.GetServiceType(); 558 uint32_t token_rate = complete_view.GetTokenRate(); 559 uint32_t peak_bandwidth = complete_view.GetPeakBandwidth(); 560 uint32_t latency = complete_view.GetLatency(); 561 uint32_t delay_variation = complete_view.GetDelayVariation(); 562 callbacks->OnQosSetupComplete(service_type, token_rate, peak_bandwidth, latency, 563 delay_variation); 564 }); 565 } 566 on_flow_specification_completeclassic_impl567 void on_flow_specification_complete(EventView packet) { 568 FlowSpecificationCompleteView complete_view = FlowSpecificationCompleteView::Create(packet); 569 if (!complete_view.IsValid()) { 570 log::error("Received on_flow_specification_complete with invalid packet"); 571 return; 572 } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) { 573 auto status = complete_view.GetStatus(); 574 std::string error_code = ErrorCodeText(status); 575 log::error("Received on_flow_specification_complete with error code {}", error_code); 576 return; 577 } 578 uint16_t handle = complete_view.GetConnectionHandle(); 579 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 580 FlowDirection flow_direction = complete_view.GetFlowDirection(); 581 ServiceType service_type = complete_view.GetServiceType(); 582 uint32_t token_rate = complete_view.GetTokenRate(); 583 uint32_t token_bucket_size = complete_view.GetTokenBucketSize(); 584 uint32_t peak_bandwidth = complete_view.GetPeakBandwidth(); 585 uint32_t access_latency = complete_view.GetAccessLatency(); 586 callbacks->OnFlowSpecificationComplete(flow_direction, service_type, token_rate, 587 token_bucket_size, peak_bandwidth, access_latency); 588 }); 589 } 590 on_flush_occurredclassic_impl591 void on_flush_occurred(EventView packet) { 592 FlushOccurredView flush_occurred_view = FlushOccurredView::Create(packet); 593 if (!flush_occurred_view.IsValid()) { 594 log::error("Received on_flush_occurred with invalid packet"); 595 return; 596 } 597 uint16_t handle = flush_occurred_view.GetConnectionHandle(); 598 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 599 callbacks->OnFlushOccurred(); 600 }); 601 } 602 on_enhanced_flush_completeclassic_impl603 void on_enhanced_flush_complete(EventView packet) { 604 auto flush_complete = EnhancedFlushCompleteView::Create(packet); 605 if (!flush_complete.IsValid()) { 606 log::error("Received an invalid packet"); 607 return; 608 } 609 uint16_t handle = flush_complete.GetConnectionHandle(); 610 connections.execute( 611 handle, [](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); }); 612 } 613 on_read_remote_version_informationclassic_impl614 void on_read_remote_version_information(hci::ErrorCode hci_status, uint16_t handle, 615 uint8_t version, uint16_t manufacturer_name, 616 uint16_t sub_version) { 617 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 618 callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, 619 sub_version); 620 }); 621 } 622 on_read_remote_supported_features_completeclassic_impl623 void on_read_remote_supported_features_complete(EventView packet) { 624 auto view = ReadRemoteSupportedFeaturesCompleteView::Create(packet); 625 log::assert_that(view.IsValid(), "Read remote supported features packet invalid"); 626 uint16_t handle = view.GetConnectionHandle(); 627 auto status = view.GetStatus(); 628 if (status != ErrorCode::SUCCESS) { 629 log::error("handle:{} status:{}", handle, ErrorCodeText(status)); 630 return; 631 } 632 bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures(connections.get_address(handle), 0, 633 view.GetLmpFeatures(), handle); 634 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 635 callbacks->OnReadRemoteSupportedFeaturesComplete(view.GetLmpFeatures()); 636 }); 637 } 638 on_read_remote_extended_features_completeclassic_impl639 void on_read_remote_extended_features_complete(EventView packet) { 640 auto view = ReadRemoteExtendedFeaturesCompleteView::Create(packet); 641 log::assert_that(view.IsValid(), "Read remote extended features packet invalid"); 642 uint16_t handle = view.GetConnectionHandle(); 643 auto status = view.GetStatus(); 644 if (status != ErrorCode::SUCCESS) { 645 log::error("handle:{} status:{}", handle, ErrorCodeText(status)); 646 return; 647 } 648 bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures(connections.get_address(handle), 649 view.GetPageNumber(), 650 view.GetExtendedLmpFeatures(), handle); 651 connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { 652 callbacks->OnReadRemoteExtendedFeaturesComplete( 653 view.GetPageNumber(), view.GetMaximumPageNumber(), view.GetExtendedLmpFeatures()); 654 }); 655 } 656 on_role_changeclassic_impl657 void on_role_change(EventView packet) { 658 RoleChangeView role_change_view = RoleChangeView::Create(packet); 659 if (!role_change_view.IsValid()) { 660 log::error("Received on_role_change with invalid packet"); 661 return; 662 } 663 auto hci_status = role_change_view.GetStatus(); 664 Address bd_addr = role_change_view.GetBdAddr(); 665 Role new_role = role_change_view.GetNewRole(); 666 bool sent = false; 667 connections.execute(bd_addr, [=, &sent](ConnectionManagementCallbacks* callbacks) { 668 if (callbacks != nullptr) { 669 callbacks->OnRoleChange(hci_status, new_role); 670 sent = true; 671 } 672 }); 673 if (!sent) { 674 if (delayed_role_change_ != nullptr) { 675 log::warn("Second delayed role change (@{} dropped)", delayed_role_change_->GetBdAddr()); 676 } 677 log::info("Role change for {} with no matching connection (new role: {})", 678 role_change_view.GetBdAddr(), RoleText(role_change_view.GetNewRole())); 679 delayed_role_change_ = std::make_unique<RoleChangeView>(role_change_view); 680 } 681 } 682 on_link_supervision_timeout_changedclassic_impl683 void on_link_supervision_timeout_changed(EventView packet) { 684 auto view = LinkSupervisionTimeoutChangedView::Create(packet); 685 log::assert_that(view.IsValid(), "Link supervision timeout changed packet invalid"); 686 log::info("UNIMPLEMENTED called"); 687 } 688 on_accept_connection_statusclassic_impl689 void on_accept_connection_status(Address address, CommandStatusView status) { 690 auto accept_status = AcceptConnectionRequestStatusView::Create(status); 691 log::assert_that(accept_status.IsValid(), "assert failed: accept_status.IsValid()"); 692 if (status.GetStatus() != ErrorCode::SUCCESS) { 693 cancel_connect(address); 694 } 695 } 696 central_link_keyclassic_impl697 void central_link_key(KeyFlag key_flag) { 698 std::unique_ptr<CentralLinkKeyBuilder> packet = CentralLinkKeyBuilder::Create(key_flag); 699 acl_connection_interface_->EnqueueCommand( 700 std::move(packet), handler_->BindOnce(check_status<CentralLinkKeyStatusView>)); 701 } 702 switch_roleclassic_impl703 void switch_role(Address address, Role role) { 704 std::unique_ptr<SwitchRoleBuilder> packet = SwitchRoleBuilder::Create(address, role); 705 acl_connection_interface_->EnqueueCommand( 706 std::move(packet), handler_->BindOnce(check_status<SwitchRoleStatusView>)); 707 } 708 write_default_link_policy_settingsclassic_impl709 void write_default_link_policy_settings(uint16_t default_link_policy_settings) { 710 std::unique_ptr<WriteDefaultLinkPolicySettingsBuilder> packet = 711 WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings); 712 acl_connection_interface_->EnqueueCommand( 713 std::move(packet), 714 handler_->BindOnce(check_complete<WriteDefaultLinkPolicySettingsCompleteView>)); 715 } 716 accept_connectionclassic_impl717 void accept_connection(Address address) { 718 auto role = AcceptConnectionRequestRole::BECOME_CENTRAL; // We prefer to be central 719 acl_connection_interface_->EnqueueCommand( 720 AcceptConnectionRequestBuilder::Create(address, role), 721 handler_->BindOnceOn(this, &classic_impl::on_accept_connection_status, address)); 722 } 723 reject_connectionclassic_impl724 void reject_connection(std::unique_ptr<RejectConnectionRequestBuilder> builder) { 725 acl_connection_interface_->EnqueueCommand( 726 std::move(builder), 727 handler_->BindOnce(check_status<RejectConnectionRequestStatusView>)); 728 } 729 HACK_get_handleclassic_impl730 uint16_t HACK_get_handle(Address address) { return connections.HACK_get_handle(address); } 731 handle_register_callbacksclassic_impl732 void handle_register_callbacks(ConnectionCallbacks* callbacks, os::Handler* handler) { 733 log::assert_that(client_callbacks_ == nullptr, "assert failed: client_callbacks_ == nullptr"); 734 log::assert_that(client_handler_ == nullptr, "assert failed: client_handler_ == nullptr"); 735 client_callbacks_ = callbacks; 736 client_handler_ = handler; 737 } 738 handle_unregister_callbacksclassic_impl739 void handle_unregister_callbacks(ConnectionCallbacks* callbacks, std::promise<void> promise) { 740 log::assert_that(client_callbacks_ == callbacks, 741 "Registered callback entity is different then unregister request"); 742 client_callbacks_ = nullptr; 743 client_handler_ = nullptr; 744 promise.set_value(); 745 } 746 747 HciLayer* hci_layer_ = nullptr; 748 Controller* controller_ = nullptr; 749 RoundRobinScheduler* round_robin_scheduler_ = nullptr; 750 AclScheduler* acl_scheduler_ = nullptr; 751 RemoteNameRequestModule* remote_name_request_module_ = nullptr; 752 AclConnectionInterface* acl_connection_interface_ = nullptr; 753 os::Handler* handler_ = nullptr; 754 ConnectionCallbacks* client_callbacks_ = nullptr; 755 os::Handler* client_handler_ = nullptr; 756 757 common::Callback<bool(Address, ClassOfDevice)> should_accept_connection_; 758 std::unique_ptr<RoleChangeView> delayed_role_change_ = nullptr; 759 }; 760 761 } // namespace acl_manager 762 } // namespace hci 763 } // namespace bluetooth 764