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 <base/strings/stringprintf.h>
20 #include <bluetooth/log.h>
21 
22 #include <cstdint>
23 #include <memory>
24 #include <string>
25 #include <unordered_set>
26 #include <vector>
27 
28 #include "common/bind.h"
29 #include "common/init_flags.h"
30 #include "hci/acl_manager/assembler.h"
31 #include "hci/acl_manager/le_acceptlist_callbacks.h"
32 #include "hci/acl_manager/le_acl_connection.h"
33 #include "hci/acl_manager/le_connection_callbacks.h"
34 #include "hci/acl_manager/le_connection_management_callbacks.h"
35 #include "hci/acl_manager/round_robin_scheduler.h"
36 #include "hci/controller.h"
37 #include "hci/hci_layer.h"
38 #include "hci/hci_packets.h"
39 #include "hci/le_address_manager.h"
40 #include "macros.h"
41 #include "os/alarm.h"
42 #include "os/handler.h"
43 #include "os/system_properties.h"
44 
45 namespace bluetooth {
46 namespace hci {
47 namespace acl_manager {
48 
49 using common::BindOnce;
50 
51 constexpr uint16_t kConnIntervalMin = 0x0018;
52 constexpr uint16_t kConnIntervalMax = 0x0028;
53 constexpr uint16_t kConnLatency = 0x0000;
54 constexpr uint16_t kSupervisionTimeout = 0x01f4;
55 constexpr uint16_t kScanIntervalFast = 0x0060;    /* 30 ~ 60 ms (use 60)  = 96 *0.625 */
56 constexpr uint16_t kScanWindowFast = 0x0030;      /* 30 ms = 48 *0.625 */
57 constexpr uint16_t kScanWindow2mFast = 0x0018;    /* 15 ms = 24 *0.625 */
58 constexpr uint16_t kScanWindowCodedFast = 0x0018; /* 15 ms = 24 *0.625 */
59 constexpr uint16_t kScanIntervalSlow = 0x0800;    /* 1.28 s = 2048 *0.625 */
60 constexpr uint16_t kScanWindowSlow = 0x0030;      /* 30 ms = 48 *0.625 */
61 constexpr uint16_t kScanIntervalSystemSuspend = 0x0400; /* 640 ms = 1024 * 0.625 */
62 constexpr uint16_t kScanWindowSystemSuspend = 0x0012;   /* 11.25ms = 18 * 0.625 */
63 constexpr uint32_t kCreateConnectionTimeoutMs = 30 * 1000;
64 constexpr uint8_t PHY_LE_NO_PACKET = 0x00;
65 constexpr uint8_t PHY_LE_1M = 0x01;
66 constexpr uint8_t PHY_LE_2M = 0x02;
67 constexpr uint8_t PHY_LE_CODED = 0x04;
68 constexpr bool kEnableBlePrivacy = true;
69 constexpr bool kEnableBleOnlyInit1mPhy = false;
70 
71 static const std::string kPropertyMinConnInterval = "bluetooth.core.le.min_connection_interval";
72 static const std::string kPropertyMaxConnInterval = "bluetooth.core.le.max_connection_interval";
73 static const std::string kPropertyConnLatency = "bluetooth.core.le.connection_latency";
74 static const std::string kPropertyConnSupervisionTimeout = "bluetooth.core.le.connection_supervision_timeout";
75 static const std::string kPropertyDirectConnTimeout = "bluetooth.core.le.direct_connection_timeout";
76 static const std::string kPropertyConnScanIntervalFast = "bluetooth.core.le.connection_scan_interval_fast";
77 static const std::string kPropertyConnScanWindowFast = "bluetooth.core.le.connection_scan_window_fast";
78 static const std::string kPropertyConnScanWindow2mFast = "bluetooth.core.le.connection_scan_window_2m_fast";
79 static const std::string kPropertyConnScanWindowCodedFast = "bluetooth.core.le.connection_scan_window_coded_fast";
80 static const std::string kPropertyConnScanIntervalSlow = "bluetooth.core.le.connection_scan_interval_slow";
81 static const std::string kPropertyConnScanWindowSlow = "bluetooth.core.le.connection_scan_window_slow";
82 static const std::string kPropertyConnScanIntervalSystemSuspend =
83     "bluetooth.core.le.connection_scan_interval_system_suspend";
84 static const std::string kPropertyConnScanWindowSystemSuspend =
85     "bluetooth.core.le.connection_scan_window_system_suspend";
86 static const std::string kPropertyEnableBlePrivacy = "bluetooth.core.gap.le.privacy.enabled";
87 static const std::string kPropertyEnableBleOnlyInit1mPhy = "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled";
88 
89 enum class ConnectabilityState {
90   DISARMED = 0,
91   ARMING = 1,
92   ARMED = 2,
93   DISARMING = 3,
94 };
95 
connectability_state_machine_text(const ConnectabilityState & state)96 inline std::string connectability_state_machine_text(const ConnectabilityState& state) {
97   switch (state) {
98     CASE_RETURN_TEXT(ConnectabilityState::DISARMED);
99     CASE_RETURN_TEXT(ConnectabilityState::ARMING);
100     CASE_RETURN_TEXT(ConnectabilityState::ARMED);
101     CASE_RETURN_TEXT(ConnectabilityState::DISARMING);
102   }
103 }
104 
105 struct le_acl_connection {
le_acl_connectionle_acl_connection106   le_acl_connection(
107       AddressWithType remote_address,
108       std::unique_ptr<LeAclConnection> pending_connection,
109       AclConnection::QueueDownEnd* queue_down_end,
110       os::Handler* handler)
111       : remote_address_(remote_address),
112         pending_connection_(std::move(pending_connection)),
113         assembler_(new acl_manager::assembler(remote_address, queue_down_end, handler)) {}
~le_acl_connectionle_acl_connection114   ~le_acl_connection() {
115     delete assembler_;
116   }
117   AddressWithType remote_address_;
118   std::unique_ptr<LeAclConnection> pending_connection_;
119   acl_manager::assembler* assembler_;
120   LeConnectionManagementCallbacks* le_connection_management_callbacks_ = nullptr;
121 };
122 
123 struct le_impl : public bluetooth::hci::LeAddressManagerCallback {
le_implle_impl124   le_impl(
125       HciLayer* hci_layer,
126       Controller* controller,
127       os::Handler* handler,
128       RoundRobinScheduler* round_robin_scheduler,
129       bool crash_on_unknown_handle)
130       : hci_layer_(hci_layer), controller_(controller), round_robin_scheduler_(round_robin_scheduler) {
131     hci_layer_ = hci_layer;
132     controller_ = controller;
133     handler_ = handler;
134     connections.crash_on_unknown_handle_ = crash_on_unknown_handle;
135     le_acl_connection_interface_ = hci_layer_->GetLeAclConnectionInterface(
136         handler_->BindOn(this, &le_impl::on_le_event),
137         handler_->BindOn(this, &le_impl::on_le_disconnect),
138         handler_->BindOn(this, &le_impl::on_le_read_remote_version_information));
139     le_address_manager_ = new LeAddressManager(
140         common::Bind(&le_impl::enqueue_command, common::Unretained(this)),
141         handler_,
142         controller->GetMacAddress(),
143         controller->GetLeFilterAcceptListSize(),
144         controller->GetLeResolvingListSize());
145   }
146 
~le_implle_impl147   ~le_impl() {
148     if (address_manager_registered) {
149       le_address_manager_->UnregisterSync(this);
150     }
151     delete le_address_manager_;
152     hci_layer_->PutLeAclConnectionInterface();
153     connections.reset();
154   }
155 
on_le_eventle_impl156   void on_le_event(LeMetaEventView event_packet) {
157     SubeventCode code = event_packet.GetSubeventCode();
158     switch (code) {
159       case SubeventCode::CONNECTION_COMPLETE:
160       case SubeventCode::ENHANCED_CONNECTION_COMPLETE:
161         on_le_connection_complete(event_packet);
162         break;
163       case SubeventCode::CONNECTION_UPDATE_COMPLETE:
164         on_le_connection_update_complete(event_packet);
165         break;
166       case SubeventCode::PHY_UPDATE_COMPLETE:
167         on_le_phy_update_complete(event_packet);
168         break;
169       case SubeventCode::DATA_LENGTH_CHANGE:
170         on_data_length_change(event_packet);
171         break;
172       case SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
173         on_remote_connection_parameter_request(event_packet);
174         break;
175       case SubeventCode::LE_SUBRATE_CHANGE:
176         on_le_subrate_change(event_packet);
177         break;
178       default:
179         log::fatal("Unhandled event code {}", SubeventCodeText(code));
180     }
181   }
182 
183  private:
184   static constexpr uint16_t kIllegalConnectionHandle = 0xffff;
185   struct {
186    private:
187     std::map<uint16_t, le_acl_connection> le_acl_connections_;
188     mutable std::mutex le_acl_connections_guard_;
find_callbacksle_impl::__anon15a6721c0108189     LeConnectionManagementCallbacks* find_callbacks(uint16_t handle) {
190       auto connection = le_acl_connections_.find(handle);
191       if (connection == le_acl_connections_.end()) return nullptr;
192       return connection->second.le_connection_management_callbacks_;
193     }
removele_impl::__anon15a6721c0108194     void remove(uint16_t handle) {
195       auto connection = le_acl_connections_.find(handle);
196       if (connection != le_acl_connections_.end()) {
197         connection->second.le_connection_management_callbacks_ = nullptr;
198         le_acl_connections_.erase(handle);
199       }
200     }
201 
202    public:
203     bool crash_on_unknown_handle_ = false;
is_emptyle_impl::__anon15a6721c0108204     bool is_empty() const {
205       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
206       return le_acl_connections_.empty();
207     }
resetle_impl::__anon15a6721c0108208     void reset() {
209       std::map<uint16_t, le_acl_connection> le_acl_connections{};
210       {
211         std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
212         le_acl_connections = std::move(le_acl_connections_);
213       }
214       le_acl_connections.clear();
215     }
invalidatele_impl::__anon15a6721c0108216     void invalidate(uint16_t handle) {
217       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
218       remove(handle);
219     }
220     void execute(
221         uint16_t handle,
222         std::function<void(LeConnectionManagementCallbacks* callbacks)> execute,
223         bool remove_afterwards = false) {
224       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
225       auto callbacks = find_callbacks(handle);
226       if (callbacks != nullptr)
227         execute(callbacks);
228       else
229         log::assert_that(
230             !crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}", handle);
231       if (remove_afterwards) remove(handle);
232     }
send_packet_upwardle_impl::__anon15a6721c0108233     bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
234       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
235       auto connection = le_acl_connections_.find(handle);
236       if (connection != le_acl_connections_.end()) cb(connection->second.assembler_);
237       return connection != le_acl_connections_.end();
238     }
addle_impl::__anon15a6721c0108239     void add(
240         uint16_t handle,
241         const AddressWithType& remote_address,
242         std::unique_ptr<LeAclConnection> pending_connection,
243         AclConnection::QueueDownEnd* queue_end,
244         os::Handler* handler,
245         LeConnectionManagementCallbacks* le_connection_management_callbacks) {
246       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
247       auto emplace_pair = le_acl_connections_.emplace(
248           std::piecewise_construct,
249           std::forward_as_tuple(handle),
250           std::forward_as_tuple(remote_address, std::move(pending_connection), queue_end, handler));
251       log::assert_that(
252           emplace_pair.second,
253           "assert failed: emplace_pair.second");  // Make sure the connection is unique
254       emplace_pair.first->second.le_connection_management_callbacks_ = le_connection_management_callbacks;
255     }
256 
record_peripheral_data_and_extract_pending_connectionle_impl::__anon15a6721c0108257     std::unique_ptr<LeAclConnection> record_peripheral_data_and_extract_pending_connection(
258         uint16_t handle, DataAsPeripheral data) {
259       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
260       auto connection = le_acl_connections_.find(handle);
261       if (connection != le_acl_connections_.end() && connection->second.pending_connection_.get()) {
262         connection->second.pending_connection_->UpdateRoleSpecificData(data);
263         return std::move(connection->second.pending_connection_);
264       } else {
265         return nullptr;
266       }
267     }
268 
HACK_get_handlele_impl::__anon15a6721c0108269     uint16_t HACK_get_handle(Address address) const {
270       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
271       for (auto it = le_acl_connections_.begin(); it != le_acl_connections_.end(); it++) {
272         if (it->second.remote_address_.GetAddress() == address) {
273           return it->first;
274         }
275       }
276       return kIllegalConnectionHandle;
277     }
278 
getAddressWithTypele_impl::__anon15a6721c0108279     AddressWithType getAddressWithType(uint16_t handle) {
280       std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
281       auto it = le_acl_connections_.find(handle);
282       if (it != le_acl_connections_.end()) {
283         return it->second.remote_address_;
284       }
285       AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
286       return empty;
287     }
288 
alreadyConnectedle_impl::__anon15a6721c0108289     bool alreadyConnected(AddressWithType address_with_type) {
290       for (auto it = le_acl_connections_.begin(); it != le_acl_connections_.end(); it++) {
291         if (it->second.remote_address_ == address_with_type) {
292           return true;
293         }
294       }
295       return false;
296     }
297 
298   } connections;
299 
300  public:
enqueue_commandle_impl301   void enqueue_command(std::unique_ptr<CommandBuilder> command_packet) {
302     hci_layer_->EnqueueCommand(
303         std::move(command_packet),
304         handler_->BindOnce(&LeAddressManager::OnCommandComplete, common::Unretained(le_address_manager_)));
305   }
306 
send_packet_upwardle_impl307   bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
308     return connections.send_packet_upward(handle, cb);
309   }
310 
report_le_connection_failurele_impl311   void report_le_connection_failure(AddressWithType address, ErrorCode status) {
312     le_client_handler_->Post(common::BindOnce(
313         &LeConnectionCallbacks::OnLeConnectFail,
314         common::Unretained(le_client_callbacks_),
315         address,
316         status));
317     if (le_acceptlist_callbacks_ != nullptr) {
318       le_acceptlist_callbacks_->OnLeConnectFail(address, status);
319     }
320   }
321 
322   // connection canceled by LeAddressManager.OnPause(), will auto reconnect by LeAddressManager.OnResume()
on_le_connection_canceled_on_pausele_impl323   void on_le_connection_canceled_on_pause() {
324     log::assert_that(pause_connection, "Connection must be paused to ack the le address manager");
325     arm_on_resume_ = true;
326     connectability_state_ = ConnectabilityState::DISARMED;
327     le_address_manager_->AckPause(this);
328   }
329 
on_common_le_connection_completele_impl330   void on_common_le_connection_complete(AddressWithType address_with_type) {
331     auto connecting_addr_with_type = connecting_le_.find(address_with_type);
332     if (connecting_addr_with_type == connecting_le_.end()) {
333       log::warn("No prior connection request for {}", address_with_type);
334     }
335     connecting_le_.clear();
336 
337     direct_connect_remove(address_with_type);
338   }
339 
on_le_connection_completele_impl340   void on_le_connection_complete(LeMetaEventView packet) {
341     ErrorCode status;
342     Address address;
343     AddressType peer_address_type;
344     Role role;
345     AddressWithType remote_address;
346     uint16_t handle, conn_interval, conn_latency, supervision_timeout;
347 
348     if (packet.GetSubeventCode() == SubeventCode::CONNECTION_COMPLETE) {
349       LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
350       log::assert_that(
351           connection_complete.IsValid(), "assert failed: connection_complete.IsValid()");
352       status = connection_complete.GetStatus();
353       address = connection_complete.GetPeerAddress();
354       peer_address_type = connection_complete.GetPeerAddressType();
355       role = connection_complete.GetRole();
356       handle = connection_complete.GetConnectionHandle();
357       conn_interval = connection_complete.GetConnInterval();
358       conn_latency = connection_complete.GetConnLatency();
359       supervision_timeout = connection_complete.GetSupervisionTimeout();
360       remote_address = AddressWithType(address, peer_address_type);
361     } else if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) {
362       LeEnhancedConnectionCompleteView connection_complete =
363           LeEnhancedConnectionCompleteView::Create(packet);
364       log::assert_that(
365           connection_complete.IsValid(), "assert failed: connection_complete.IsValid()");
366       status = connection_complete.GetStatus();
367       address = connection_complete.GetPeerAddress();
368       peer_address_type = connection_complete.GetPeerAddressType();
369       role = connection_complete.GetRole();
370       handle = connection_complete.GetConnectionHandle();
371       conn_interval = connection_complete.GetConnInterval();
372       conn_latency = connection_complete.GetConnLatency();
373       supervision_timeout = connection_complete.GetSupervisionTimeout();
374       AddressType remote_address_type;
375       switch (peer_address_type) {
376         case AddressType::PUBLIC_DEVICE_ADDRESS:
377         case AddressType::PUBLIC_IDENTITY_ADDRESS:
378           remote_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
379           break;
380         case AddressType::RANDOM_DEVICE_ADDRESS:
381         case AddressType::RANDOM_IDENTITY_ADDRESS:
382           remote_address_type = AddressType::RANDOM_DEVICE_ADDRESS;
383           break;
384       }
385       remote_address = AddressWithType(address, remote_address_type);
386     } else {
387       log::fatal("Bad subevent code:{:02x}", packet.GetSubeventCode());
388       return;
389     }
390 
391     const bool in_filter_accept_list = is_device_in_accept_list(remote_address);
392 
393     if (role == hci::Role::CENTRAL) {
394       connectability_state_ = ConnectabilityState::DISARMED;
395       if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
396         on_le_connection_canceled_on_pause();
397         return;
398       }
399       if (status == ErrorCode::UNKNOWN_CONNECTION && arm_on_disarm_) {
400         arm_on_disarm_ = false;
401         arm_connectability();
402         return;
403       }
404       on_common_le_connection_complete(remote_address);
405       if (status == ErrorCode::UNKNOWN_CONNECTION) {
406         if (remote_address.GetAddress() != Address::kEmpty) {
407           log::info("Controller send non-empty address field:{}", remote_address.GetAddress());
408         }
409         // direct connect canceled due to connection timeout, start background connect
410         create_le_connection(remote_address, false, false);
411         return;
412       }
413 
414       arm_on_resume_ = false;
415       ready_to_unregister = true;
416       remove_device_from_accept_list(remote_address);
417 
418       if (!accept_list.empty()) {
419         AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
420         handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
421       }
422 
423       if (le_client_handler_ == nullptr) {
424         log::error("No callbacks to call");
425         return;
426       }
427 
428       if (status != ErrorCode::SUCCESS) {
429         report_le_connection_failure(remote_address, status);
430         return;
431       }
432     } else {
433       log::info("Received connection complete with Peripheral role");
434       if (le_client_handler_ == nullptr) {
435         log::error("No callbacks to call");
436         return;
437       }
438 
439       if (status != ErrorCode::SUCCESS) {
440         std::string error_code = ErrorCodeText(status);
441         log::warn("Received on_le_connection_complete with error code {}", error_code);
442         report_le_connection_failure(remote_address, status);
443         return;
444       }
445 
446       if (in_filter_accept_list) {
447         log::info(
448             "Received incoming connection of device in filter accept_list, {}", remote_address);
449         direct_connect_remove(remote_address);
450         remove_device_from_accept_list(remote_address);
451       }
452     }
453 
454     if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
455       log::error("Receive connection complete with invalid connection parameters");
456       return;
457     }
458     auto role_specific_data = initialize_role_specific_data(role);
459     auto queue = std::make_shared<AclConnection::Queue>(10);
460     auto queue_down_end = queue->GetDownEnd();
461     round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
462     std::unique_ptr<LeAclConnection> connection(new LeAclConnection(
463         std::move(queue),
464         le_acl_connection_interface_,
465         handle,
466         role_specific_data,
467         remote_address));
468     connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
469     connection->interval_ = conn_interval;
470     connection->latency_ = conn_latency;
471     connection->supervision_timeout_ = supervision_timeout;
472     connection->in_filter_accept_list_ = in_filter_accept_list;
473     connection->locally_initiated_ = (role == hci::Role::CENTRAL);
474 
475     if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) {
476       LeEnhancedConnectionCompleteView connection_complete =
477           LeEnhancedConnectionCompleteView::Create(packet);
478       log::assert_that(
479           connection_complete.IsValid(), "assert failed: connection_complete.IsValid()");
480 
481       connection->local_resolvable_private_address_ =
482           connection_complete.GetLocalResolvablePrivateAddress();
483       connection->peer_resolvable_private_address_ =
484           connection_complete.GetPeerResolvablePrivateAddress();
485     }
486 
487     auto connection_callbacks = connection->GetEventCallbacks(
488         [this](uint16_t handle) { this->connections.invalidate(handle); });
489     if (std::holds_alternative<DataAsUninitializedPeripheral>(role_specific_data)) {
490       // the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated
491       // event, since we need it to know what local_address / advertising set the peer connected to.
492       // In the meantime, we store it as a pending_connection.
493       connections.add(
494           handle,
495           remote_address,
496           std::move(connection),
497           queue_down_end,
498           handler_,
499           connection_callbacks);
500     } else {
501       connections.add(
502           handle, remote_address, nullptr, queue_down_end, handler_, connection_callbacks);
503       le_client_handler_->Post(common::BindOnce(
504           &LeConnectionCallbacks::OnLeConnectSuccess,
505           common::Unretained(le_client_callbacks_),
506           remote_address,
507           std::move(connection)));
508       if (le_acceptlist_callbacks_ != nullptr) {
509         le_acceptlist_callbacks_->OnLeConnectSuccess(remote_address);
510       }
511     }
512   }
513 
initialize_role_specific_datale_impl514   RoleSpecificData initialize_role_specific_data(Role role) {
515     if (role == hci::Role::CENTRAL) {
516       return DataAsCentral{le_address_manager_->GetInitiatorAddress()};
517     } else if (
518         controller_->SupportsBleExtendedAdvertising() ||
519         controller_->IsSupported(hci::OpCode::LE_MULTI_ADVT)) {
520       // when accepting connection, we must obtain the address from the advertiser.
521       // When we receive "set terminated event", we associate connection handle with advertiser
522       // address
523       return DataAsUninitializedPeripheral{};
524     } else {
525       // the exception is if we only support legacy advertising - here, our current address is also
526       // our advertised address
527       return DataAsPeripheral{
528           le_address_manager_->GetInitiatorAddress(),
529           {},
530           true /* For now, ignore non-discoverable legacy advertising TODO(b/254314964) */};
531     }
532   }
533 
534   static constexpr bool kRemoveConnectionAfterwards = true;
on_le_disconnectle_impl535   void on_le_disconnect(uint16_t handle, ErrorCode reason) {
536     AddressWithType remote_address = connections.getAddressWithType(handle);
537     bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_;
538     connections.crash_on_unknown_handle_ = false;
539     connections.execute(
540         handle,
541         [=, this](LeConnectionManagementCallbacks* callbacks) {
542           round_robin_scheduler_->Unregister(handle);
543           callbacks->OnDisconnection(reason);
544         },
545         kRemoveConnectionAfterwards);
546     if (le_acceptlist_callbacks_ != nullptr) {
547       le_acceptlist_callbacks_->OnLeDisconnection(remote_address);
548     }
549     connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers;
550 
551     if (background_connections_.count(remote_address) == 1) {
552       log::info("re-add device to accept list");
553       arm_on_resume_ = true;
554       add_device_to_accept_list(remote_address);
555     }
556   }
557 
on_le_connection_update_completele_impl558   void on_le_connection_update_complete(LeMetaEventView view) {
559     auto complete_view = LeConnectionUpdateCompleteView::Create(view);
560     if (!complete_view.IsValid()) {
561       log::error("Received on_le_connection_update_complete with invalid packet");
562       return;
563     }
564     auto handle = complete_view.GetConnectionHandle();
565     connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
566       callbacks->OnConnectionUpdate(
567           complete_view.GetStatus(),
568           complete_view.GetConnInterval(),
569           complete_view.GetConnLatency(),
570           complete_view.GetSupervisionTimeout());
571     });
572   }
573 
on_le_phy_update_completele_impl574   void on_le_phy_update_complete(LeMetaEventView view) {
575     auto complete_view = LePhyUpdateCompleteView::Create(view);
576     if (!complete_view.IsValid()) {
577       log::error("Received on_le_phy_update_complete with invalid packet");
578       return;
579     }
580     auto handle = complete_view.GetConnectionHandle();
581     connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
582       callbacks->OnPhyUpdate(complete_view.GetStatus(), complete_view.GetTxPhy(), complete_view.GetRxPhy());
583     });
584   }
585 
on_le_read_remote_version_informationle_impl586   void on_le_read_remote_version_information(
587       hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) {
588     connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
589       callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version);
590     });
591   }
592 
on_data_length_changele_impl593   void on_data_length_change(LeMetaEventView view) {
594     auto data_length_view = LeDataLengthChangeView::Create(view);
595     if (!data_length_view.IsValid()) {
596       log::error("Invalid packet");
597       return;
598     }
599     auto handle = data_length_view.GetConnectionHandle();
600     connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
601       callbacks->OnDataLengthChange(
602           data_length_view.GetMaxTxOctets(),
603           data_length_view.GetMaxTxTime(),
604           data_length_view.GetMaxRxOctets(),
605           data_length_view.GetMaxRxTime());
606     });
607   }
608 
on_remote_connection_parameter_requestle_impl609   void on_remote_connection_parameter_request(LeMetaEventView view) {
610     auto request_view = LeRemoteConnectionParameterRequestView::Create(view);
611     if (!request_view.IsValid()) {
612       log::error("Invalid packet");
613       return;
614     }
615 
616     auto handle = request_view.GetConnectionHandle();
617     connections.execute(handle, [=, this](LeConnectionManagementCallbacks* /* callbacks */) {
618       // TODO: this is blindly accepting any parameters, just so we don't hang connection
619       // have proper parameter negotiation
620       le_acl_connection_interface_->EnqueueCommand(
621           LeRemoteConnectionParameterRequestReplyBuilder::Create(
622               handle,
623               request_view.GetIntervalMin(),
624               request_view.GetIntervalMax(),
625               request_view.GetLatency(),
626               request_view.GetTimeout(),
627               0,
628               0),
629           handler_->BindOnce([](CommandCompleteView /* status */) {}));
630     });
631   }
632 
on_le_subrate_changele_impl633   void on_le_subrate_change(LeMetaEventView view) {
634     auto subrate_change_view = LeSubrateChangeView::Create(view);
635     if (!subrate_change_view.IsValid()) {
636       log::error("Invalid packet");
637       return;
638     }
639     auto handle = subrate_change_view.GetConnectionHandle();
640     connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
641       callbacks->OnLeSubrateChange(
642           subrate_change_view.GetStatus(),
643           subrate_change_view.GetSubrateFactor(),
644           subrate_change_view.GetPeripheralLatency(),
645           subrate_change_view.GetContinuationNumber(),
646           subrate_change_view.GetSupervisionTimeout());
647     });
648   }
649 
HACK_get_handlele_impl650   uint16_t HACK_get_handle(Address address) {
651     return connections.HACK_get_handle(address);
652   }
653 
HACK_get_addressle_impl654   Address HACK_get_address(uint16_t connection_handle) {
655     return connections.getAddressWithType(connection_handle).GetAddress();
656   }
657 
OnAdvertisingSetTerminatedle_impl658   void OnAdvertisingSetTerminated(
659       uint16_t conn_handle,
660       uint8_t adv_set_id,
661       hci::AddressWithType adv_set_address,
662       bool is_discoverable) {
663     auto connection = connections.record_peripheral_data_and_extract_pending_connection(
664         conn_handle, DataAsPeripheral{adv_set_address, adv_set_id, is_discoverable});
665 
666     if (connection != nullptr) {
667       if (le_acceptlist_callbacks_ != nullptr) {
668         le_acceptlist_callbacks_->OnLeConnectSuccess(connection->GetRemoteAddress());
669       }
670       le_client_handler_->Post(common::BindOnce(
671           &LeConnectionCallbacks::OnLeConnectSuccess,
672           common::Unretained(le_client_callbacks_),
673           connection->GetRemoteAddress(),
674           std::move(connection)));
675     }
676   }
677 
direct_connect_addle_impl678   void direct_connect_add(AddressWithType address_with_type) {
679     direct_connections_.insert(address_with_type);
680     if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
681       return;
682     }
683 
684     auto emplace_result = create_connection_timeout_alarms_.emplace(
685         std::piecewise_construct,
686         std::forward_as_tuple(address_with_type.GetAddress(), address_with_type.GetAddressType()),
687         std::forward_as_tuple(handler_));
688     uint32_t connection_timeout =
689         os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs);
690     emplace_result.first->second.Schedule(
691               common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), address_with_type),
692               std::chrono::milliseconds(connection_timeout));
693   }
694 
direct_connect_removele_impl695   void direct_connect_remove(AddressWithType address_with_type) {
696     auto it = create_connection_timeout_alarms_.find(address_with_type);
697     if (it != create_connection_timeout_alarms_.end()) {
698       it->second.Cancel();
699       create_connection_timeout_alarms_.erase(it);
700     }
701     direct_connections_.erase(address_with_type);
702   }
703 
add_device_to_accept_listle_impl704   void add_device_to_accept_list(AddressWithType address_with_type) {
705     if (connections.alreadyConnected(address_with_type)) {
706       log::info("Device already connected, return");
707       return;
708     }
709 
710     if (accept_list.find(address_with_type) != accept_list.end()) {
711       log::warn("Device already exists in acceptlist and cannot be added: {}", address_with_type);
712       return;
713     }
714 
715     accept_list.insert(address_with_type);
716     register_with_address_manager();
717     le_address_manager_->AddDeviceToFilterAcceptList(
718         address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
719   }
720 
is_device_in_accept_listle_impl721   bool is_device_in_accept_list(AddressWithType address_with_type) {
722     return (accept_list.find(address_with_type) != accept_list.end());
723   }
724 
remove_device_from_accept_listle_impl725   void remove_device_from_accept_list(AddressWithType address_with_type) {
726     if (accept_list.find(address_with_type) == accept_list.end()) {
727       log::warn("Device not in acceptlist and cannot be removed: {}", address_with_type);
728       return;
729     }
730     accept_list.erase(address_with_type);
731     connecting_le_.erase(address_with_type);
732     register_with_address_manager();
733     le_address_manager_->RemoveDeviceFromFilterAcceptList(
734         address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
735   }
736 
clear_filter_accept_listle_impl737   void clear_filter_accept_list() {
738     accept_list.clear();
739     register_with_address_manager();
740     le_address_manager_->ClearFilterAcceptList();
741   }
742 
add_device_to_resolving_listle_impl743   void add_device_to_resolving_list(
744       AddressWithType address_with_type,
745       const std::array<uint8_t, 16>& peer_irk,
746       const std::array<uint8_t, 16>& local_irk) {
747     register_with_address_manager();
748     le_address_manager_->AddDeviceToResolvingList(
749         address_with_type.ToPeerAddressType(), address_with_type.GetAddress(), peer_irk, local_irk);
750     if (le_acceptlist_callbacks_ != nullptr) {
751       le_acceptlist_callbacks_->OnResolvingListChange();
752     }
753   }
754 
remove_device_from_resolving_listle_impl755   void remove_device_from_resolving_list(AddressWithType address_with_type) {
756     register_with_address_manager();
757     le_address_manager_->RemoveDeviceFromResolvingList(
758         address_with_type.ToPeerAddressType(), address_with_type.GetAddress());
759     if (le_acceptlist_callbacks_ != nullptr) {
760       le_acceptlist_callbacks_->OnResolvingListChange();
761     }
762   }
763 
update_connectability_state_after_armedle_impl764   void update_connectability_state_after_armed(const ErrorCode& status) {
765     switch (connectability_state_) {
766       case ConnectabilityState::DISARMED:
767       case ConnectabilityState::ARMED:
768       case ConnectabilityState::DISARMING:
769         log::error(
770             "Received connectability arm notification for unexpected state:{} status:{}",
771             connectability_state_machine_text(connectability_state_),
772             ErrorCodeText(status));
773         break;
774       case ConnectabilityState::ARMING:
775         if (status != ErrorCode::SUCCESS) {
776           log::error("Le connection state machine armed failed status:{}", ErrorCodeText(status));
777         }
778         connectability_state_ =
779             (status == ErrorCode::SUCCESS) ? ConnectabilityState::ARMED : ConnectabilityState::DISARMED;
780         log::info(
781             "Le connection state machine armed state:{} status:{}",
782             connectability_state_machine_text(connectability_state_),
783             ErrorCodeText(status));
784         if (disarmed_while_arming_) {
785           disarmed_while_arming_ = false;
786           disarm_connectability();
787         }
788     }
789   }
790 
on_extended_create_connectionle_impl791   void on_extended_create_connection(CommandStatusView status) {
792     log::assert_that(status.IsValid(), "assert failed: status.IsValid()");
793     log::assert_that(
794         status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION,
795         "assert failed: status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION");
796     update_connectability_state_after_armed(status.GetStatus());
797   }
798 
on_create_connectionle_impl799   void on_create_connection(CommandStatusView status) {
800     log::assert_that(status.IsValid(), "assert failed: status.IsValid()");
801     log::assert_that(
802         status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION,
803         "assert failed: status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION");
804     update_connectability_state_after_armed(status.GetStatus());
805   }
806 
arm_connectabilityle_impl807   void arm_connectability() {
808     if (connectability_state_ != ConnectabilityState::DISARMED) {
809       log::error(
810           "Attempting to re-arm le connection state machine in unexpected state:{}",
811           connectability_state_machine_text(connectability_state_));
812       return;
813     }
814     if (accept_list.empty()) {
815       log::info(
816           "Ignored request to re-arm le connection state machine when filter accept list is empty");
817       return;
818     }
819     AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
820     connectability_state_ = ConnectabilityState::ARMING;
821     connecting_le_ = accept_list;
822 
823     uint16_t le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalSlow, kScanIntervalSlow);
824     uint16_t le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowSlow, kScanWindowSlow);
825     uint16_t le_scan_window_2m = le_scan_window;
826     uint16_t le_scan_window_coded = le_scan_window;
827     // If there is any direct connection in the connection list, use the fast parameter
828     if (!direct_connections_.empty()) {
829       le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalFast, kScanIntervalFast);
830       le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowFast, kScanWindowFast);
831       le_scan_window_2m = os::GetSystemPropertyUint32(kPropertyConnScanWindow2mFast, kScanWindow2mFast);
832       le_scan_window_coded = os::GetSystemPropertyUint32(kPropertyConnScanWindowCodedFast, kScanWindowCodedFast);
833     }
834     // Use specific parameters when in system suspend.
835     if (system_suspend_) {
836       le_scan_interval = os::GetSystemPropertyUint32(
837           kPropertyConnScanIntervalSystemSuspend, kScanIntervalSystemSuspend);
838       le_scan_window = os::GetSystemPropertyUint32(
839           kPropertyConnScanWindowSystemSuspend, kScanWindowSystemSuspend);
840       le_scan_window_2m = le_scan_window;
841       le_scan_window_coded = le_scan_window;
842     }
843     InitiatorFilterPolicy initiator_filter_policy = InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST;
844     OwnAddressType own_address_type =
845         static_cast<OwnAddressType>(le_address_manager_->GetInitiatorAddress().GetAddressType());
846     uint16_t conn_interval_min = os::GetSystemPropertyUint32(kPropertyMinConnInterval, kConnIntervalMin);
847     uint16_t conn_interval_max = os::GetSystemPropertyUint32(kPropertyMaxConnInterval, kConnIntervalMax);
848     uint16_t conn_latency = os::GetSystemPropertyUint32(kPropertyConnLatency, kConnLatency);
849     uint16_t supervision_timeout = os::GetSystemPropertyUint32(kPropertyConnSupervisionTimeout, kSupervisionTimeout);
850     log::assert_that(
851         check_connection_parameters(
852             conn_interval_min, conn_interval_max, conn_latency, supervision_timeout),
853         "assert failed: check_connection_parameters(conn_interval_min, conn_interval_max, "
854         "conn_latency, supervision_timeout)");
855 
856     AddressWithType address_with_type = connection_peer_address_with_type_;
857     if (initiator_filter_policy == InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) {
858       address_with_type = AddressWithType();
859     }
860 
861     if (controller_->IsSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION)) {
862       bool only_init_1m_phy = os::GetSystemPropertyBool(kPropertyEnableBleOnlyInit1mPhy, kEnableBleOnlyInit1mPhy);
863 
864       uint8_t initiating_phys = PHY_LE_1M;
865       std::vector<LeCreateConnPhyScanParameters> parameters = {};
866       LeCreateConnPhyScanParameters scan_parameters;
867       scan_parameters.scan_interval_ = le_scan_interval;
868       scan_parameters.scan_window_ = le_scan_window;
869       scan_parameters.conn_interval_min_ = conn_interval_min;
870       scan_parameters.conn_interval_max_ = conn_interval_max;
871       scan_parameters.conn_latency_ = conn_latency;
872       scan_parameters.supervision_timeout_ = supervision_timeout;
873       scan_parameters.min_ce_length_ = 0x00;
874       scan_parameters.max_ce_length_ = 0x00;
875       parameters.push_back(scan_parameters);
876 
877       if (controller_->SupportsBle2mPhy() && !only_init_1m_phy) {
878         LeCreateConnPhyScanParameters scan_parameters_2m;
879         scan_parameters_2m.scan_interval_ = le_scan_interval;
880         scan_parameters_2m.scan_window_ = le_scan_window_2m;
881         scan_parameters_2m.conn_interval_min_ = conn_interval_min;
882         scan_parameters_2m.conn_interval_max_ = conn_interval_max;
883         scan_parameters_2m.conn_latency_ = conn_latency;
884         scan_parameters_2m.supervision_timeout_ = supervision_timeout;
885         scan_parameters_2m.min_ce_length_ = 0x00;
886         scan_parameters_2m.max_ce_length_ = 0x00;
887         parameters.push_back(scan_parameters_2m);
888         initiating_phys |= PHY_LE_2M;
889       }
890       if (controller_->SupportsBleCodedPhy() && !only_init_1m_phy) {
891         LeCreateConnPhyScanParameters scan_parameters_coded;
892         scan_parameters_coded.scan_interval_ = le_scan_interval;
893         scan_parameters_coded.scan_window_ = le_scan_window_coded;
894         scan_parameters_coded.conn_interval_min_ = conn_interval_min;
895         scan_parameters_coded.conn_interval_max_ = conn_interval_max;
896         scan_parameters_coded.conn_latency_ = conn_latency;
897         scan_parameters_coded.supervision_timeout_ = supervision_timeout;
898         scan_parameters_coded.min_ce_length_ = 0x00;
899         scan_parameters_coded.max_ce_length_ = 0x00;
900         parameters.push_back(scan_parameters_coded);
901         initiating_phys |= PHY_LE_CODED;
902       }
903 
904       le_acl_connection_interface_->EnqueueCommand(
905           LeExtendedCreateConnectionBuilder::Create(
906               initiator_filter_policy,
907               own_address_type,
908               address_with_type.GetAddressType(),
909               address_with_type.GetAddress(),
910               initiating_phys,
911               parameters),
912           handler_->BindOnce(&le_impl::on_extended_create_connection, common::Unretained(this)));
913     } else {
914       le_acl_connection_interface_->EnqueueCommand(
915           LeCreateConnectionBuilder::Create(
916               le_scan_interval,
917               le_scan_window,
918               initiator_filter_policy,
919               address_with_type.GetAddressType(),
920               address_with_type.GetAddress(),
921               own_address_type,
922               conn_interval_min,
923               conn_interval_max,
924               conn_latency,
925               supervision_timeout,
926               0x00,
927               0x00),
928           handler_->BindOnce(&le_impl::on_create_connection, common::Unretained(this)));
929     }
930   }
931 
disarm_connectabilityle_impl932   void disarm_connectability() {
933 
934     switch (connectability_state_) {
935       case ConnectabilityState::ARMED:
936         log::info("Disarming LE connection state machine with create connection cancel");
937         connectability_state_ = ConnectabilityState::DISARMING;
938         le_acl_connection_interface_->EnqueueCommand(
939             LeCreateConnectionCancelBuilder::Create(),
940             handler_->BindOnce(&le_impl::on_create_connection_cancel_complete, common::Unretained(this)));
941         break;
942 
943       case ConnectabilityState::ARMING:
944         log::info("Queueing cancel connect until after connection state machine is armed");
945         disarmed_while_arming_ = true;
946         break;
947       case ConnectabilityState::DISARMING:
948       case ConnectabilityState::DISARMED:
949         log::error(
950             "Attempting to disarm le connection state machine in unexpected state:{}",
951             connectability_state_machine_text(connectability_state_));
952         break;
953     }
954   }
955 
create_le_connectionle_impl956   void create_le_connection(AddressWithType address_with_type, bool add_to_accept_list, bool is_direct) {
957     if (le_client_callbacks_ == nullptr) {
958       log::error("No callbacks to call");
959       return;
960     }
961 
962     if (connections.alreadyConnected(address_with_type)) {
963       log::info("Device already connected, return");
964       return;
965     }
966 
967     bool already_in_accept_list = accept_list.find(address_with_type) != accept_list.end();
968     // TODO: Configure default LE connection parameters?
969     if (add_to_accept_list) {
970       if (!already_in_accept_list) {
971         add_device_to_accept_list(address_with_type);
972       }
973 
974       if (is_direct) {
975         direct_connect_add(address_with_type);
976       }
977     }
978 
979     if (!address_manager_registered) {
980       auto policy = le_address_manager_->Register(this);
981       address_manager_registered = true;
982 
983       // Pause connection, wait for set random address complete
984       if (policy == LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS ||
985           policy == LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
986         pause_connection = true;
987       }
988     }
989 
990     if (pause_connection) {
991       arm_on_resume_ = true;
992       return;
993     }
994 
995     switch (connectability_state_) {
996       case ConnectabilityState::ARMED:
997       case ConnectabilityState::ARMING:
998         if (already_in_accept_list) {
999           arm_on_disarm_ = true;
1000           disarm_connectability();
1001         } else {
1002           // Ignored, if we add new device to the filter accept list, create connection command will
1003           // be sent by OnResume.
1004           log::debug(
1005               "Deferred until filter accept list updated create connection state {}",
1006               connectability_state_machine_text(connectability_state_));
1007         }
1008         break;
1009       default:
1010         // If we added to filter accept list then the arming of the le state machine
1011         // must wait until the filter accept list command as completed
1012         if (add_to_accept_list) {
1013           arm_on_resume_ = true;
1014           log::debug("Deferred until filter accept list has completed");
1015         } else {
1016           handler_->CallOn(this, &le_impl::arm_connectability);
1017         }
1018         break;
1019     }
1020   }
1021 
on_create_connection_timeoutle_impl1022   void on_create_connection_timeout(AddressWithType address_with_type) {
1023     log::info("on_create_connection_timeout, address: {}", address_with_type);
1024     direct_connect_remove(address_with_type);
1025 
1026     if (background_connections_.find(address_with_type) != background_connections_.end()) {
1027       disarm_connectability();
1028     } else {
1029       remove_device_from_accept_list(address_with_type);
1030     }
1031     le_client_handler_->Post(common::BindOnce(
1032         &LeConnectionCallbacks::OnLeConnectFail,
1033         common::Unretained(le_client_callbacks_),
1034         address_with_type,
1035         ErrorCode::CONNECTION_ACCEPT_TIMEOUT));
1036   }
1037 
cancel_connectle_impl1038   void cancel_connect(AddressWithType address_with_type) {
1039     direct_connect_remove(address_with_type);
1040     // the connection will be canceled by LeAddressManager.OnPause()
1041     remove_device_from_accept_list(address_with_type);
1042   }
1043 
set_le_suggested_default_data_parametersle_impl1044   void set_le_suggested_default_data_parameters(uint16_t length, uint16_t time) {
1045     auto packet = LeWriteSuggestedDefaultDataLengthBuilder::Create(length, time);
1046     le_acl_connection_interface_->EnqueueCommand(
1047         std::move(packet), handler_->BindOnce([](CommandCompleteView /* complete */) {}));
1048   }
1049 
LeSetDefaultSubratele_impl1050   void LeSetDefaultSubrate(
1051       uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) {
1052     le_acl_connection_interface_->EnqueueCommand(
1053         LeSetDefaultSubrateBuilder::Create(subrate_min, subrate_max, max_latency, cont_num, sup_tout),
1054         handler_->BindOnce([](CommandCompleteView complete) {
1055           auto complete_view = LeSetDefaultSubrateCompleteView::Create(complete);
1056           log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1057           ErrorCode status = complete_view.GetStatus();
1058           log::assert_that(status == ErrorCode::SUCCESS, "Status = {}", ErrorCodeText(status));
1059         }));
1060   }
1061 
clear_resolving_listle_impl1062   void clear_resolving_list() {
1063     le_address_manager_->ClearResolvingList();
1064   }
1065 
set_privacy_policy_for_initiator_addressle_impl1066   void set_privacy_policy_for_initiator_address(
1067       LeAddressManager::AddressPolicy address_policy,
1068       AddressWithType fixed_address,
1069       Octet16 rotation_irk,
1070       std::chrono::milliseconds minimum_rotation_time,
1071       std::chrono::milliseconds maximum_rotation_time) {
1072     le_address_manager_->SetPrivacyPolicyForInitiatorAddress(
1073         address_policy,
1074         fixed_address,
1075         rotation_irk,
1076         controller_->SupportsBlePrivacy() && os::GetSystemPropertyBool(kPropertyEnableBlePrivacy, kEnableBlePrivacy),
1077         minimum_rotation_time,
1078         maximum_rotation_time);
1079   }
1080 
1081   // TODO(jpawlowski): remove once we have config file abstraction in cert tests
set_privacy_policy_for_initiator_address_for_testle_impl1082   void set_privacy_policy_for_initiator_address_for_test(
1083       LeAddressManager::AddressPolicy address_policy,
1084       AddressWithType fixed_address,
1085       Octet16 rotation_irk,
1086       std::chrono::milliseconds minimum_rotation_time,
1087       std::chrono::milliseconds maximum_rotation_time) {
1088     le_address_manager_->SetPrivacyPolicyForInitiatorAddressForTest(
1089         address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time);
1090   }
1091 
handle_register_le_callbacksle_impl1092   void handle_register_le_callbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) {
1093     log::assert_that(
1094         le_client_callbacks_ == nullptr, "assert failed: le_client_callbacks_ == nullptr");
1095     log::assert_that(le_client_handler_ == nullptr, "assert failed: le_client_handler_ == nullptr");
1096     le_client_callbacks_ = callbacks;
1097     le_client_handler_ = handler;
1098   }
1099 
handle_register_le_acceptlist_callbacksle_impl1100   void handle_register_le_acceptlist_callbacks(LeAcceptlistCallbacks* callbacks) {
1101     log::assert_that(
1102         le_acceptlist_callbacks_ == nullptr, "assert failed: le_acceptlist_callbacks_ == nullptr");
1103     le_acceptlist_callbacks_ = callbacks;
1104   }
1105 
handle_unregister_le_callbacksle_impl1106   void handle_unregister_le_callbacks(LeConnectionCallbacks* callbacks, std::promise<void> promise) {
1107     log::assert_that(
1108         le_client_callbacks_ == callbacks,
1109         "Registered le callback entity is different then unregister request");
1110     le_client_callbacks_ = nullptr;
1111     le_client_handler_ = nullptr;
1112     promise.set_value();
1113   }
1114 
handle_unregister_le_acceptlist_callbacksle_impl1115   void handle_unregister_le_acceptlist_callbacks(
1116       LeAcceptlistCallbacks* callbacks, std::promise<void> promise) {
1117     log::assert_that(
1118         le_acceptlist_callbacks_ == callbacks,
1119         "Registered le callback entity is different then unregister request");
1120     le_acceptlist_callbacks_ = nullptr;
1121     promise.set_value();
1122   }
1123 
check_connection_parametersle_impl1124   bool check_connection_parameters(
1125       uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) {
1126     if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
1127         conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
1128         supervision_timeout > 0x0C80) {
1129       log::error("Invalid parameter");
1130       return false;
1131     }
1132 
1133     // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
1134     // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
1135     // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in
1136     // milliseconds.
1137     uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
1138     if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) {
1139       log::error("Invalid parameter");
1140       return false;
1141     }
1142 
1143     return true;
1144   }
1145 
add_device_to_background_connection_listle_impl1146   void add_device_to_background_connection_list(AddressWithType address_with_type) {
1147     background_connections_.insert(address_with_type);
1148   }
1149 
remove_device_from_background_connection_listle_impl1150   void remove_device_from_background_connection_list(AddressWithType address_with_type) {
1151     background_connections_.erase(address_with_type);
1152   }
1153 
is_on_background_connection_listle_impl1154   void is_on_background_connection_list(AddressWithType address_with_type, std::promise<bool> promise) {
1155     promise.set_value(background_connections_.find(address_with_type) != background_connections_.end());
1156   }
1157 
OnPausele_impl1158   void OnPause() override {  // bluetooth::hci::LeAddressManagerCallback
1159     if (!address_manager_registered) {
1160       log::warn("Unregistered!");
1161       return;
1162     }
1163     pause_connection = true;
1164     if (connectability_state_ == ConnectabilityState::DISARMED) {
1165       le_address_manager_->AckPause(this);
1166       return;
1167     }
1168     arm_on_resume_ = !connecting_le_.empty();
1169     disarm_connectability();
1170   }
1171 
OnResumele_impl1172   void OnResume() override {  // bluetooth::hci::LeAddressManagerCallback
1173     if (!address_manager_registered) {
1174       log::warn("Unregistered!");
1175       return;
1176     }
1177     pause_connection = false;
1178     if (arm_on_resume_) {
1179       arm_connectability();
1180     }
1181     arm_on_resume_ = false;
1182     le_address_manager_->AckResume(this);
1183     check_for_unregister();
1184   }
1185 
on_create_connection_cancel_completele_impl1186   void on_create_connection_cancel_complete(CommandCompleteView view) {
1187     auto complete_view = LeCreateConnectionCancelCompleteView::Create(view);
1188     log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1189     if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1190       auto status = complete_view.GetStatus();
1191       std::string error_code = ErrorCodeText(status);
1192       log::warn("Received on_create_connection_cancel_complete with error code {}", error_code);
1193       if (pause_connection) {
1194         log::warn("AckPause");
1195         le_address_manager_->AckPause(this);
1196         return;
1197       }
1198     }
1199     if (connectability_state_ != ConnectabilityState::DISARMING) {
1200       log::error(
1201           "Attempting to disarm le connection state machine in unexpected state:{}",
1202           connectability_state_machine_text(connectability_state_));
1203     }
1204   }
1205 
register_with_address_managerle_impl1206   void register_with_address_manager() {
1207     if (!address_manager_registered) {
1208       le_address_manager_->Register(this);
1209       address_manager_registered = true;
1210       pause_connection = true;
1211     }
1212   }
1213 
check_for_unregisterle_impl1214   void check_for_unregister() {
1215     if (connections.is_empty() && connecting_le_.empty() && address_manager_registered && ready_to_unregister) {
1216       le_address_manager_->Unregister(this);
1217       address_manager_registered = false;
1218       pause_connection = false;
1219       ready_to_unregister = false;
1220     }
1221   }
1222 
set_system_suspend_statele_impl1223   void set_system_suspend_state(bool suspended) {
1224     system_suspend_ = suspended;
1225   }
1226 
1227   HciLayer* hci_layer_ = nullptr;
1228   Controller* controller_ = nullptr;
1229   os::Handler* handler_ = nullptr;
1230   RoundRobinScheduler* round_robin_scheduler_ = nullptr;
1231   LeAddressManager* le_address_manager_ = nullptr;
1232   LeAclConnectionInterface* le_acl_connection_interface_ = nullptr;
1233   LeConnectionCallbacks* le_client_callbacks_ = nullptr;
1234   os::Handler* le_client_handler_ = nullptr;
1235   LeAcceptlistCallbacks* le_acceptlist_callbacks_ = nullptr;
1236   std::unordered_set<AddressWithType> connecting_le_{};
1237   bool arm_on_resume_{};
1238   bool arm_on_disarm_{};
1239   std::unordered_set<AddressWithType> direct_connections_{};
1240   // Set of devices that will not be removed from accept list after direct connect timeout
1241   std::unordered_set<AddressWithType> background_connections_;
1242   /* This is content of controller "Filter Accept List"*/
1243   std::unordered_set<AddressWithType> accept_list;
1244   AddressWithType connection_peer_address_with_type_;  // Direct peer address UNSUPPORTEDD
1245   bool address_manager_registered = false;
1246   bool ready_to_unregister = false;
1247   bool pause_connection = false;
1248   bool disarmed_while_arming_ = false;
1249   bool system_suspend_ = false;
1250   ConnectabilityState connectability_state_{ConnectabilityState::DISARMED};
1251   std::map<AddressWithType, os::Alarm> create_connection_timeout_alarms_{};
1252 };
1253 
1254 }  // namespace acl_manager
1255 }  // namespace hci
1256 }  // namespace bluetooth
1257