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