• 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 <atomic>
20 #include <memory>
21 #include <unordered_set>
22 
23 #include "common/bind.h"
24 #include "common/init_flags.h"
25 #include "hci/acl_manager/acl_scheduler.h"
26 #include "hci/acl_manager/assembler.h"
27 #include "hci/acl_manager/event_checkers.h"
28 #include "hci/acl_manager/round_robin_scheduler.h"
29 #include "hci/controller.h"
30 #include "hci/remote_name_request.h"
31 #include "os/metrics.h"
32 #include "security/security_manager_listener.h"
33 #include "security/security_module.h"
34 
35 namespace bluetooth {
36 namespace hci {
37 namespace acl_manager {
38 
39 struct acl_connection {
acl_connectionacl_connection40   acl_connection(AddressWithType address_with_type, AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler)
41       : address_with_type_(address_with_type),
42         assembler_(new acl_manager::assembler(address_with_type, queue_down_end, handler)) {}
~acl_connectionacl_connection43   ~acl_connection() {
44     delete assembler_;
45   }
46   AddressWithType address_with_type_;
47   struct acl_manager::assembler* assembler_;
48   ConnectionManagementCallbacks* connection_management_callbacks_ = nullptr;
49 };
50 
51 struct classic_impl : public security::ISecurityManagerListener {
classic_implclassic_impl52   classic_impl(
53       HciLayer* hci_layer,
54       Controller* controller,
55       os::Handler* handler,
56       RoundRobinScheduler* round_robin_scheduler,
57       bool crash_on_unknown_handle,
58       AclScheduler* acl_scheduler,
59       RemoteNameRequestModule* remote_name_request_module)
60       : hci_layer_(hci_layer),
61         controller_(controller),
62         round_robin_scheduler_(round_robin_scheduler),
63         acl_scheduler_(acl_scheduler),
64         remote_name_request_module_(remote_name_request_module) {
65     hci_layer_ = hci_layer;
66     controller_ = controller;
67     handler_ = handler;
68     connections.crash_on_unknown_handle_ = crash_on_unknown_handle;
69     should_accept_connection_ = common::Bind([](Address, ClassOfDevice) { return true; });
70     acl_connection_interface_ = hci_layer_->GetAclConnectionInterface(
71         handler_->BindOn(this, &classic_impl::on_classic_event),
72         handler_->BindOn(this, &classic_impl::on_classic_disconnect),
73         handler_->BindOn(this, &classic_impl::on_read_remote_version_information));
74   }
75 
~classic_implclassic_impl76   ~classic_impl() {
77     hci_layer_->PutAclConnectionInterface();
78     connections.reset();
79     security_manager_.reset();
80   }
81 
on_classic_eventclassic_impl82   void on_classic_event(EventView event_packet) {
83     EventCode event_code = event_packet.GetEventCode();
84     switch (event_code) {
85       case EventCode::CONNECTION_COMPLETE:
86         on_connection_complete(event_packet);
87         break;
88       case EventCode::CONNECTION_REQUEST:
89         on_incoming_connection(event_packet);
90         break;
91       case EventCode::CONNECTION_PACKET_TYPE_CHANGED:
92         on_connection_packet_type_changed(event_packet);
93         break;
94       case EventCode::AUTHENTICATION_COMPLETE:
95         on_authentication_complete(event_packet);
96         break;
97       case EventCode::READ_CLOCK_OFFSET_COMPLETE:
98         on_read_clock_offset_complete(event_packet);
99         break;
100       case EventCode::MODE_CHANGE:
101         on_mode_change(event_packet);
102         break;
103       case EventCode::SNIFF_SUBRATING:
104         on_sniff_subrating(event_packet);
105         break;
106       case EventCode::QOS_SETUP_COMPLETE:
107         on_qos_setup_complete(event_packet);
108         break;
109       case EventCode::ROLE_CHANGE:
110         on_role_change(event_packet);
111         break;
112       case EventCode::FLOW_SPECIFICATION_COMPLETE:
113         on_flow_specification_complete(event_packet);
114         break;
115       case EventCode::FLUSH_OCCURRED:
116         on_flush_occurred(event_packet);
117         break;
118       case EventCode::READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
119         on_read_remote_supported_features_complete(event_packet);
120         break;
121       case EventCode::READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
122         on_read_remote_extended_features_complete(event_packet);
123         break;
124       case EventCode::LINK_SUPERVISION_TIMEOUT_CHANGED:
125         on_link_supervision_timeout_changed(event_packet);
126         break;
127       case EventCode::CENTRAL_LINK_KEY_COMPLETE:
128         on_central_link_key_complete(event_packet);
129         break;
130       default:
131         LOG_ALWAYS_FATAL("Unhandled event code %s", EventCodeText(event_code).c_str());
132     }
133   }
134 
135  private:
136   static constexpr uint16_t kIllegalConnectionHandle = 0xffff;
137   struct {
138    private:
139     std::map<uint16_t, acl_connection> acl_connections_;
140     mutable std::mutex acl_connections_guard_;
find_callbacksclassic_impl::__anon1f2b1fb20108141     ConnectionManagementCallbacks* find_callbacks(uint16_t handle) {
142       auto connection = acl_connections_.find(handle);
143       if (connection == acl_connections_.end()) return nullptr;
144       return connection->second.connection_management_callbacks_;
145     }
find_callbacksclassic_impl::__anon1f2b1fb20108146     ConnectionManagementCallbacks* find_callbacks(const Address& address) {
147       for (auto& connection_pair : acl_connections_) {
148         if (connection_pair.second.address_with_type_.GetAddress() == address) {
149           return connection_pair.second.connection_management_callbacks_;
150         }
151       }
152       return nullptr;
153     }
removeclassic_impl::__anon1f2b1fb20108154     void remove(uint16_t handle) {
155       auto connection = acl_connections_.find(handle);
156       if (connection != acl_connections_.end()) {
157         connection->second.connection_management_callbacks_ = nullptr;
158         acl_connections_.erase(handle);
159       }
160     }
161 
162    public:
163     bool crash_on_unknown_handle_ = false;
is_emptyclassic_impl::__anon1f2b1fb20108164     bool is_empty() const {
165       std::unique_lock<std::mutex> lock(acl_connections_guard_);
166       return acl_connections_.empty();
167     }
resetclassic_impl::__anon1f2b1fb20108168     void reset() {
169       std::unique_lock<std::mutex> lock(acl_connections_guard_);
170       acl_connections_.clear();
171     }
invalidateclassic_impl::__anon1f2b1fb20108172     void invalidate(uint16_t handle) {
173       std::unique_lock<std::mutex> lock(acl_connections_guard_);
174       remove(handle);
175     }
176     void execute(
177         uint16_t handle,
178         std::function<void(ConnectionManagementCallbacks* callbacks)> execute,
179         bool remove_afterwards = false) {
180       std::unique_lock<std::mutex> lock(acl_connections_guard_);
181       auto callbacks = find_callbacks(handle);
182       if (callbacks != nullptr)
183         execute(callbacks);
184       else
185         ASSERT_LOG(!crash_on_unknown_handle_, "Received command for unknown handle:0x%x", handle);
186       if (remove_afterwards) remove(handle);
187     }
executeclassic_impl::__anon1f2b1fb20108188     void execute(const Address& address, std::function<void(ConnectionManagementCallbacks* callbacks)> execute) {
189       std::unique_lock<std::mutex> lock(acl_connections_guard_);
190       auto callbacks = find_callbacks(address);
191       if (callbacks != nullptr) execute(callbacks);
192     }
send_packet_upwardclassic_impl::__anon1f2b1fb20108193     bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
194       std::unique_lock<std::mutex> lock(acl_connections_guard_);
195       auto connection = acl_connections_.find(handle);
196       if (connection != acl_connections_.end()) cb(connection->second.assembler_);
197       return connection != acl_connections_.end();
198     }
addclassic_impl::__anon1f2b1fb20108199     void add(
200         uint16_t handle,
201         const AddressWithType& remote_address,
202         AclConnection::QueueDownEnd* queue_end,
203         os::Handler* handler,
204         ConnectionManagementCallbacks* connection_management_callbacks) {
205       std::unique_lock<std::mutex> lock(acl_connections_guard_);
206       auto emplace_pair = acl_connections_.emplace(
207           std::piecewise_construct,
208           std::forward_as_tuple(handle),
209           std::forward_as_tuple(remote_address, queue_end, handler));
210       ASSERT(emplace_pair.second);  // Make sure the connection is unique
211       emplace_pair.first->second.connection_management_callbacks_ = connection_management_callbacks;
212     }
HACK_get_handleclassic_impl::__anon1f2b1fb20108213     uint16_t HACK_get_handle(const Address& address) const {
214       std::unique_lock<std::mutex> lock(acl_connections_guard_);
215       for (auto it = acl_connections_.begin(); it != acl_connections_.end(); it++) {
216         if (it->second.address_with_type_.GetAddress() == address) {
217           return it->first;
218         }
219       }
220       return kIllegalConnectionHandle;
221     }
get_addressclassic_impl::__anon1f2b1fb20108222     Address get_address(uint16_t handle) const {
223       std::unique_lock<std::mutex> lock(acl_connections_guard_);
224       auto connection = acl_connections_.find(handle);
225       if (connection == acl_connections_.end()) {
226         return Address::kEmpty;
227       }
228       return connection->second.address_with_type_.GetAddress();
229     }
is_classic_link_already_connectedclassic_impl::__anon1f2b1fb20108230     bool is_classic_link_already_connected(const Address& address) const {
231       std::unique_lock<std::mutex> lock(acl_connections_guard_);
232       for (const auto& connection : acl_connections_) {
233         if (connection.second.address_with_type_.GetAddress() == address) {
234           return true;
235         }
236       }
237       return false;
238     }
239   } connections;
240 
241  public:
send_packet_upwardclassic_impl242   bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
243     return connections.send_packet_upward(handle, cb);
244   }
245 
on_incoming_connectionclassic_impl246   void on_incoming_connection(EventView packet) {
247     ConnectionRequestView request = ConnectionRequestView::Create(packet);
248     ASSERT(request.IsValid());
249     Address address = request.GetBdAddr();
250     if (client_callbacks_ == nullptr) {
251       LOG_ERROR("No callbacks to call");
252       auto reason = RejectConnectionReason::LIMITED_RESOURCES;
253       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
254       return;
255     }
256 
257     switch (request.GetLinkType()) {
258       case ConnectionRequestLinkType::SCO:
259         client_handler_->CallOn(
260             client_callbacks_, &ConnectionCallbacks::HACK_OnScoConnectRequest, address, request.GetClassOfDevice());
261         return;
262 
263       case ConnectionRequestLinkType::ACL:
264         // Need to upstream Cod information when getting connection_request
265         client_handler_->CallOn(
266             client_callbacks_,
267             &ConnectionCallbacks::OnConnectRequest,
268             address,
269             request.GetClassOfDevice());
270         break;
271 
272       case ConnectionRequestLinkType::ESCO:
273         client_handler_->CallOn(
274             client_callbacks_, &ConnectionCallbacks::HACK_OnEscoConnectRequest, address, request.GetClassOfDevice());
275         return;
276 
277       case ConnectionRequestLinkType::UNKNOWN:
278         LOG_ERROR("Request has unknown ConnectionRequestLinkType.");
279         return;
280     }
281 
282     acl_scheduler_->RegisterPendingIncomingConnection(address);
283 
284     if (is_classic_link_already_connected(address)) {
285       auto reason = RejectConnectionReason::UNACCEPTABLE_BD_ADDR;
286       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
287     } else if (should_accept_connection_.Run(address, request.GetClassOfDevice())) {
288       this->accept_connection(address);
289     } else {
290       auto reason = RejectConnectionReason::LIMITED_RESOURCES;  // TODO: determine reason
291       this->reject_connection(RejectConnectionRequestBuilder::Create(address, reason));
292     }
293   }
294 
is_classic_link_already_connectedclassic_impl295   bool is_classic_link_already_connected(Address address) {
296     return connections.is_classic_link_already_connected(address);
297   }
298 
create_connectionclassic_impl299   void create_connection(Address address) {
300     // TODO: Configure default connection parameters?
301     uint16_t packet_type = 0x4408 /* DM 1,3,5 */ | 0x8810 /*DH 1,3,5 */;
302     PageScanRepetitionMode page_scan_repetition_mode = PageScanRepetitionMode::R1;
303     uint16_t clock_offset = 0;
304     ClockOffsetValid clock_offset_valid = ClockOffsetValid::INVALID;
305     CreateConnectionRoleSwitch allow_role_switch = CreateConnectionRoleSwitch::ALLOW_ROLE_SWITCH;
306     ASSERT(client_callbacks_ != nullptr);
307     std::unique_ptr<CreateConnectionBuilder> packet = CreateConnectionBuilder::Create(
308         address, packet_type, page_scan_repetition_mode, clock_offset, clock_offset_valid, allow_role_switch);
309 
310     acl_scheduler_->EnqueueOutgoingAclConnection(
311         address, handler_->BindOnceOn(this, &classic_impl::actually_create_connection, address, std::move(packet)));
312   }
313 
actually_create_connectionclassic_impl314   void actually_create_connection(Address address, std::unique_ptr<CreateConnectionBuilder> packet) {
315     if (is_classic_link_already_connected(address)) {
316       LOG_WARN("already connected: %s", ADDRESS_TO_LOGGABLE_CSTR(address));
317       acl_scheduler_->ReportOutgoingAclConnectionFailure();
318       return;
319     }
320     acl_connection_interface_->EnqueueCommand(
321         std::move(packet), handler_->BindOnceOn(this, &classic_impl::on_create_connection_status, address));
322   }
323 
on_create_connection_statusclassic_impl324   void on_create_connection_status(Address address, CommandStatusView status) {
325     ASSERT(status.IsValid());
326     ASSERT(status.GetCommandOpCode() == OpCode::CREATE_CONNECTION);
327     if (status.GetStatus() != hci::ErrorCode::SUCCESS /* = pending */) {
328       // something went wrong, but unblock queue and report to caller
329       LOG_ERROR("Failed to create connection, reporting failure and continuing");
330       ASSERT(client_callbacks_ != nullptr);
331       client_handler_->Post(common::BindOnce(
332           &ConnectionCallbacks::OnConnectFail,
333           common::Unretained(client_callbacks_),
334           address,
335           status.GetStatus(),
336           true /* locally initiated */));
337       acl_scheduler_->ReportOutgoingAclConnectionFailure();
338     } else {
339       // everything is good, resume when a connection_complete event arrives
340       return;
341     }
342   }
343 
344   enum class Initiator {
345     LOCALLY_INITIATED,
346     REMOTE_INITIATED,
347   };
348 
create_and_announce_connectionclassic_impl349   void create_and_announce_connection(
350       ConnectionCompleteView connection_complete, Role current_role, Initiator initiator) {
351     auto status = connection_complete.GetStatus();
352     auto address = connection_complete.GetBdAddr();
353     if (client_callbacks_ == nullptr) {
354       LOG_WARN("No client callbacks registered for connection");
355       return;
356     }
357     if (status != ErrorCode::SUCCESS) {
358       client_handler_->Post(common::BindOnce(
359           &ConnectionCallbacks::OnConnectFail,
360           common::Unretained(client_callbacks_),
361           address,
362           status,
363           initiator == Initiator::LOCALLY_INITIATED));
364       return;
365     }
366     uint16_t handle = connection_complete.GetConnectionHandle();
367     auto queue = std::make_shared<AclConnection::Queue>(10);
368     auto queue_down_end = queue->GetDownEnd();
369     round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::CLASSIC, handle, queue);
370     std::unique_ptr<ClassicAclConnection> connection(
371         new ClassicAclConnection(std::move(queue), acl_connection_interface_, handle, address));
372     connection->locally_initiated_ = initiator == Initiator::LOCALLY_INITIATED;
373     connections.add(
374         handle,
375         AddressWithType{address, AddressType::PUBLIC_DEVICE_ADDRESS},
376         queue_down_end,
377         handler_,
378         connection->GetEventCallbacks([this](uint16_t handle) { this->connections.invalidate(handle); }));
379     connections.execute(address, [=](ConnectionManagementCallbacks* callbacks) {
380       if (delayed_role_change_ == nullptr) {
381         callbacks->OnRoleChange(hci::ErrorCode::SUCCESS, current_role);
382       } else if (delayed_role_change_->GetBdAddr() == address) {
383         LOG_INFO("Sending delayed role change for %s",
384                  ADDRESS_TO_LOGGABLE_CSTR(delayed_role_change_->GetBdAddr()));
385         callbacks->OnRoleChange(delayed_role_change_->GetStatus(), delayed_role_change_->GetNewRole());
386         delayed_role_change_.reset();
387       }
388     });
389     client_handler_->Post(common::BindOnce(
390         &ConnectionCallbacks::OnConnectSuccess, common::Unretained(client_callbacks_), std::move(connection)));
391   }
392 
on_connection_completeclassic_impl393   void on_connection_complete(EventView packet) {
394     ConnectionCompleteView connection_complete = ConnectionCompleteView::Create(packet);
395     ASSERT(connection_complete.IsValid());
396     auto status = connection_complete.GetStatus();
397     auto address = connection_complete.GetBdAddr();
398 
399     // TODO(b/261610529) - Some controllers incorrectly return connection
400     // failures via HCI Connect Complete instead of SCO connect complete.
401     // Temporarily just drop these packets until we have finer grained control
402     // over these ASSERTs.
403 #if TARGET_FLOSS
404     auto handle = connection_complete.GetConnectionHandle();
405     auto link_type = connection_complete.GetLinkType();
406 
407     // HACK: Some failed SCO connections are reporting failures via
408     //       ConnectComplete instead of ScoConnectionComplete.
409     //       Drop such packets.
410     if (handle == 0xffff && link_type == LinkType::SCO) {
411       LOG_ERROR(
412           "ConnectionComplete with invalid handle(%u), link type(%u) and status(%d). Dropping packet.",
413           handle,
414           link_type,
415           status);
416       return;
417     }
418 #endif
419 
420     acl_scheduler_->ReportAclConnectionCompletion(
421         address,
422         handler_->BindOnceOn(
423             this,
424             &classic_impl::create_and_announce_connection,
425             connection_complete,
426             Role::CENTRAL,
427             Initiator::LOCALLY_INITIATED),
428         handler_->BindOnceOn(
429             this,
430             &classic_impl::create_and_announce_connection,
431             connection_complete,
432             Role::PERIPHERAL,
433             Initiator::REMOTE_INITIATED),
434         handler_->BindOnce(
435             [=](RemoteNameRequestModule* remote_name_request_module,
436                 Address address,
437                 ErrorCode status,
438                 std::string valid_incoming_addresses) {
439               ASSERT_LOG(
440                   status == ErrorCode::UNKNOWN_CONNECTION,
441                   "No prior connection request for %s expecting:%s",
442                   ADDRESS_TO_LOGGABLE_CSTR(address),
443                   valid_incoming_addresses.c_str());
444               LOG_WARN(
445                   "No matching connection to %s (%s)",
446                   ADDRESS_TO_LOGGABLE_CSTR(address),
447                   ErrorCodeText(status).c_str());
448               LOG_WARN("Firmware error after RemoteNameRequestCancel?");  // see b/184239841
449               if (bluetooth::common::init_flags::gd_remote_name_request_is_enabled()) {
450                 ASSERT_LOG(
451                     remote_name_request_module != nullptr,
452                     "RNR module enabled but module not provided");
453                 remote_name_request_module->ReportRemoteNameRequestCancellation(address);
454               }
455             },
456             common::Unretained(remote_name_request_module_),
457             address,
458             status));
459   }
460 
cancel_connectclassic_impl461   void cancel_connect(Address address) {
462     acl_scheduler_->CancelAclConnection(
463         address,
464         handler_->BindOnceOn(this, &classic_impl::actually_cancel_connect, address),
465         client_handler_->BindOnceOn(
466             client_callbacks_,
467             &ConnectionCallbacks::OnConnectFail,
468             address,
469             ErrorCode::UNKNOWN_CONNECTION,
470             true /* locally initiated */));
471   }
472 
actually_cancel_connectclassic_impl473   void actually_cancel_connect(Address address) {
474     std::unique_ptr<CreateConnectionCancelBuilder> packet = CreateConnectionCancelBuilder::Create(address);
475     acl_connection_interface_->EnqueueCommand(
476         std::move(packet), handler_->BindOnce(&check_command_complete<CreateConnectionCancelCompleteView>));
477   }
478 
479   static constexpr bool kRemoveConnectionAfterwards = true;
on_classic_disconnectclassic_impl480   void on_classic_disconnect(uint16_t handle, ErrorCode reason) {
481     bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_;
482     bluetooth::os::LogMetricBluetoothDisconnectionReasonReported(
483         static_cast<uint32_t>(reason), connections.get_address(handle), handle);
484     connections.crash_on_unknown_handle_ = false;
485     connections.execute(
486         handle,
487         [=](ConnectionManagementCallbacks* callbacks) {
488           round_robin_scheduler_->Unregister(handle);
489           callbacks->OnDisconnection(reason);
490         },
491         kRemoveConnectionAfterwards);
492     // This handle is probably for SCO, so we use the callback workaround.
493     if (non_acl_disconnect_callback_ != nullptr) {
494       non_acl_disconnect_callback_(handle, static_cast<uint8_t>(reason));
495     }
496     connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers;
497   }
498 
on_connection_packet_type_changedclassic_impl499   void on_connection_packet_type_changed(EventView packet) {
500     ConnectionPacketTypeChangedView packet_type_changed = ConnectionPacketTypeChangedView::Create(packet);
501     if (!packet_type_changed.IsValid()) {
502       LOG_ERROR("Received on_connection_packet_type_changed with invalid packet");
503       return;
504     } else if (packet_type_changed.GetStatus() != ErrorCode::SUCCESS) {
505       auto status = packet_type_changed.GetStatus();
506       std::string error_code = ErrorCodeText(status);
507       LOG_ERROR("Received on_connection_packet_type_changed with error code %s", error_code.c_str());
508       return;
509     }
510     uint16_t handle = packet_type_changed.GetConnectionHandle();
511     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
512       // We don't handle this event; we didn't do this in legacy stack either.
513     });
514   }
515 
on_central_link_key_completeclassic_impl516   void on_central_link_key_complete(EventView packet) {
517     CentralLinkKeyCompleteView complete_view = CentralLinkKeyCompleteView::Create(packet);
518     if (!complete_view.IsValid()) {
519       LOG_ERROR("Received on_central_link_key_complete with invalid packet");
520       return;
521     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
522       auto status = complete_view.GetStatus();
523       std::string error_code = ErrorCodeText(status);
524       LOG_ERROR("Received on_central_link_key_complete with error code %s", error_code.c_str());
525       return;
526     }
527     uint16_t handle = complete_view.GetConnectionHandle();
528     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
529       KeyFlag key_flag = complete_view.GetKeyFlag();
530       callbacks->OnCentralLinkKeyComplete(key_flag);
531     });
532   }
533 
on_authentication_completeclassic_impl534   void on_authentication_complete(EventView packet) {
535     AuthenticationCompleteView authentication_complete = AuthenticationCompleteView::Create(packet);
536     if (!authentication_complete.IsValid()) {
537       LOG_ERROR("Received on_authentication_complete with invalid packet");
538       return;
539     }
540     uint16_t handle = authentication_complete.GetConnectionHandle();
541     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
542       callbacks->OnAuthenticationComplete(authentication_complete.GetStatus());
543     });
544   }
545 
on_change_connection_link_key_completeclassic_impl546   void on_change_connection_link_key_complete(EventView packet) {
547     ChangeConnectionLinkKeyCompleteView complete_view = ChangeConnectionLinkKeyCompleteView::Create(packet);
548     if (!complete_view.IsValid()) {
549       LOG_ERROR("Received on_change_connection_link_key_complete with invalid packet");
550       return;
551     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
552       auto status = complete_view.GetStatus();
553       std::string error_code = ErrorCodeText(status);
554       LOG_ERROR("Received on_change_connection_link_key_complete with error code %s", error_code.c_str());
555       return;
556     }
557     uint16_t handle = complete_view.GetConnectionHandle();
558     connections.execute(
559         handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnChangeConnectionLinkKeyComplete(); });
560   }
561 
on_read_clock_offset_completeclassic_impl562   void on_read_clock_offset_complete(EventView packet) {
563     ReadClockOffsetCompleteView complete_view = ReadClockOffsetCompleteView::Create(packet);
564     if (!complete_view.IsValid()) {
565       LOG_ERROR("Received on_read_clock_offset_complete with invalid packet");
566       return;
567     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
568       auto status = complete_view.GetStatus();
569       std::string error_code = ErrorCodeText(status);
570       LOG_ERROR("Received on_read_clock_offset_complete with error code %s", error_code.c_str());
571       return;
572     }
573     uint16_t handle = complete_view.GetConnectionHandle();
574     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
575       uint16_t clock_offset = complete_view.GetClockOffset();
576       callbacks->OnReadClockOffsetComplete(clock_offset);
577     });
578   }
579 
on_mode_changeclassic_impl580   void on_mode_change(EventView packet) {
581     ModeChangeView mode_change_view = ModeChangeView::Create(packet);
582     if (!mode_change_view.IsValid()) {
583       LOG_ERROR("Received on_mode_change with invalid packet");
584       return;
585     }
586     uint16_t handle = mode_change_view.GetConnectionHandle();
587     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
588       callbacks->OnModeChange(
589           mode_change_view.GetStatus(), mode_change_view.GetCurrentMode(), mode_change_view.GetInterval());
590     });
591   }
592 
on_sniff_subratingclassic_impl593   void on_sniff_subrating(EventView packet) {
594     SniffSubratingEventView sniff_subrating_view = SniffSubratingEventView::Create(packet);
595     if (!sniff_subrating_view.IsValid()) {
596       LOG_ERROR("Received on_sniff_subrating with invalid packet");
597       return;
598     }
599     uint16_t handle = sniff_subrating_view.GetConnectionHandle();
600     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
601       callbacks->OnSniffSubrating(
602           sniff_subrating_view.GetStatus(),
603           sniff_subrating_view.GetMaximumTransmitLatency(),
604           sniff_subrating_view.GetMaximumReceiveLatency(),
605           sniff_subrating_view.GetMinimumRemoteTimeout(),
606           sniff_subrating_view.GetMinimumLocalTimeout());
607     });
608   }
609 
on_qos_setup_completeclassic_impl610   void on_qos_setup_complete(EventView packet) {
611     QosSetupCompleteView complete_view = QosSetupCompleteView::Create(packet);
612     if (!complete_view.IsValid()) {
613       LOG_ERROR("Received on_qos_setup_complete with invalid packet");
614       return;
615     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
616       auto status = complete_view.GetStatus();
617       std::string error_code = ErrorCodeText(status);
618       LOG_ERROR("Received on_qos_setup_complete with error code %s", error_code.c_str());
619       return;
620     }
621     uint16_t handle = complete_view.GetConnectionHandle();
622     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
623       ServiceType service_type = complete_view.GetServiceType();
624       uint32_t token_rate = complete_view.GetTokenRate();
625       uint32_t peak_bandwidth = complete_view.GetPeakBandwidth();
626       uint32_t latency = complete_view.GetLatency();
627       uint32_t delay_variation = complete_view.GetDelayVariation();
628       callbacks->OnQosSetupComplete(service_type, token_rate, peak_bandwidth, latency, delay_variation);
629     });
630   }
631 
on_flow_specification_completeclassic_impl632   void on_flow_specification_complete(EventView packet) {
633     FlowSpecificationCompleteView complete_view = FlowSpecificationCompleteView::Create(packet);
634     if (!complete_view.IsValid()) {
635       LOG_ERROR("Received on_flow_specification_complete with invalid packet");
636       return;
637     } else if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
638       auto status = complete_view.GetStatus();
639       std::string error_code = ErrorCodeText(status);
640       LOG_ERROR("Received on_flow_specification_complete with error code %s", error_code.c_str());
641       return;
642     }
643     uint16_t handle = complete_view.GetConnectionHandle();
644     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
645       FlowDirection flow_direction = complete_view.GetFlowDirection();
646       ServiceType service_type = complete_view.GetServiceType();
647       uint32_t token_rate = complete_view.GetTokenRate();
648       uint32_t token_bucket_size = complete_view.GetTokenBucketSize();
649       uint32_t peak_bandwidth = complete_view.GetPeakBandwidth();
650       uint32_t access_latency = complete_view.GetAccessLatency();
651       callbacks->OnFlowSpecificationComplete(
652           flow_direction, service_type, token_rate, token_bucket_size, peak_bandwidth, access_latency);
653     });
654   }
655 
on_flush_occurredclassic_impl656   void on_flush_occurred(EventView packet) {
657     FlushOccurredView flush_occurred_view = FlushOccurredView::Create(packet);
658     if (!flush_occurred_view.IsValid()) {
659       LOG_ERROR("Received on_flush_occurred with invalid packet");
660       return;
661     }
662     uint16_t handle = flush_occurred_view.GetConnectionHandle();
663     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) { callbacks->OnFlushOccurred(); });
664   }
665 
on_read_remote_version_informationclassic_impl666   void on_read_remote_version_information(
667       hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) {
668     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
669       callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version);
670     });
671   }
672 
on_read_remote_supported_features_completeclassic_impl673   void on_read_remote_supported_features_complete(EventView packet) {
674     auto view = ReadRemoteSupportedFeaturesCompleteView::Create(packet);
675     ASSERT_LOG(view.IsValid(), "Read remote supported features packet invalid");
676     uint16_t handle = view.GetConnectionHandle();
677     bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures(
678         connections.get_address(handle), 0, view.GetLmpFeatures(), handle);
679     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
680       callbacks->OnReadRemoteSupportedFeaturesComplete(view.GetLmpFeatures());
681     });
682   }
683 
on_read_remote_extended_features_completeclassic_impl684   void on_read_remote_extended_features_complete(EventView packet) {
685     auto view = ReadRemoteExtendedFeaturesCompleteView::Create(packet);
686     ASSERT_LOG(view.IsValid(), "Read remote extended features packet invalid");
687     uint16_t handle = view.GetConnectionHandle();
688     bluetooth::os::LogMetricBluetoothRemoteSupportedFeatures(
689         connections.get_address(handle), view.GetPageNumber(), view.GetExtendedLmpFeatures(), handle);
690     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
691       callbacks->OnReadRemoteExtendedFeaturesComplete(
692           view.GetPageNumber(), view.GetMaximumPageNumber(), view.GetExtendedLmpFeatures());
693     });
694   }
695 
OnEncryptionStateChangedclassic_impl696   void OnEncryptionStateChanged(EncryptionChangeView encryption_change_view) override {
697     if (!encryption_change_view.IsValid()) {
698       LOG_ERROR("Invalid packet");
699       return;
700     } else if (encryption_change_view.GetStatus() != ErrorCode::SUCCESS) {
701       auto status = encryption_change_view.GetStatus();
702       std::string error_code = ErrorCodeText(status);
703       LOG_ERROR("error_code %s", error_code.c_str());
704       return;
705     }
706     uint16_t handle = encryption_change_view.GetConnectionHandle();
707     connections.execute(handle, [=](ConnectionManagementCallbacks* callbacks) {
708       EncryptionEnabled enabled = encryption_change_view.GetEncryptionEnabled();
709       callbacks->OnEncryptionChange(enabled);
710     });
711   }
712 
on_role_changeclassic_impl713   void on_role_change(EventView packet) {
714     RoleChangeView role_change_view = RoleChangeView::Create(packet);
715     if (!role_change_view.IsValid()) {
716       LOG_ERROR("Received on_role_change with invalid packet");
717       return;
718     }
719     auto hci_status = role_change_view.GetStatus();
720     Address bd_addr = role_change_view.GetBdAddr();
721     Role new_role = role_change_view.GetNewRole();
722     bool sent = false;
723     connections.execute(bd_addr, [=, &sent](ConnectionManagementCallbacks* callbacks) {
724       if (callbacks != nullptr) {
725         callbacks->OnRoleChange(hci_status, new_role);
726         sent = true;
727       }
728     });
729     if (!sent) {
730       if (delayed_role_change_ != nullptr) {
731         LOG_WARN(
732             "Second delayed role change (@%s dropped)",
733             ADDRESS_TO_LOGGABLE_CSTR(delayed_role_change_->GetBdAddr()));
734       }
735       LOG_INFO(
736           "Role change for %s with no matching connection (new role: %s)",
737           ADDRESS_TO_LOGGABLE_CSTR(role_change_view.GetBdAddr()),
738           RoleText(role_change_view.GetNewRole()).c_str());
739       delayed_role_change_ = std::make_unique<RoleChangeView>(role_change_view);
740     }
741   }
742 
on_link_supervision_timeout_changedclassic_impl743   void on_link_supervision_timeout_changed(EventView packet) {
744     auto view = LinkSupervisionTimeoutChangedView::Create(packet);
745     ASSERT_LOG(view.IsValid(), "Link supervision timeout changed packet invalid");
746     LOG_INFO("UNIMPLEMENTED called");
747   }
748 
on_accept_connection_statusclassic_impl749   void on_accept_connection_status(Address address, CommandStatusView status) {
750     auto accept_status = AcceptConnectionRequestStatusView::Create(status);
751     ASSERT(accept_status.IsValid());
752     if (status.GetStatus() != ErrorCode::SUCCESS) {
753       cancel_connect(address);
754     }
755   }
756 
central_link_keyclassic_impl757   void central_link_key(KeyFlag key_flag) {
758     std::unique_ptr<CentralLinkKeyBuilder> packet = CentralLinkKeyBuilder::Create(key_flag);
759     acl_connection_interface_->EnqueueCommand(
760         std::move(packet), handler_->BindOnce(&check_command_status<CentralLinkKeyStatusView>));
761   }
762 
switch_roleclassic_impl763   void switch_role(Address address, Role role) {
764     std::unique_ptr<SwitchRoleBuilder> packet = SwitchRoleBuilder::Create(address, role);
765     acl_connection_interface_->EnqueueCommand(
766         std::move(packet), handler_->BindOnce(&check_command_status<SwitchRoleStatusView>));
767   }
768 
write_default_link_policy_settingsclassic_impl769   void write_default_link_policy_settings(uint16_t default_link_policy_settings) {
770     std::unique_ptr<WriteDefaultLinkPolicySettingsBuilder> packet =
771         WriteDefaultLinkPolicySettingsBuilder::Create(default_link_policy_settings);
772     acl_connection_interface_->EnqueueCommand(
773         std::move(packet), handler_->BindOnce(&check_command_complete<WriteDefaultLinkPolicySettingsCompleteView>));
774   }
775 
accept_connectionclassic_impl776   void accept_connection(Address address) {
777     auto role = AcceptConnectionRequestRole::BECOME_CENTRAL;  // We prefer to be central
778     acl_connection_interface_->EnqueueCommand(
779         AcceptConnectionRequestBuilder::Create(address, role),
780         handler_->BindOnceOn(this, &classic_impl::on_accept_connection_status, address));
781   }
782 
reject_connectionclassic_impl783   void reject_connection(std::unique_ptr<RejectConnectionRequestBuilder> builder) {
784     acl_connection_interface_->EnqueueCommand(
785         std::move(builder), handler_->BindOnce(&check_command_status<RejectConnectionRequestStatusView>));
786   }
787 
OnDeviceBondedclassic_impl788   void OnDeviceBonded(bluetooth::hci::AddressWithType device) override {}
OnDeviceUnbondedclassic_impl789   void OnDeviceUnbonded(bluetooth::hci::AddressWithType device) override {}
OnDeviceBondFailedclassic_impl790   void OnDeviceBondFailed(bluetooth::hci::AddressWithType device, security::PairingFailure status) override {}
791 
set_security_moduleclassic_impl792   void set_security_module(security::SecurityModule* security_module) {
793     security_manager_ = security_module->GetSecurityManager();
794     security_manager_->RegisterCallbackListener(this, handler_);
795   }
796 
HACK_get_handleclassic_impl797   uint16_t HACK_get_handle(Address address) {
798     return connections.HACK_get_handle(address);
799   }
800 
HACK_SetNonAclDisconnectCallbackclassic_impl801   void HACK_SetNonAclDisconnectCallback(std::function<void(uint16_t, uint8_t)> callback) {
802     non_acl_disconnect_callback_ = callback;
803   }
804 
handle_register_callbacksclassic_impl805   void handle_register_callbacks(ConnectionCallbacks* callbacks, os::Handler* handler) {
806     ASSERT(client_callbacks_ == nullptr);
807     ASSERT(client_handler_ == nullptr);
808     client_callbacks_ = callbacks;
809     client_handler_ = handler;
810   }
811 
handle_unregister_callbacksclassic_impl812   void handle_unregister_callbacks(ConnectionCallbacks* callbacks, std::promise<void> promise) {
813     ASSERT_LOG(client_callbacks_ == callbacks, "Registered callback entity is different then unregister request");
814     client_callbacks_ = nullptr;
815     client_handler_ = nullptr;
816     promise.set_value();
817   }
818 
819   HciLayer* hci_layer_ = nullptr;
820   Controller* controller_ = nullptr;
821   RoundRobinScheduler* round_robin_scheduler_ = nullptr;
822   AclScheduler* acl_scheduler_ = nullptr;
823   RemoteNameRequestModule* remote_name_request_module_ = nullptr;
824   AclConnectionInterface* acl_connection_interface_ = nullptr;
825   os::Handler* handler_ = nullptr;
826   ConnectionCallbacks* client_callbacks_ = nullptr;
827   os::Handler* client_handler_ = nullptr;
828 
829   common::Callback<bool(Address, ClassOfDevice)> should_accept_connection_;
830   std::unique_ptr<RoleChangeView> delayed_role_change_ = nullptr;
831 
832   std::unique_ptr<security::SecurityManager> security_manager_;
833 
834   std::function<void(uint16_t, uint8_t)> non_acl_disconnect_callback_;
835 };
836 
837 }  // namespace acl_manager
838 }  // namespace hci
839 }  // namespace bluetooth
840