• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "common/bind.h"
20 #include "hci/acl_manager/assembler.h"
21 #include "hci/acl_manager/event_checkers.h"
22 #include "hci/acl_manager/round_robin_scheduler.h"
23 #include "hci/controller.h"
24 #include "security/security_manager_listener.h"
25 #include "security/security_module.h"
26 
27 namespace bluetooth {
28 namespace hci {
29 namespace acl_manager {
30 
31 struct acl_connection {
acl_connectionacl_connection32   acl_connection(AddressWithType address_with_type, AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler)
33       : assembler_(address_with_type, queue_down_end, handler), address_with_type_(address_with_type) {}
34   ~acl_connection() = default;
35   struct acl_manager::assembler assembler_;
36   AddressWithType address_with_type_;
37   ConnectionManagementCallbacks* connection_management_callbacks_ = nullptr;
38 };
39 
40 struct classic_impl : public security::ISecurityManagerListener {
classic_implclassic_impl41   classic_impl(
42       HciLayer* hci_layer,
43       Controller* controller,
44       os::Handler* handler,
45       RoundRobinScheduler* round_robin_scheduler,
46       bool crash_on_unknown_handle)
47       : hci_layer_(hci_layer),
48         controller_(controller),
49         round_robin_scheduler_(round_robin_scheduler),
50         crash_on_unknown_handle_(crash_on_unknown_handle) {
51     hci_layer_ = hci_layer;
52     controller_ = controller;
53     handler_ = handler;
54     should_accept_connection_ = common::Bind([](Address, ClassOfDevice) { return true; });
55     acl_connection_interface_ = hci_layer_->GetAclConnectionInterface(
56         handler_->BindOn(this, &classic_impl::on_classic_event),
57         handler_->BindOn(this, &classic_impl::on_classic_disconnect),
58         handler_->BindOn(this, &classic_impl::on_read_remote_version_information));
59   }
60 
~classic_implclassic_impl61   ~classic_impl() {
62     for (auto event_code : AclConnectionEvents) {
63       hci_layer_->UnregisterEventHandler(event_code);
64     }
65     acl_connections_.clear();
66     security_manager_.reset();
67   }
68 
get_callbacksclassic_impl69   ConnectionManagementCallbacks* get_callbacks(uint16_t handle) {
70     auto conn = acl_connections_.find(handle);
71     if (conn == acl_connections_.end()) {
72       return nullptr;
73     } else {
74       return conn->second.connection_management_callbacks_;
75     }
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_REQUEST:
85         on_incoming_connection(event_packet);
86         break;
87       case EventCode::CONNECTION_PACKET_TYPE_CHANGED:
88         on_connection_packet_type_changed(event_packet);
89         break;
90       case EventCode::AUTHENTICATION_COMPLETE:
91         on_authentication_complete(event_packet);
92         break;
93       case EventCode::READ_CLOCK_OFFSET_COMPLETE:
94         on_read_clock_offset_complete(event_packet);
95         break;
96       case EventCode::MODE_CHANGE:
97         on_mode_change(event_packet);
98         break;
99       case EventCode::SNIFF_SUBRATING:
100         on_sniff_subrating(event_packet);
101         break;
102       case EventCode::QOS_SETUP_COMPLETE:
103         on_qos_setup_complete(event_packet);
104         break;
105       case EventCode::ROLE_CHANGE:
106         on_role_change(event_packet);
107         break;
108       case EventCode::FLOW_SPECIFICATION_COMPLETE:
109         on_flow_specification_complete(event_packet);
110         break;
111       case EventCode::FLUSH_OCCURRED:
112         on_flush_occurred(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_ALWAYS_FATAL("Unhandled event code %s", EventCodeText(event_code).c_str());
128     }
129   }
130 
on_classic_disconnectclassic_impl131   void on_classic_disconnect(uint16_t handle, ErrorCode reason) {
132     auto callbacks = get_callbacks(handle);
133     if (callbacks != nullptr) {
134       round_robin_scheduler_->Unregister(handle);
135       callbacks->OnDisconnection(reason);
136       acl_connections_.erase(handle);
137     } else {
138       // This handle is probably for SCO, so we use the callback workaround.
139       if (sco_disconnect_callback_ != nullptr) {
140         sco_disconnect_callback_(handle, static_cast<uint8_t>(reason));
141       }
142     }
143   }
144 
handle_register_callbacksclassic_impl145   void handle_register_callbacks(ConnectionCallbacks* callbacks, os::Handler* handler) {
146     ASSERT(client_callbacks_ == nullptr);
147     ASSERT(client_handler_ == nullptr);
148     client_callbacks_ = callbacks;
149     client_handler_ = handler;
150   }
151 
handle_unregister_callbacksclassic_impl152   void handle_unregister_callbacks(ConnectionCallbacks* callbacks, std::promise<void> promise) {
153     ASSERT_LOG(client_callbacks_ == callbacks, "Registered callback entity is different then unregister request");
154     client_callbacks_ = nullptr;
155     client_handler_ = nullptr;
156     promise.set_value();
157   }
158 
on_incoming_connectionclassic_impl159   void on_incoming_connection(EventView packet) {
160     ConnectionRequestView request = ConnectionRequestView::Create(packet);
161     ASSERT(request.IsValid());
162     Address address = request.GetBdAddr();
163     if (client_callbacks_ == nullptr) {
164       LOG_ERROR("No callbacks to call");
165       auto reason = RejectConnectionReason::LIMITED_RESOURCES;
166       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
167       return;
168     }
169 
170     switch (request.GetLinkType()) {
171       case ConnectionRequestLinkType::SCO:
172         client_handler_->CallOn(
173             client_callbacks_, &ConnectionCallbacks::HACK_OnScoConnectRequest, address, request.GetClassOfDevice());
174         return;
175 
176       case ConnectionRequestLinkType::ACL:
177         break;
178 
179       case ConnectionRequestLinkType::ESCO:
180         client_handler_->CallOn(
181             client_callbacks_, &ConnectionCallbacks::HACK_OnEscoConnectRequest, address, request.GetClassOfDevice());
182         return;
183 
184       case ConnectionRequestLinkType::UNKNOWN:
185         LOG_ERROR("Request has unknown ConnectionRequestLinkType.");
186         return;
187     }
188 
189     incoming_connecting_address_ = address;
190     if (is_classic_link_already_connected(address)) {
191       auto reason = RejectConnectionReason::UNACCEPTABLE_BD_ADDR;
192       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
193     } else if (should_accept_connection_.Run(address, request.GetClassOfDevice())) {
194       this->accept_connection(address);
195     } else {
196       auto reason = RejectConnectionReason::LIMITED_RESOURCES;  // TODO: determine reason
197       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
198     }
199   }
200 
is_classic_link_already_connectedclassic_impl201   bool is_classic_link_already_connected(Address address) {
202     for (const auto& connection : acl_connections_) {
203       if (connection.second.address_with_type_.GetAddress() == address) {
204         return true;
205       }
206     }
207     return false;
208   }
209 
create_connectionclassic_impl210   void create_connection(Address address) {
211     // TODO: Configure default connection parameters?
212     uint16_t packet_type = 0x4408 /* DM 1,3,5 */ | 0x8810 /*DH 1,3,5 */;
213     PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R1;
214     uint16_t clock_offset = 0;
215     ClockOffsetValid clock_offset_valid = ClockOffsetValid::INVALID;
216     CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH;
217     ASSERT(client_callbacks_ != nullptr);
218     std::unique_ptr<CreateConnectionBuilder> packet = CreateConnectionBuilder::Create(
219         address, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch);
220 
221     if (incoming_connecting_address_ == Address::kEmpty && outgoing_connecting_address_ == Address::kEmpty) {
222       if (is_classic_link_already_connected(address)) {
223         LOG_WARN("already connected: %s", address.ToString().c_str());
224         return;
225       }
226       outgoing_connecting_address_ = address;
227       acl_connection_interface_->EnqueueCommand(std::move(packet), handler_->BindOnce([](CommandStatusView status) {
228         ASSERT(status.IsValid());
229         ASSERT(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION);
230       }));
231     } else {
232       pending_outgoing_connections_.emplace(address, std::move(packet));
233     }
234   }
235 
on_connection_completeclassic_impl236   void on_connection_complete(EventView packet) {
237     ConnectionCompleteView connection_complete = ConnectionCompleteView::Create(packet);
238     ASSERT(connection_complete.IsValid());
239     auto status = connection_complete.GetStatus();
240     auto address = connection_complete.GetBdAddr();
241     Role current_role = Role::CENTRAL;
242     bool locally_initiated = true;
243     if (outgoing_connecting_address_ == address) {
244       outgoing_connecting_address_ = Address::kEmpty;
245     } else {
246       locally_initiated = false;
247       if (incoming_connecting_address_ != address && status == ErrorCode::UNKNOWN_CONNECTION) {
248         LOG_WARN("No matching connection to %s (%s)", address.ToString().c_str(), ErrorCodeText(status).c_str());
249         LOG_WARN("Firmware error after RemoteNameRequestCancel?");
250         return;
251       }
252       ASSERT_LOG(incoming_connecting_address_ == address, "No prior connection request for %s",
253                  address.ToString().c_str());
254       incoming_connecting_address_ = Address::kEmpty;
255       current_role = Role::PERIPHERAL;
256     }
257     if (client_callbacks_ == nullptr) {
258       LOG_WARN("No client callbacks registered for connection");
259       return;
260     }
261     if (status != ErrorCode::SUCCESS) {
262       client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectFail, common::Unretained(client_callbacks_),
263                                              address, status));
264       return;
265     }
266     uint16_t handle = connection_complete.GetConnectionHandle();
267     auto queue = std::make_shared<AclConnection::Queue>(10);
268     auto conn_pair = acl_connections_.emplace(
269         std::piecewise_construct,
270         std::forward_as_tuple(handle),
271         std::forward_as_tuple(
272             AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS}, queue->GetDownEnd(), handler_));
273     ASSERT(conn_pair.second);  // Make sure it's not a duplicate
274     round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, queue);
275     std::unique_ptr<ClassicAclConnection> connection(
276         new ClassicAclConnection(std::move(queue), acl_connection_interface_, handle, address));
277     connection->locally_initiated_ = locally_initiated;
278     auto& connection_proxy = conn_pair.first->second;
279     connection_proxy.connection_management_callbacks_ = connection->GetEventCallbacks();
280     if (delayed_role_change_ != nullptr) {
281       if (delayed_role_change_->GetBdAddr() == address) {
282         LOG_INFO("Sending delayed role change for %s", delayed_role_change_->GetBdAddr().ToString().c_str());
283         connection_proxy.connection_management_callbacks_->OnRoleChange(
284             delayed_role_change_->GetStatus(), delayed_role_change_->GetNewRole());
285       }
286       delayed_role_change_ = nullptr;
287     } else {
288       connection_proxy.connection_management_callbacks_->OnRoleChange(hci::ErrorCode::SUCCESS, current_role);
289     }
290     client_handler_->Post(common::BindOnce(&ConnectionCallbacks::OnConnectSuccess,
291                                            common::Unretained(client_callbacks_), std::move(connection)));
292     while (!pending_outgoing_connections_.empty()) {
293       auto create_connection_packet_and_address = std::move(pending_outgoing_connections_.front());
294       pending_outgoing_connections_.pop();
295       if (!is_classic_link_already_connected(create_connection_packet_and_address.first)) {
296         outgoing_connecting_address_ = create_connection_packet_and_address.first;
297         acl_connection_interface_->EnqueueCommand(std::move(create_connection_packet_and_address.second),
298                                                   handler_->BindOnce([](CommandStatusView status) {
299                                                     ASSERT(status.IsValid());
300                                                     ASSERT(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION);
301                                                   }));
302         break;
303       }
304     }
305   }
306 
on_connection_packet_type_changedclassic_impl307   void on_connection_packet_type_changed(EventView packet) {
308     ConnectionPacketTypeChangedView packet_type_changed = ConnectionPacketTypeChangedView::Create(packet);
309     if (!packet_type_changed.IsValid()) {
310       LOG_ERROR("Received on_connection_packet_type_changed with invalid packet");
311       return;
312     } else if (packet_type_changed.GetStatus() != ErrorCode::SUCCESS) {
313       auto status = packet_type_changed.GetStatus();
314       std::string error_code = ErrorCodeText(status);
315       LOG_ERROR("Received on_connection_packet_type_changed with error code %s", error_code.c_str());
316       return;
317     }
318     uint16_t handle = packet_type_changed.GetConnectionHandle();
319     auto callbacks = get_callbacks(handle);
320     if (callbacks == nullptr) {
321       LOG_WARN("Unknown connection handle 0x%04hx", handle);
322       ASSERT(!crash_on_unknown_handle_);
323       return;
324     }
325     // We don't handle this event; we didn't do this in legacy stack either.
326   }
327 
on_central_link_key_completeclassic_impl328   void on_central_link_key_complete(EventView packet) {
329     CentralLinkKeyCompleteView complete_view = CentralLinkKeyCompleteView::Create(packet);
330     if (!complete_view.IsValid()) {
331       LOG_ERROR("Received on_central_link_key_complete with invalid packet");
332       return;
333     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
334       auto status = complete_view.GetStatus();
335       std::string error_code = ErrorCodeText(status);
336       LOG_ERROR("Received on_central_link_key_complete with error code %s", error_code.c_str());
337       return;
338     }
339     uint16_t handle = complete_view.GetConnectionHandle();
340     auto callbacks = get_callbacks(handle);
341     if (callbacks == nullptr) {
342       LOG_WARN("Unknown connection handle 0x%04hx", handle);
343       ASSERT(!crash_on_unknown_handle_);
344       return;
345     }
346     KeyFlag key_flag = complete_view.GetKeyFlag();
347     callbacks->OnCentralLinkKeyComplete(key_flag);
348   }
349 
on_authentication_completeclassic_impl350   void on_authentication_complete(EventView packet) {
351     AuthenticationCompleteView authentication_complete = AuthenticationCompleteView::Create(packet);
352     if (!authentication_complete.IsValid()) {
353       LOG_ERROR("Received on_authentication_complete with invalid packet");
354       return;
355     }
356     uint16_t handle = authentication_complete.GetConnectionHandle();
357     auto callbacks = get_callbacks(handle);
358     if (callbacks == nullptr) {
359       LOG_WARN("Unknown connection handle 0x%04hx", handle);
360       ASSERT(!crash_on_unknown_handle_);
361       return;
362     }
363     callbacks->OnAuthenticationComplete(authentication_complete.GetStatus());
364   }
365 
cancel_connectclassic_impl366   void cancel_connect(Address address) {
367     if (outgoing_connecting_address_ == address) {
368       LOG_INFO("Cannot cancel non-existent connection to %s", address.ToString().c_str());
369       return;
370     }
371     std::unique_ptr<CreateConnectionCancelBuilder> packet = CreateConnectionCancelBuilder::Create(address);
372     acl_connection_interface_->EnqueueCommand(
373         std::move(packet), handler_->BindOnce(&check_command_complete<CreateConnectionCancelCompleteView>));
374   }
375 
central_link_keyclassic_impl376   void central_link_key(KeyFlag key_flag) {
377     std::unique_ptr<CentralLinkKeyBuilder> packet = CentralLinkKeyBuilder::Create(key_flag);
378     acl_connection_interface_->EnqueueCommand(
379         std::move(packet), handler_->BindOnce(&check_command_status<CentralLinkKeyStatusView>));
380   }
381 
switch_roleclassic_impl382   void switch_role(Address address, Role role) {
383     std::unique_ptr<SwitchRoleBuilder> packet = SwitchRoleBuilder::Create(address, role);
384     acl_connection_interface_->EnqueueCommand(std::move(packet),
385                                               handler_->BindOnce(&check_command_status<SwitchRoleStatusView>));
386   }
387 
write_default_link_policy_settingsclassic_impl388   void write_default_link_policy_settings(uint16_t default_link_policy_settings) {
389     std::unique_ptr<WriteDefaultLinkPolicySettingsBuilder> packet =
390         WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings);
391     acl_connection_interface_->EnqueueCommand(
392         std::move(packet), handler_->BindOnce(&check_command_complete<WriteDefaultLinkPolicySettingsCompleteView>));
393   }
394 
accept_connectionclassic_impl395   void accept_connection(Address address) {
396     auto role = AcceptConnectionRequestRole::BECOME_CENTRAL;  // We prefer to be central
397     acl_connection_interface_->EnqueueCommand(
398         AcceptConnectionRequestBuilder::Create(address, role),
399         handler_->BindOnceOn(this, &classic_impl::on_accept_connection_status, address));
400   }
401 
on_change_connection_link_key_completeclassic_impl402   void on_change_connection_link_key_complete(EventView packet) {
403     ChangeConnectionLinkKeyCompleteView complete_view = ChangeConnectionLinkKeyCompleteView::Create(packet);
404     if (!complete_view.IsValid()) {
405       LOG_ERROR("Received on_change_connection_link_key_complete with invalid packet");
406       return;
407     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
408       auto status = complete_view.GetStatus();
409       std::string error_code = ErrorCodeText(status);
410       LOG_ERROR("Received on_change_connection_link_key_complete with error code %s", error_code.c_str());
411       return;
412     }
413     uint16_t handle = complete_view.GetConnectionHandle();
414     auto callbacks = get_callbacks(handle);
415     if (callbacks == nullptr) {
416       LOG_WARN("Unknown connection handle 0x%04hx", handle);
417       ASSERT(!crash_on_unknown_handle_);
418       return;
419     }
420     callbacks->OnChangeConnectionLinkKeyComplete();
421   }
422 
on_read_clock_offset_completeclassic_impl423   void on_read_clock_offset_complete(EventView packet) {
424     ReadClockOffsetCompleteView complete_view = ReadClockOffsetCompleteView::Create(packet);
425     if (!complete_view.IsValid()) {
426       LOG_ERROR("Received on_read_clock_offset_complete with invalid packet");
427       return;
428     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
429       auto status = complete_view.GetStatus();
430       std::string error_code = ErrorCodeText(status);
431       LOG_ERROR("Received on_read_clock_offset_complete with error code %s", error_code.c_str());
432       return;
433     }
434     uint16_t handle = complete_view.GetConnectionHandle();
435     auto callbacks = get_callbacks(handle);
436     if (callbacks == nullptr) {
437       LOG_WARN("Unknown connection handle 0x%04hx", handle);
438       ASSERT(!crash_on_unknown_handle_);
439       return;
440     }
441     uint16_t clock_offset = complete_view.GetClockOffset();
442     callbacks->OnReadClockOffsetComplete(clock_offset);
443   }
444 
on_mode_changeclassic_impl445   void on_mode_change(EventView packet) {
446     ModeChangeView mode_change_view = ModeChangeView::Create(packet);
447     if (!mode_change_view.IsValid()) {
448       LOG_ERROR("Received on_mode_change with invalid packet");
449       return;
450     }
451     uint16_t handle = mode_change_view.GetConnectionHandle();
452     auto callbacks = get_callbacks(handle);
453     if (callbacks == nullptr) {
454       LOG_WARN("Unknown connection handle 0x%04hx", handle);
455       ASSERT(!crash_on_unknown_handle_);
456       return;
457     }
458     callbacks->OnModeChange(
459         mode_change_view.GetStatus(), mode_change_view.GetCurrentMode(), mode_change_view.GetInterval());
460   }
461 
on_sniff_subratingclassic_impl462   void on_sniff_subrating(EventView packet) {
463     SniffSubratingEventView sniff_subrating_view = SniffSubratingEventView::Create(packet);
464     if (!sniff_subrating_view.IsValid()) {
465       LOG_ERROR("Received on_sniff_subrating with invalid packet");
466       return;
467     }
468     uint16_t handle = sniff_subrating_view.GetConnectionHandle();
469     auto callbacks = get_callbacks(handle);
470     if (callbacks == nullptr) {
471       LOG_WARN("Unknown connection handle 0x%04hx", handle);
472       ASSERT(!crash_on_unknown_handle_);
473       return;
474     }
475     callbacks->OnSniffSubrating(
476         sniff_subrating_view.GetStatus(),
477         sniff_subrating_view.GetMaximumTransmitLatency(),
478         sniff_subrating_view.GetMaximumReceiveLatency(),
479         sniff_subrating_view.GetMinimumRemoteTimeout(),
480         sniff_subrating_view.GetMinimumLocalTimeout());
481   }
482 
on_qos_setup_completeclassic_impl483   void on_qos_setup_complete(EventView packet) {
484     QosSetupCompleteView complete_view = QosSetupCompleteView::Create(packet);
485     if (!complete_view.IsValid()) {
486       LOG_ERROR("Received on_qos_setup_complete with invalid packet");
487       return;
488     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
489       auto status = complete_view.GetStatus();
490       std::string error_code = ErrorCodeText(status);
491       LOG_ERROR("Received on_qos_setup_complete with error code %s", error_code.c_str());
492       return;
493     }
494     uint16_t handle = complete_view.GetConnectionHandle();
495     auto callbacks = get_callbacks(handle);
496     if (callbacks == nullptr) {
497       LOG_WARN("Unknown connection handle 0x%04hx", handle);
498       ASSERT(!crash_on_unknown_handle_);
499       return;
500     }
501     ServiceType service_type = complete_view.GetServiceType();
502     uint32_t token_rate = complete_view.GetTokenRate();
503     uint32_t peak_bandwidth = complete_view.GetPeakBandwidth();
504     uint32_t latency = complete_view.GetLatency();
505     uint32_t delay_variation = complete_view.GetDelayVariation();
506     callbacks->OnQosSetupComplete(service_type, token_rate, peak_bandwidth, latency, delay_variation);
507   }
508 
on_role_changeclassic_impl509   void on_role_change(EventView packet) {
510     RoleChangeView role_change_view = RoleChangeView::Create(packet);
511     if (!role_change_view.IsValid()) {
512       LOG_ERROR("Received on_role_change with invalid packet");
513       return;
514     }
515     bool sent = false;
516     auto hci_status = role_change_view.GetStatus();
517     Address bd_addr = role_change_view.GetBdAddr();
518     Role new_role = role_change_view.GetNewRole();
519     for (auto& connection_pair : acl_connections_) {
520       if (connection_pair.second.address_with_type_.GetAddress() == bd_addr) {
521         connection_pair.second.connection_management_callbacks_->OnRoleChange(hci_status, new_role);
522         sent = true;
523       }
524     }
525     if (!sent) {
526       if (delayed_role_change_ != nullptr) {
527         LOG_WARN("Second delayed role change (@%s dropped)", delayed_role_change_->GetBdAddr().ToString().c_str());
528       }
529       LOG_INFO(
530           "Role change for %s with no matching connection (new role: %s)",
531           role_change_view.GetBdAddr().ToString().c_str(),
532           RoleText(role_change_view.GetNewRole()).c_str());
533       delayed_role_change_ = std::make_unique<RoleChangeView>(role_change_view);
534     }
535   }
536 
on_flow_specification_completeclassic_impl537   void on_flow_specification_complete(EventView packet) {
538     FlowSpecificationCompleteView complete_view = FlowSpecificationCompleteView::Create(packet);
539     if (!complete_view.IsValid()) {
540       LOG_ERROR("Received on_flow_specification_complete with invalid packet");
541       return;
542     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
543       auto status = complete_view.GetStatus();
544       std::string error_code = ErrorCodeText(status);
545       LOG_ERROR("Received on_flow_specification_complete with error code %s", error_code.c_str());
546       return;
547     }
548     uint16_t handle = complete_view.GetConnectionHandle();
549     auto callbacks = get_callbacks(handle);
550     if (callbacks == nullptr) {
551       LOG_WARN("Unknown connection handle 0x%04hx", handle);
552       ASSERT(!crash_on_unknown_handle_);
553       return;
554     }
555     FlowDirection flow_direction = complete_view.GetFlowDirection();
556     ServiceType service_type = complete_view.GetServiceType();
557     uint32_t token_rate = complete_view.GetTokenRate();
558     uint32_t token_bucket_size = complete_view.GetTokenBucketSize();
559     uint32_t peak_bandwidth = complete_view.GetPeakBandwidth();
560     uint32_t access_latency = complete_view.GetAccessLatency();
561     callbacks->OnFlowSpecificationComplete(
562         flow_direction, service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency);
563   }
564 
on_flush_occurredclassic_impl565   void on_flush_occurred(EventView packet) {
566     FlushOccurredView flush_occurred_view = FlushOccurredView::Create(packet);
567     if (!flush_occurred_view.IsValid()) {
568       LOG_ERROR("Received on_flush_occurred with invalid packet");
569       return;
570     }
571     uint16_t handle = flush_occurred_view.GetConnectionHandle();
572     auto callbacks = get_callbacks(handle);
573     if (callbacks == nullptr) {
574       LOG_WARN("Unknown connection handle 0x%04hx", handle);
575       ASSERT(!crash_on_unknown_handle_);
576       return;
577     }
578     callbacks->OnFlushOccurred();
579   }
580 
on_read_remote_version_informationclassic_impl581   void on_read_remote_version_information(
582       hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) {
583     auto callbacks = get_callbacks(handle);
584     if (callbacks == nullptr) {
585       LOG_WARN("Unknown connection handle 0x%04hx", handle);
586       ASSERT(!crash_on_unknown_handle_);
587       return;
588     }
589     callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version);
590   }
591 
on_read_remote_supported_features_completeclassic_impl592   void on_read_remote_supported_features_complete(EventView packet) {
593     auto view = ReadRemoteSupportedFeaturesCompleteView::Create(packet);
594     ASSERT_LOG(view.IsValid(), "Read remote supported features packet invalid");
595     uint16_t handle = view.GetConnectionHandle();
596     auto callbacks = get_callbacks(handle);
597     if (callbacks == nullptr) {
598       LOG_WARN("Unknown connection handle 0x%04hx", handle);
599       ASSERT(!crash_on_unknown_handle_);
600       return;
601     }
602     callbacks->OnReadRemoteSupportedFeaturesComplete(view.GetLmpFeatures());
603   }
604 
on_read_remote_extended_features_completeclassic_impl605   void on_read_remote_extended_features_complete(EventView packet) {
606     auto view = ReadRemoteExtendedFeaturesCompleteView::Create(packet);
607     ASSERT_LOG(view.IsValid(), "Read remote extended features packet invalid");
608     uint16_t handle = view.GetConnectionHandle();
609     auto callbacks = get_callbacks(handle);
610     if (callbacks == nullptr) {
611       LOG_WARN("Unknown connection handle 0x%04hx", handle);
612       ASSERT(!crash_on_unknown_handle_);
613       return;
614     }
615     callbacks->OnReadRemoteExtendedFeaturesComplete(
616         view.GetPageNumber(), view.GetMaximumPageNumber(), view.GetExtendedLmpFeatures());
617   }
618 
on_link_supervision_timeout_changedclassic_impl619   void on_link_supervision_timeout_changed(EventView packet) {
620     auto view = LinkSupervisionTimeoutChangedView::Create(packet);
621     ASSERT_LOG(view.IsValid(), "Link supervision timeout changed packet invalid");
622     LOG_INFO("UNIMPLEMENTED called");
623   }
624 
on_accept_connection_statusclassic_impl625   void on_accept_connection_status(Address address, CommandStatusView status) {
626     auto accept_status = AcceptConnectionRequestStatusView::Create(status);
627     ASSERT(accept_status.IsValid());
628     if (status.GetStatus() != ErrorCode::SUCCESS) {
629       cancel_connect(address);
630     }
631   }
632 
reject_connectionclassic_impl633   void reject_connection(std::unique_ptr<RejectConnectionRequestBuilder> builder) {
634     acl_connection_interface_->EnqueueCommand(
635         std::move(builder), handler_->BindOnce(&check_command_status<RejectConnectionRequestStatusView>));
636   }
637 
OnDeviceBondedclassic_impl638   void OnDeviceBonded(bluetooth::hci::AddressWithType device) override {}
OnDeviceUnbondedclassic_impl639   void OnDeviceUnbonded(bluetooth::hci::AddressWithType device) override {}
OnDeviceBondFailedclassic_impl640   void OnDeviceBondFailed(bluetooth::hci::AddressWithType device, security::PairingFailure status) override {}
641 
OnEncryptionStateChangedclassic_impl642   void OnEncryptionStateChanged(EncryptionChangeView encryption_change_view) override {
643     if (!encryption_change_view.IsValid()) {
644       LOG_ERROR("Invalid packet");
645       return;
646     } else if (encryption_change_view.GetStatus() != ErrorCode::SUCCESS) {
647       auto status = encryption_change_view.GetStatus();
648       std::string error_code = ErrorCodeText(status);
649       LOG_ERROR("error_code %s", error_code.c_str());
650       return;
651     }
652     uint16_t handle = encryption_change_view.GetConnectionHandle();
653     auto callbacks = get_callbacks(handle);
654     if (callbacks == nullptr) {
655       LOG_WARN("Unknown connection handle 0x%04hx", handle);
656       ASSERT(!crash_on_unknown_handle_);
657       return;
658     }
659     EncryptionEnabled enabled = encryption_change_view.GetEncryptionEnabled();
660     callbacks->OnEncryptionChange(enabled);
661   }
662 
set_security_moduleclassic_impl663   void set_security_module(security::SecurityModule* security_module) {
664     security_manager_ = security_module->GetSecurityManager();
665     security_manager_->RegisterCallbackListener(this, handler_);
666   }
667 
HACK_get_handleclassic_impl668   uint16_t HACK_get_handle(Address address) {
669     for (auto it = acl_connections_.begin(); it != acl_connections_.end(); it++) {
670       if (it->second.address_with_type_.GetAddress() == address) {
671         return it->first;
672       }
673     }
674     return 0xFFFF;
675   }
676 
HACK_SetScoDisconnectCallbackclassic_impl677   void HACK_SetScoDisconnectCallback(std::function<void(uint16_t, uint8_t)> callback) {
678     sco_disconnect_callback_ = callback;
679   }
680 
681   HciLayer* hci_layer_ = nullptr;
682   Controller* controller_ = nullptr;
683   RoundRobinScheduler* round_robin_scheduler_ = nullptr;
684   AclConnectionInterface* acl_connection_interface_ = nullptr;
685   os::Handler* handler_ = nullptr;
686   ConnectionCallbacks* client_callbacks_ = nullptr;
687   os::Handler* client_handler_ = nullptr;
688   std::map<uint16_t, acl_connection> acl_connections_;
689   Address outgoing_connecting_address_{Address::kEmpty};
690   Address incoming_connecting_address_{Address::kEmpty};
691   common::Callback<bool(Address, ClassOfDevice)> should_accept_connection_;
692   std::queue<std::pair<Address, std::unique_ptr<CreateConnectionBuilder>>> pending_outgoing_connections_;
693   std::unique_ptr<RoleChangeView> delayed_role_change_ = nullptr;
694 
695   std::unique_ptr<security::SecurityManager> security_manager_;
696   bool crash_on_unknown_handle_ = false;
697 
698   std::function<void(uint16_t, uint8_t)> sco_disconnect_callback_;
699 };
700 
701 }  // namespace acl_manager
702 }  // namespace hci
703 }  // namespace bluetooth
704