1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #pragma once
18
19 #include <bluetooth/log.h>
20 #include <com_android_bluetooth_flags.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/le_conn_params.h"
30 #include "hci/acl_manager/assembler.h"
31 #include "hci/acl_manager/classic_impl.h"
32 #include "hci/acl_manager/le_acceptlist_callbacks.h"
33 #include "hci/acl_manager/le_acl_connection.h"
34 #include "hci/acl_manager/le_connection_callbacks.h"
35 #include "hci/acl_manager/le_connection_management_callbacks.h"
36 #include "hci/acl_manager/round_robin_scheduler.h"
37 #include "hci/controller.h"
38 #include "hci/hci_layer.h"
39 #include "hci/hci_packets.h"
40 #include "hci/le_address_manager.h"
41 #include "macros.h"
42 #include "main/shim/metrics_api.h"
43 #include "os/alarm.h"
44 #include "os/handler.h"
45 #include "os/system_properties.h"
46 #include "stack/include/btm_ble_api_types.h"
47
48 namespace bluetooth {
49 namespace hci {
50 namespace acl_manager {
51
52 using common::BindOnce;
53
54 constexpr uint16_t kConnIntervalMin = 0x0018;
55 constexpr uint16_t kConnIntervalMax = 0x0028;
56 constexpr uint16_t kConnLatency = 0x0000;
57 constexpr uint16_t kSupervisionTimeout = 0x01f4;
58 constexpr uint16_t kScanIntervalFast = 0x0060; /* 30 ~ 60 ms (use 60) = 96 *0.625 */
59 constexpr uint16_t kScanWindowFast = 0x0030; /* 30 ms = 48 *0.625 */
60 constexpr uint16_t kScanWindow2mFast = 0x0018; /* 15 ms = 24 *0.625 */
61 constexpr uint16_t kScanWindowCodedFast = 0x0018; /* 15 ms = 24 *0.625 */
62 constexpr uint16_t kScanIntervalSlow = 0x0800; /* 1.28 s = 2048 *0.625 */
63 constexpr uint16_t kScanWindowSlow = 0x0030; /* 30 ms = 48 *0.625 */
64 constexpr uint16_t kScanIntervalSystemSuspend = 0x0400; /* 640 ms = 1024 * 0.625 */
65 constexpr uint16_t kScanWindowSystemSuspend = 0x0012; /* 11.25ms = 18 * 0.625 */
66 constexpr uint32_t kCreateConnectionTimeoutMs = 30 * 1000;
67 constexpr uint8_t PHY_LE_NO_PACKET = 0x00;
68 constexpr uint8_t PHY_LE_1M = 0x01;
69 constexpr uint8_t PHY_LE_2M = 0x02;
70 constexpr uint8_t PHY_LE_CODED = 0x04;
71 constexpr bool kEnableBlePrivacy = true;
72 constexpr bool kEnableBleOnlyInit1mPhy = false;
73
74 static const std::string kPropertyMinConnInterval = "bluetooth.core.le.min_connection_interval";
75 static const std::string kPropertyMaxConnInterval = "bluetooth.core.le.max_connection_interval";
76 static const std::string kPropertyConnLatency = "bluetooth.core.le.connection_latency";
77 static const std::string kPropertyConnSupervisionTimeout =
78 "bluetooth.core.le.connection_supervision_timeout";
79 static const std::string kPropertyDirectConnTimeout = "bluetooth.core.le.direct_connection_timeout";
80 static const std::string kPropertyConnScanIntervalFast =
81 "bluetooth.core.le.connection_scan_interval_fast";
82 static const std::string kPropertyConnScanWindowFast =
83 "bluetooth.core.le.connection_scan_window_fast";
84 static const std::string kPropertyConnScanWindow2mFast =
85 "bluetooth.core.le.connection_scan_window_2m_fast";
86 static const std::string kPropertyConnScanWindowCodedFast =
87 "bluetooth.core.le.connection_scan_window_coded_fast";
88 static const std::string kPropertyConnScanIntervalSlow =
89 "bluetooth.core.le.connection_scan_interval_slow";
90 static const std::string kPropertyConnScanWindowSlow =
91 "bluetooth.core.le.connection_scan_window_slow";
92 static const std::string kPropertyConnScanIntervalSystemSuspend =
93 "bluetooth.core.le.connection_scan_interval_system_suspend";
94 static const std::string kPropertyConnScanWindowSystemSuspend =
95 "bluetooth.core.le.connection_scan_window_system_suspend";
96 static const std::string kPropertyEnableBlePrivacy = "bluetooth.core.gap.le.privacy.enabled";
97 static const std::string kPropertyEnableBleOnlyInit1mPhy =
98 "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled";
99
100 enum class ConnectabilityState {
101 DISARMED = 0,
102 ARMING = 1,
103 ARMED = 2,
104 DISARMING = 3,
105 };
106
107 enum class ConnectionMode { RELAXED = 0, AGGRESSIVE = 1 };
108
connectability_state_machine_text(const ConnectabilityState & state)109 inline std::string connectability_state_machine_text(const ConnectabilityState& state) {
110 switch (state) {
111 CASE_RETURN_TEXT(ConnectabilityState::DISARMED);
112 CASE_RETURN_TEXT(ConnectabilityState::ARMING);
113 CASE_RETURN_TEXT(ConnectabilityState::ARMED);
114 CASE_RETURN_TEXT(ConnectabilityState::DISARMING);
115 }
116 }
117
118 struct le_acl_connection {
le_acl_connectionle_acl_connection119 le_acl_connection(AddressWithType remote_address,
120 std::unique_ptr<LeAclConnection> pending_connection,
121 AclConnection::QueueDownEnd* queue_down_end, os::Handler* handler)
122 : remote_address_(remote_address),
123 pending_connection_(std::move(pending_connection)),
124 assembler_(new acl_manager::assembler(remote_address, queue_down_end, handler)) {}
~le_acl_connectionle_acl_connection125 ~le_acl_connection() { delete assembler_; }
126 AddressWithType remote_address_;
127 std::unique_ptr<LeAclConnection> pending_connection_;
128 acl_manager::assembler* assembler_;
129 LeConnectionManagementCallbacks* le_connection_management_callbacks_ = nullptr;
130 };
131
132 struct le_impl : public bluetooth::hci::LeAddressManagerCallback {
le_implle_impl133 le_impl(HciLayer* hci_layer, Controller* controller, os::Handler* handler,
134 RoundRobinScheduler* round_robin_scheduler, bool crash_on_unknown_handle,
135 classic_impl* classic_impl)
136 : hci_layer_(hci_layer),
137 controller_(controller),
138 round_robin_scheduler_(round_robin_scheduler) {
139 hci_layer_ = hci_layer;
140 controller_ = controller;
141 handler_ = handler;
142 connections.crash_on_unknown_handle_ = crash_on_unknown_handle;
143 classic_impl_ = classic_impl;
144 le_acl_connection_interface_ = hci_layer_->GetLeAclConnectionInterface(
145 handler_->BindOn(this, &le_impl::on_le_event),
146 handler_->BindOn(this, &le_impl::on_le_disconnect),
147 handler_->BindOn(this, &le_impl::on_le_read_remote_version_information));
148 le_address_manager_ = new LeAddressManager(
149 common::Bind(&le_impl::enqueue_command, common::Unretained(this)), handler_,
150 controller->GetMacAddress(), controller->GetLeFilterAcceptListSize(),
151 controller->GetLeResolvingListSize(), controller_);
152 }
153
~le_implle_impl154 ~le_impl() {
155 if (address_manager_registered) {
156 le_address_manager_->UnregisterSync(this);
157 }
158 delete le_address_manager_;
159 hci_layer_->PutLeAclConnectionInterface();
160 connections.reset();
161 }
162
on_le_eventle_impl163 void on_le_event(LeMetaEventView event_packet) {
164 SubeventCode code = event_packet.GetSubeventCode();
165 switch (code) {
166 case SubeventCode::CONNECTION_COMPLETE:
167 case SubeventCode::ENHANCED_CONNECTION_COMPLETE:
168 on_le_connection_complete(event_packet);
169 break;
170 case SubeventCode::CONNECTION_UPDATE_COMPLETE:
171 on_le_connection_update_complete(event_packet);
172 break;
173 case SubeventCode::PHY_UPDATE_COMPLETE:
174 on_le_phy_update_complete(event_packet);
175 break;
176 case SubeventCode::DATA_LENGTH_CHANGE:
177 on_data_length_change(event_packet);
178 break;
179 case SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
180 on_remote_connection_parameter_request(event_packet);
181 break;
182 case SubeventCode::LE_SUBRATE_CHANGE:
183 on_le_subrate_change(event_packet);
184 break;
185 default:
186 log::fatal("Unhandled event code {}", SubeventCodeText(code));
187 }
188 }
189
190 private:
191 static constexpr uint16_t kIllegalConnectionHandle = 0xffff;
192 struct {
193 private:
194 std::map<uint16_t, le_acl_connection> le_acl_connections_;
195 mutable std::mutex le_acl_connections_guard_;
find_callbacksle_impl::__anon81a832520108196 LeConnectionManagementCallbacks* find_callbacks(uint16_t handle) {
197 auto connection = le_acl_connections_.find(handle);
198 if (connection == le_acl_connections_.end()) {
199 return nullptr;
200 }
201 return connection->second.le_connection_management_callbacks_;
202 }
removele_impl::__anon81a832520108203 void remove(uint16_t handle) {
204 auto connection = le_acl_connections_.find(handle);
205 if (connection != le_acl_connections_.end()) {
206 connection->second.le_connection_management_callbacks_ = nullptr;
207 le_acl_connections_.erase(handle);
208 }
209 }
210
211 public:
212 bool crash_on_unknown_handle_ = false;
sizele_impl::__anon81a832520108213 size_t size() const {
214 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
215 return le_acl_connections_.size();
216 }
is_emptyle_impl::__anon81a832520108217 bool is_empty() const {
218 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
219 return le_acl_connections_.empty();
220 }
resetle_impl::__anon81a832520108221 void reset() {
222 std::map<uint16_t, le_acl_connection> le_acl_connections{};
223 {
224 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
225 le_acl_connections = std::move(le_acl_connections_);
226 }
227 le_acl_connections.clear();
228 }
invalidatele_impl::__anon81a832520108229 void invalidate(uint16_t handle) {
230 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
231 remove(handle);
232 }
233 void execute(uint16_t handle,
234 std::function<void(LeConnectionManagementCallbacks* callbacks)> execute,
235 bool remove_afterwards = false) {
236 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
237 auto callbacks = find_callbacks(handle);
238 if (callbacks != nullptr) {
239 execute(callbacks);
240 } else {
241 log::assert_that(!crash_on_unknown_handle_, "Received command for unknown handle:0x{:x}",
242 handle);
243 }
244 if (remove_afterwards) {
245 remove(handle);
246 }
247 }
send_packet_upwardle_impl::__anon81a832520108248 bool send_packet_upward(uint16_t handle,
249 std::function<void(struct acl_manager::assembler* assembler)> cb) {
250 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
251 auto connection = le_acl_connections_.find(handle);
252 if (connection != le_acl_connections_.end()) {
253 cb(connection->second.assembler_);
254 }
255 return connection != le_acl_connections_.end();
256 }
addle_impl::__anon81a832520108257 void add(uint16_t handle, const AddressWithType& remote_address,
258 std::unique_ptr<LeAclConnection> pending_connection,
259 AclConnection::QueueDownEnd* queue_end, os::Handler* handler,
260 LeConnectionManagementCallbacks* le_connection_management_callbacks) {
261 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
262 auto emplace_pair = le_acl_connections_.emplace(
263 std::piecewise_construct, std::forward_as_tuple(handle),
264 std::forward_as_tuple(remote_address, std::move(pending_connection), queue_end,
265 handler));
266 log::assert_that(emplace_pair.second,
267 "assert failed: emplace_pair.second"); // Make sure the connection is unique
268 emplace_pair.first->second.le_connection_management_callbacks_ =
269 le_connection_management_callbacks;
270 }
271
record_peripheral_data_and_extract_pending_connectionle_impl::__anon81a832520108272 std::unique_ptr<LeAclConnection> record_peripheral_data_and_extract_pending_connection(
273 uint16_t handle, DataAsPeripheral data) {
274 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
275 auto connection = le_acl_connections_.find(handle);
276 if (connection != le_acl_connections_.end() && connection->second.pending_connection_.get()) {
277 connection->second.pending_connection_->UpdateRoleSpecificData(data);
278 return std::move(connection->second.pending_connection_);
279 } else {
280 return nullptr;
281 }
282 }
283
HACK_get_handlele_impl::__anon81a832520108284 uint16_t HACK_get_handle(Address address) const {
285 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
286 for (auto it = le_acl_connections_.begin(); it != le_acl_connections_.end(); it++) {
287 if (it->second.remote_address_.GetAddress() == address) {
288 return it->first;
289 }
290 }
291 return kIllegalConnectionHandle;
292 }
293
getAddressWithTypele_impl::__anon81a832520108294 AddressWithType getAddressWithType(uint16_t handle) {
295 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
296 auto it = le_acl_connections_.find(handle);
297 if (it != le_acl_connections_.end()) {
298 return it->second.remote_address_;
299 }
300 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
301 return empty;
302 }
303
alreadyConnectedle_impl::__anon81a832520108304 bool alreadyConnected(AddressWithType address_with_type) {
305 for (auto it = le_acl_connections_.begin(); it != le_acl_connections_.end(); it++) {
306 if (it->second.remote_address_ == address_with_type) {
307 return true;
308 }
309 }
310 return false;
311 }
312 } connections;
313
connection_mode_to_stringle_impl314 std::string connection_mode_to_string(ConnectionMode connection_mode) {
315 switch (connection_mode) {
316 case ConnectionMode::RELAXED:
317 return "RELAXED";
318 case ConnectionMode::AGGRESSIVE:
319 return "AGGRESSIVE";
320 default:
321 return "UNKNOWN";
322 }
323 }
324
325 public:
enqueue_commandle_impl326 void enqueue_command(std::unique_ptr<CommandBuilder> command_packet) {
327 hci_layer_->EnqueueCommand(std::move(command_packet),
328 handler_->BindOnce(&LeAddressManager::OnCommandComplete,
329 common::Unretained(le_address_manager_)));
330 }
331
send_packet_upwardle_impl332 bool send_packet_upward(uint16_t handle,
333 std::function<void(struct acl_manager::assembler* assembler)> cb) {
334 return connections.send_packet_upward(handle, cb);
335 }
336
report_le_connection_failurele_impl337 void report_le_connection_failure(AddressWithType address, ErrorCode status) {
338 le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectFail,
339 common::Unretained(le_client_callbacks_), address,
340 status));
341 if (le_acceptlist_callbacks_ != nullptr) {
342 le_acceptlist_callbacks_->OnLeConnectFail(address, status);
343 }
344 }
345
set_connectability_statele_impl346 void set_connectability_state(ConnectabilityState state) {
347 log::debug("{} --> {}", connectability_state_machine_text(connectability_state_),
348 connectability_state_machine_text(state));
349 connectability_state_ = state;
350 if (com::android::bluetooth::flags::le_impl_ack_pause_disarmed()) {
351 if (state == ConnectabilityState::DISARMED && pause_connection) {
352 le_address_manager_->AckPause(this);
353 }
354 }
355 }
356
357 // connection canceled by LeAddressManager.OnPause(), will auto reconnect by
358 // LeAddressManager.OnResume()
on_le_connection_canceled_on_pausele_impl359 void on_le_connection_canceled_on_pause() {
360 log::assert_that(pause_connection, "Connection must be paused to ack the le address manager");
361 arm_on_resume_ = true;
362 set_connectability_state(ConnectabilityState::DISARMED);
363 if (!com::android::bluetooth::flags::le_impl_ack_pause_disarmed()) {
364 le_address_manager_->AckPause(this);
365 }
366 }
367
on_common_le_connection_completele_impl368 void on_common_le_connection_complete(AddressWithType address_with_type) {
369 auto connecting_addr_with_type = connecting_le_.find(address_with_type);
370 if (connecting_addr_with_type == connecting_le_.end()) {
371 log::warn("No prior connection request for {}", address_with_type);
372 }
373 connecting_le_.clear();
374
375 direct_connect_remove(address_with_type);
376 }
377
on_le_connection_completele_impl378 void on_le_connection_complete(LeMetaEventView packet) {
379 ErrorCode status;
380 Address address;
381 AddressType peer_address_type;
382 Role role;
383 AddressWithType remote_address;
384 uint16_t handle, conn_interval, conn_latency, supervision_timeout;
385
386 if (packet.GetSubeventCode() == SubeventCode::CONNECTION_COMPLETE) {
387 LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
388 log::assert_that(connection_complete.IsValid(),
389 "assert failed: connection_complete.IsValid()");
390 status = connection_complete.GetStatus();
391 address = connection_complete.GetPeerAddress();
392 peer_address_type = connection_complete.GetPeerAddressType();
393 role = connection_complete.GetRole();
394 handle = connection_complete.GetConnectionHandle();
395 conn_interval = connection_complete.GetConnInterval();
396 conn_latency = connection_complete.GetConnLatency();
397 supervision_timeout = connection_complete.GetSupervisionTimeout();
398 remote_address = AddressWithType(address, peer_address_type);
399 } else if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) {
400 LeEnhancedConnectionCompleteView connection_complete =
401 LeEnhancedConnectionCompleteView::Create(packet);
402 log::assert_that(connection_complete.IsValid(),
403 "assert failed: connection_complete.IsValid()");
404 status = connection_complete.GetStatus();
405 address = connection_complete.GetPeerAddress();
406 peer_address_type = connection_complete.GetPeerAddressType();
407 role = connection_complete.GetRole();
408 handle = connection_complete.GetConnectionHandle();
409 conn_interval = connection_complete.GetConnInterval();
410 conn_latency = connection_complete.GetConnLatency();
411 supervision_timeout = connection_complete.GetSupervisionTimeout();
412 AddressType remote_address_type;
413 switch (peer_address_type) {
414 case AddressType::PUBLIC_DEVICE_ADDRESS:
415 case AddressType::PUBLIC_IDENTITY_ADDRESS:
416 remote_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
417 break;
418 case AddressType::RANDOM_DEVICE_ADDRESS:
419 case AddressType::RANDOM_IDENTITY_ADDRESS:
420 remote_address_type = AddressType::RANDOM_DEVICE_ADDRESS;
421 break;
422 }
423 remote_address = AddressWithType(address, remote_address_type);
424 } else {
425 log::fatal("Bad subevent code:{:02x}", packet.GetSubeventCode());
426 return;
427 }
428
429 bluetooth::shim::LogMetricLeConnectionStatus(address, true /* is_connect */, status);
430
431 const bool in_filter_accept_list = is_device_in_accept_list(remote_address);
432
433 if (role == hci::Role::CENTRAL) {
434 set_connectability_state(ConnectabilityState::DISARMED);
435 if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
436 on_le_connection_canceled_on_pause();
437 return;
438 }
439 if (status == ErrorCode::UNKNOWN_CONNECTION && arm_on_disarm_) {
440 arm_on_disarm_ = false;
441 arm_connectability();
442 return;
443 }
444 on_common_le_connection_complete(remote_address);
445 if (status == ErrorCode::UNKNOWN_CONNECTION) {
446 if (remote_address.GetAddress() != Address::kEmpty) {
447 log::info("Controller send non-empty address field:{}", remote_address.GetAddress());
448 }
449 // direct connect canceled due to connection timeout, start background connect
450 create_le_connection(remote_address, false, false);
451 return;
452 }
453
454 arm_on_resume_ = false;
455 ready_to_unregister = true;
456 remove_device_from_accept_list(remote_address);
457
458 if (!accept_list.empty()) {
459 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
460 handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this),
461 empty, false, false));
462 }
463
464 if (le_client_handler_ == nullptr) {
465 log::error("No callbacks to call");
466 return;
467 }
468
469 if (status != ErrorCode::SUCCESS) {
470 report_le_connection_failure(remote_address, status);
471 return;
472 }
473 } else {
474 log::info("Received connection complete with Peripheral role");
475 if (le_client_handler_ == nullptr) {
476 log::error("No callbacks to call");
477 return;
478 }
479
480 if (status != ErrorCode::SUCCESS) {
481 std::string error_code = ErrorCodeText(status);
482 log::warn("Received on_le_connection_complete with error code {}", error_code);
483 report_le_connection_failure(remote_address, status);
484 return;
485 }
486
487 if (in_filter_accept_list) {
488 log::info("Received incoming connection of device in filter accept_list, {}",
489 remote_address);
490 direct_connect_remove(remote_address);
491 remove_device_from_accept_list(remote_address);
492 }
493 }
494
495 if (!check_connection_parameters(conn_interval, conn_interval, conn_latency,
496 supervision_timeout)) {
497 log::error("Receive connection complete with invalid connection parameters");
498 return;
499 }
500 auto role_specific_data = initialize_role_specific_data(role);
501 auto queue = std::make_shared<AclConnection::Queue>(10);
502 auto queue_down_end = queue->GetDownEnd();
503 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
504 std::unique_ptr<LeAclConnection> connection(
505 new LeAclConnection(std::move(queue), le_acl_connection_interface_, handle,
506 role_specific_data, remote_address));
507 connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
508 connection->interval_ = conn_interval;
509 connection->latency_ = conn_latency;
510 connection->supervision_timeout_ = supervision_timeout;
511 connection->in_filter_accept_list_ = in_filter_accept_list;
512 connection->locally_initiated_ = (role == hci::Role::CENTRAL);
513
514 log::info("addr={}, conn_interval={}", remote_address, conn_interval);
515
516 if (packet.GetSubeventCode() == SubeventCode::ENHANCED_CONNECTION_COMPLETE) {
517 LeEnhancedConnectionCompleteView connection_complete =
518 LeEnhancedConnectionCompleteView::Create(packet);
519 log::assert_that(connection_complete.IsValid(),
520 "assert failed: connection_complete.IsValid()");
521
522 connection->local_resolvable_private_address_ =
523 connection_complete.GetLocalResolvablePrivateAddress();
524 connection->peer_resolvable_private_address_ =
525 connection_complete.GetPeerResolvablePrivateAddress();
526 }
527
528 auto connection_callbacks = connection->GetEventCallbacks(
529 [this](uint16_t handle) { this->connections.invalidate(handle); });
530 if (std::holds_alternative<DataAsUninitializedPeripheral>(role_specific_data)) {
531 // the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated
532 // event, since we need it to know what local_address / advertising set the peer connected to.
533 // In the meantime, we store it as a pending_connection.
534 connections.add(handle, remote_address, std::move(connection), queue_down_end, handler_,
535 connection_callbacks);
536 } else {
537 connections.add(handle, remote_address, nullptr, queue_down_end, handler_,
538 connection_callbacks);
539 le_client_handler_->Post(common::BindOnce(&LeConnectionCallbacks::OnLeConnectSuccess,
540 common::Unretained(le_client_callbacks_),
541 remote_address, std::move(connection)));
542 if (le_acceptlist_callbacks_ != nullptr) {
543 le_acceptlist_callbacks_->OnLeConnectSuccess(remote_address);
544 }
545 }
546 }
547
initialize_role_specific_datale_impl548 RoleSpecificData initialize_role_specific_data(Role role) {
549 if (role == hci::Role::CENTRAL) {
550 return DataAsCentral{le_address_manager_->GetInitiatorAddress()};
551 } else if (controller_->SupportsBleExtendedAdvertising() ||
552 controller_->IsSupported(hci::OpCode::LE_MULTI_ADVT)) {
553 // when accepting connection, we must obtain the address from the advertiser.
554 // When we receive "set terminated event", we associate connection handle with advertiser
555 // address
556 return DataAsUninitializedPeripheral{};
557 } else {
558 // the exception is if we only support legacy advertising - here, our current address is also
559 // our advertised address
560 return DataAsPeripheral{
561 le_address_manager_->GetInitiatorAddress(),
562 {},
563 true /* For now, ignore non-discoverable legacy advertising TODO(b/254314964) */};
564 }
565 }
566
567 static constexpr bool kRemoveConnectionAfterwards = true;
on_le_disconnectle_impl568 void on_le_disconnect(uint16_t handle, ErrorCode reason) {
569 AddressWithType remote_address = connections.getAddressWithType(handle);
570 bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_;
571 connections.crash_on_unknown_handle_ = false;
572 connections.execute(
573 handle,
574 [=, this](LeConnectionManagementCallbacks* callbacks) {
575 round_robin_scheduler_->Unregister(handle);
576 callbacks->OnDisconnection(reason);
577 },
578 kRemoveConnectionAfterwards);
579 if (le_acceptlist_callbacks_ != nullptr) {
580 le_acceptlist_callbacks_->OnLeDisconnection(remote_address);
581 }
582 connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers;
583
584 if (background_connections_.count(remote_address) == 1) {
585 log::info("re-add device to accept list");
586 arm_on_resume_ = true;
587 add_device_to_accept_list(remote_address);
588 }
589 bluetooth::shim::LogMetricLeConnectionStatus(remote_address.GetAddress(),
590 false /* is_connect */, reason);
591 }
592
on_le_connection_update_completele_impl593 void on_le_connection_update_complete(LeMetaEventView view) {
594 auto complete_view = LeConnectionUpdateCompleteView::Create(view);
595 if (!complete_view.IsValid()) {
596 log::error("Received on_le_connection_update_complete with invalid packet");
597 return;
598 }
599 auto handle = complete_view.GetConnectionHandle();
600 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
601 callbacks->OnConnectionUpdate(complete_view.GetStatus(), complete_view.GetConnInterval(),
602 complete_view.GetConnLatency(),
603 complete_view.GetSupervisionTimeout());
604 });
605 }
606
on_le_phy_update_completele_impl607 void on_le_phy_update_complete(LeMetaEventView view) {
608 auto complete_view = LePhyUpdateCompleteView::Create(view);
609 if (!complete_view.IsValid()) {
610 log::error("Received on_le_phy_update_complete with invalid packet");
611 return;
612 }
613 auto handle = complete_view.GetConnectionHandle();
614 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
615 callbacks->OnPhyUpdate(complete_view.GetStatus(), complete_view.GetTxPhy(),
616 complete_view.GetRxPhy());
617 });
618 }
619
on_le_read_remote_version_informationle_impl620 void on_le_read_remote_version_information(hci::ErrorCode hci_status, uint16_t handle,
621 uint8_t version, uint16_t manufacturer_name,
622 uint16_t sub_version) {
623 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
624 callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name,
625 sub_version);
626 });
627 }
628
on_data_length_changele_impl629 void on_data_length_change(LeMetaEventView view) {
630 auto data_length_view = LeDataLengthChangeView::Create(view);
631 if (!data_length_view.IsValid()) {
632 log::error("Invalid packet");
633 return;
634 }
635 auto handle = data_length_view.GetConnectionHandle();
636 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
637 callbacks->OnDataLengthChange(
638 data_length_view.GetMaxTxOctets(), data_length_view.GetMaxTxTime(),
639 data_length_view.GetMaxRxOctets(), data_length_view.GetMaxRxTime());
640 });
641 }
642
on_remote_connection_parameter_requestle_impl643 void on_remote_connection_parameter_request(LeMetaEventView view) {
644 auto request_view = LeRemoteConnectionParameterRequestView::Create(view);
645 if (!request_view.IsValid()) {
646 log::error("Invalid packet");
647 return;
648 }
649
650 connections.execute(request_view.GetConnectionHandle(),
651 [request_view](LeConnectionManagementCallbacks* callbacks) {
652 callbacks->OnParameterUpdateRequest(
653 request_view.GetIntervalMin(), request_view.GetIntervalMax(),
654 request_view.GetLatency(), request_view.GetTimeout());
655 });
656 }
657
on_le_subrate_changele_impl658 void on_le_subrate_change(LeMetaEventView view) {
659 auto subrate_change_view = LeSubrateChangeView::Create(view);
660 if (!subrate_change_view.IsValid()) {
661 log::error("Invalid packet");
662 return;
663 }
664 auto handle = subrate_change_view.GetConnectionHandle();
665 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
666 callbacks->OnLeSubrateChange(subrate_change_view.GetStatus(),
667 subrate_change_view.GetSubrateFactor(),
668 subrate_change_view.GetPeripheralLatency(),
669 subrate_change_view.GetContinuationNumber(),
670 subrate_change_view.GetSupervisionTimeout());
671 });
672 }
673
HACK_get_handlele_impl674 uint16_t HACK_get_handle(Address address) { return connections.HACK_get_handle(address); }
675
HACK_get_addressle_impl676 Address HACK_get_address(uint16_t connection_handle) {
677 return connections.getAddressWithType(connection_handle).GetAddress();
678 }
679
OnAdvertisingSetTerminatedle_impl680 void OnAdvertisingSetTerminated(uint16_t conn_handle, uint8_t adv_set_id,
681 hci::AddressWithType adv_set_address, bool is_discoverable) {
682 auto connection = connections.record_peripheral_data_and_extract_pending_connection(
683 conn_handle, DataAsPeripheral{adv_set_address, adv_set_id, is_discoverable});
684
685 if (connection != nullptr) {
686 if (le_acceptlist_callbacks_ != nullptr) {
687 le_acceptlist_callbacks_->OnLeConnectSuccess(connection->GetRemoteAddress());
688 }
689 le_client_handler_->Post(common::BindOnce(
690 &LeConnectionCallbacks::OnLeConnectSuccess, common::Unretained(le_client_callbacks_),
691 connection->GetRemoteAddress(), std::move(connection)));
692 }
693 }
694
direct_connect_addle_impl695 void direct_connect_add(AddressWithType address_with_type) {
696 log::debug("{}", address_with_type);
697 direct_connections_.insert(address_with_type);
698 if (create_connection_timeout_alarms_.find(address_with_type) !=
699 create_connection_timeout_alarms_.end()) {
700 log::verbose("Timer already added for {}", address_with_type);
701 return;
702 }
703
704 auto emplace_result = create_connection_timeout_alarms_.emplace(
705 std::piecewise_construct,
706 std::forward_as_tuple(address_with_type.GetAddress(),
707 address_with_type.GetAddressType()),
708 std::forward_as_tuple(handler_));
709 uint32_t connection_timeout =
710 os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs);
711 emplace_result.first->second.Schedule(
712 common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this),
713 address_with_type),
714 std::chrono::milliseconds(connection_timeout));
715 }
716
direct_connect_removele_impl717 void direct_connect_remove(AddressWithType address_with_type) {
718 log::debug("{}", address_with_type);
719 auto it = create_connection_timeout_alarms_.find(address_with_type);
720 if (it != create_connection_timeout_alarms_.end()) {
721 it->second.Cancel();
722 create_connection_timeout_alarms_.erase(it);
723 }
724 direct_connections_.erase(address_with_type);
725 }
726
add_device_to_accept_listle_impl727 void add_device_to_accept_list(AddressWithType address_with_type) {
728 bluetooth::shim::LogMetricLeDeviceInAcceptList(address_with_type.GetAddress(),
729 true /* is_add */);
730 if (connections.alreadyConnected(address_with_type)) {
731 log::info("Device already connected, return");
732 return;
733 }
734
735 if (accept_list.find(address_with_type) != accept_list.end()) {
736 log::warn("Device already exists in acceptlist and cannot be added: {}", address_with_type);
737 return;
738 }
739
740 log::debug("Adding device to accept list {}", address_with_type);
741 accept_list.insert(address_with_type);
742 register_with_address_manager();
743 le_address_manager_->AddDeviceToFilterAcceptList(
744 address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
745 }
746
is_device_in_accept_listle_impl747 bool is_device_in_accept_list(AddressWithType address_with_type) {
748 return accept_list.find(address_with_type) != accept_list.end();
749 }
750
remove_device_from_accept_listle_impl751 void remove_device_from_accept_list(AddressWithType address_with_type) {
752 bluetooth::shim::LogMetricLeDeviceInAcceptList(address_with_type.GetAddress(),
753 false /* is_add */);
754 if (accept_list.find(address_with_type) == accept_list.end()) {
755 log::warn("Device not in acceptlist and cannot be removed: {}", address_with_type);
756 return;
757 }
758 accept_list.erase(address_with_type);
759 connecting_le_.erase(address_with_type);
760 register_with_address_manager();
761 le_address_manager_->RemoveDeviceFromFilterAcceptList(
762 address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
763 }
764
clear_filter_accept_listle_impl765 void clear_filter_accept_list() {
766 accept_list.clear();
767 register_with_address_manager();
768 le_address_manager_->ClearFilterAcceptList();
769 }
770
add_device_to_resolving_listle_impl771 void add_device_to_resolving_list(AddressWithType address_with_type,
772 const std::array<uint8_t, 16>& peer_irk,
773 const std::array<uint8_t, 16>& local_irk) {
774 register_with_address_manager();
775 le_address_manager_->AddDeviceToResolvingList(address_with_type.ToPeerAddressType(),
776 address_with_type.GetAddress(), peer_irk,
777 local_irk);
778 if (le_acceptlist_callbacks_ != nullptr) {
779 le_acceptlist_callbacks_->OnResolvingListChange();
780 }
781 }
782
remove_device_from_resolving_listle_impl783 void remove_device_from_resolving_list(AddressWithType address_with_type) {
784 register_with_address_manager();
785 le_address_manager_->RemoveDeviceFromResolvingList(address_with_type.ToPeerAddressType(),
786 address_with_type.GetAddress());
787 if (le_acceptlist_callbacks_ != nullptr) {
788 le_acceptlist_callbacks_->OnResolvingListChange();
789 }
790 }
791
update_connectability_state_after_armedle_impl792 void update_connectability_state_after_armed(const ErrorCode& status) {
793 switch (connectability_state_) {
794 case ConnectabilityState::DISARMED:
795 case ConnectabilityState::ARMED:
796 case ConnectabilityState::DISARMING:
797 log::error("Received connectability arm notification for unexpected state:{} status:{}",
798 connectability_state_machine_text(connectability_state_), ErrorCodeText(status));
799 break;
800 case ConnectabilityState::ARMING:
801 if (status != ErrorCode::SUCCESS) {
802 log::error("Le connection state machine armed failed status:{}", ErrorCodeText(status));
803 }
804 set_connectability_state((status == ErrorCode::SUCCESS) ? ConnectabilityState::ARMED
805 : ConnectabilityState::DISARMED);
806 log::info("Le connection state machine armed state:{} status:{}",
807 connectability_state_machine_text(connectability_state_), ErrorCodeText(status));
808 if (disarmed_while_arming_) {
809 disarmed_while_arming_ = false;
810 disarm_connectability();
811 }
812 }
813 }
814
on_extended_create_connectionle_impl815 void on_extended_create_connection(CommandStatusView status) {
816 log::assert_that(status.IsValid(), "assert failed: status.IsValid()");
817 log::assert_that(
818 status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION,
819 "assert failed: status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION");
820 update_connectability_state_after_armed(status.GetStatus());
821 }
822
on_create_connectionle_impl823 void on_create_connection(CommandStatusView status) {
824 log::assert_that(status.IsValid(), "assert failed: status.IsValid()");
825 log::assert_that(status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION,
826 "assert failed: status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION");
827 update_connectability_state_after_armed(status.GetStatus());
828 }
829
arm_connectabilityle_impl830 void arm_connectability() {
831 if (connectability_state_ != ConnectabilityState::DISARMED) {
832 log::error("Attempting to re-arm le connection state machine in unexpected state:{}",
833 connectability_state_machine_text(connectability_state_));
834 return;
835 }
836 if (accept_list.empty()) {
837 log::info(
838 "Ignored request to re-arm le connection state machine when filter accept list is "
839 "empty");
840 return;
841 }
842 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
843 set_connectability_state(ConnectabilityState::ARMING);
844 connecting_le_ = accept_list;
845
846 uint16_t le_scan_interval =
847 os::GetSystemPropertyUint32(kPropertyConnScanIntervalSlow, kScanIntervalSlow);
848 uint16_t le_scan_window =
849 os::GetSystemPropertyUint32(kPropertyConnScanWindowSlow, kScanWindowSlow);
850 uint16_t le_scan_window_2m = le_scan_window;
851 uint16_t le_scan_window_coded = le_scan_window;
852 // If there is any direct connection in the connection list, use the fast parameter
853 if (!direct_connections_.empty()) {
854 le_scan_interval =
855 os::GetSystemPropertyUint32(kPropertyConnScanIntervalFast, kScanIntervalFast);
856 le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowFast, kScanWindowFast);
857 le_scan_window_2m =
858 os::GetSystemPropertyUint32(kPropertyConnScanWindow2mFast, kScanWindow2mFast);
859 le_scan_window_coded =
860 os::GetSystemPropertyUint32(kPropertyConnScanWindowCodedFast, kScanWindowCodedFast);
861 }
862 // Use specific parameters when in system suspend.
863 if (system_suspend_) {
864 le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalSystemSuspend,
865 kScanIntervalSystemSuspend);
866 le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowSystemSuspend,
867 kScanWindowSystemSuspend);
868 le_scan_window_2m = le_scan_window;
869 le_scan_window_coded = le_scan_window;
870 }
871 InitiatorFilterPolicy initiator_filter_policy = InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST;
872 OwnAddressType own_address_type = static_cast<OwnAddressType>(
873 le_address_manager_->GetInitiatorAddress().GetAddressType());
874
875 uint16_t conn_interval_min;
876 uint16_t conn_interval_max;
877 bool prefer_relaxed_connection_interval = false;
878 if (com::android::bluetooth::flags::channel_sounding_in_stack()) {
879 for (const auto& address_with_type : direct_connections_) {
880 bluetooth::hci::Address address = address_with_type.GetAddress();
881 if (relaxed_connection_interval_devices_set_.count(address) > 0) {
882 log::info(
883 "Found device {} in direct connection list that prefers using the relaxed "
884 "connection interval",
885 address);
886 prefer_relaxed_connection_interval = true;
887 break;
888 }
889 }
890 }
891
892 if (com::android::bluetooth::flags::initial_conn_params_p1()) {
893 if (prefer_relaxed_connection_interval) {
894 conn_interval_min = LeConnectionParameters::GetMinConnIntervalRelaxed();
895 conn_interval_max = LeConnectionParameters::GetMaxConnIntervalRelaxed();
896 log::debug("conn_interval_min={}, conn_interval_max={}", conn_interval_min,
897 conn_interval_max);
898 } else {
899 size_t num_classic_acl_connections = classic_impl_->get_connection_count();
900 size_t num_acl_connections = connections.size();
901
902 log::debug("ACL connection count: Classic={}, LE={}", num_classic_acl_connections,
903 num_acl_connections);
904
905 choose_connection_mode(num_classic_acl_connections + num_acl_connections,
906 &conn_interval_min, &conn_interval_max);
907 }
908 } else {
909 conn_interval_min = os::GetSystemPropertyUint32(kPropertyMinConnInterval, kConnIntervalMin);
910 conn_interval_max = os::GetSystemPropertyUint32(kPropertyMaxConnInterval, kConnIntervalMax);
911 }
912
913 uint16_t conn_latency = os::GetSystemPropertyUint32(kPropertyConnLatency, kConnLatency);
914 uint16_t supervision_timeout =
915 os::GetSystemPropertyUint32(kPropertyConnSupervisionTimeout, kSupervisionTimeout);
916 log::assert_that(
917 check_connection_parameters(conn_interval_min, conn_interval_max, conn_latency,
918 supervision_timeout),
919 "assert failed: check_connection_parameters(conn_interval_min, conn_interval_max, "
920 "conn_latency, supervision_timeout)");
921
922 AddressWithType address_with_type = connection_peer_address_with_type_;
923 if (initiator_filter_policy == InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) {
924 address_with_type = AddressWithType();
925 }
926
927 if (controller_->IsRpaGenerationSupported() &&
928 own_address_type != OwnAddressType::PUBLIC_DEVICE_ADDRESS) {
929 log::info("Support RPA offload, set own address type RESOLVABLE_OR_RANDOM_ADDRESS");
930 own_address_type = OwnAddressType::RESOLVABLE_OR_RANDOM_ADDRESS;
931 }
932
933 if (controller_->IsSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION)) {
934 bool only_init_1m_phy =
935 os::GetSystemPropertyBool(kPropertyEnableBleOnlyInit1mPhy, kEnableBleOnlyInit1mPhy);
936
937 uint8_t initiating_phys = PHY_LE_1M;
938 std::vector<LeCreateConnPhyScanParameters> parameters = {};
939 LeCreateConnPhyScanParameters scan_parameters;
940 scan_parameters.scan_interval_ = le_scan_interval;
941 scan_parameters.scan_window_ = le_scan_window;
942 scan_parameters.conn_interval_min_ = conn_interval_min;
943 scan_parameters.conn_interval_max_ = conn_interval_max;
944 scan_parameters.conn_latency_ = conn_latency;
945 scan_parameters.supervision_timeout_ = supervision_timeout;
946 scan_parameters.min_ce_length_ = 0x00;
947 scan_parameters.max_ce_length_ = 0x00;
948 parameters.push_back(scan_parameters);
949
950 if (controller_->SupportsBle2mPhy() && !only_init_1m_phy) {
951 LeCreateConnPhyScanParameters scan_parameters_2m;
952 scan_parameters_2m.scan_interval_ = le_scan_interval;
953 scan_parameters_2m.scan_window_ = le_scan_window_2m;
954 scan_parameters_2m.conn_interval_min_ = conn_interval_min;
955 scan_parameters_2m.conn_interval_max_ = conn_interval_max;
956 scan_parameters_2m.conn_latency_ = conn_latency;
957 scan_parameters_2m.supervision_timeout_ = supervision_timeout;
958 scan_parameters_2m.min_ce_length_ = 0x00;
959 scan_parameters_2m.max_ce_length_ = 0x00;
960 parameters.push_back(scan_parameters_2m);
961 initiating_phys |= PHY_LE_2M;
962 }
963 if (controller_->SupportsBleCodedPhy() && !only_init_1m_phy) {
964 LeCreateConnPhyScanParameters scan_parameters_coded;
965 scan_parameters_coded.scan_interval_ = le_scan_interval;
966 scan_parameters_coded.scan_window_ = le_scan_window_coded;
967 scan_parameters_coded.conn_interval_min_ = conn_interval_min;
968 scan_parameters_coded.conn_interval_max_ = conn_interval_max;
969 scan_parameters_coded.conn_latency_ = conn_latency;
970 scan_parameters_coded.supervision_timeout_ = supervision_timeout;
971 scan_parameters_coded.min_ce_length_ = 0x00;
972 scan_parameters_coded.max_ce_length_ = 0x00;
973 parameters.push_back(scan_parameters_coded);
974 initiating_phys |= PHY_LE_CODED;
975 }
976
977 le_acl_connection_interface_->EnqueueCommand(
978 LeExtendedCreateConnectionBuilder::Create(
979 initiator_filter_policy, own_address_type, address_with_type.GetAddressType(),
980 address_with_type.GetAddress(), initiating_phys, parameters),
981 handler_->BindOnce(&le_impl::on_extended_create_connection,
982 common::Unretained(this)));
983 } else {
984 le_acl_connection_interface_->EnqueueCommand(
985 LeCreateConnectionBuilder::Create(
986 le_scan_interval, le_scan_window, initiator_filter_policy,
987 address_with_type.GetAddressType(), address_with_type.GetAddress(),
988 own_address_type, conn_interval_min, conn_interval_max, conn_latency,
989 supervision_timeout, 0x00, 0x00),
990 handler_->BindOnce(&le_impl::on_create_connection, common::Unretained(this)));
991 }
992 }
993
994 // Choose which connection mode should be used based on the number of ongoing ACL connections.
995 // According to the connection mode, connection interval min/max values are set.
choose_connection_modele_impl996 void choose_connection_mode(size_t num_acl_connections, uint16_t* conn_interval_min,
997 uint16_t* conn_interval_max) {
998 ConnectionMode connection_mode = ConnectionMode::RELAXED;
999
1000 uint32_t aggressive_connection_threshold = LeConnectionParameters::GetAggressiveConnThreshold();
1001 log::debug("num_acl_connections={}, aggressive_connection_threshold={}", num_acl_connections,
1002 aggressive_connection_threshold);
1003
1004 if (num_acl_connections < aggressive_connection_threshold) {
1005 connection_mode = ConnectionMode::AGGRESSIVE;
1006 }
1007
1008 switch (connection_mode) {
1009 case ConnectionMode::AGGRESSIVE:
1010 *conn_interval_min = LeConnectionParameters::GetMinConnIntervalAggressive();
1011 *conn_interval_max = LeConnectionParameters::GetMaxConnIntervalAggressive();
1012 break;
1013 case ConnectionMode::RELAXED:
1014 default:
1015 *conn_interval_min = LeConnectionParameters::GetMinConnIntervalRelaxed();
1016 *conn_interval_max = LeConnectionParameters::GetMaxConnIntervalRelaxed();
1017 break;
1018 }
1019 log::info("Connection mode: {}", connection_mode_to_string(connection_mode));
1020 log::debug("conn_interval_min={}, conn_interval_max={}", *conn_interval_min,
1021 *conn_interval_max);
1022 }
1023
disarm_connectabilityle_impl1024 void disarm_connectability() {
1025 switch (connectability_state_) {
1026 case ConnectabilityState::ARMED:
1027 log::info("Disarming LE connection state machine with create connection cancel");
1028 set_connectability_state(ConnectabilityState::DISARMING);
1029 le_acl_connection_interface_->EnqueueCommand(
1030 LeCreateConnectionCancelBuilder::Create(),
1031 handler_->BindOnce(&le_impl::on_create_connection_cancel_complete,
1032 common::Unretained(this)));
1033 break;
1034
1035 case ConnectabilityState::ARMING:
1036 log::info("Queueing cancel connect until after connection state machine is armed");
1037 disarmed_while_arming_ = true;
1038 break;
1039 case ConnectabilityState::DISARMING:
1040 case ConnectabilityState::DISARMED:
1041 log::error("Attempting to disarm le connection state machine in unexpected state:{}",
1042 connectability_state_machine_text(connectability_state_));
1043 break;
1044 }
1045 }
1046
create_le_connectionle_impl1047 void create_le_connection(AddressWithType address_with_type, bool add_to_accept_list,
1048 bool is_direct) {
1049 if (le_client_callbacks_ == nullptr) {
1050 log::error("No callbacks to call");
1051 return;
1052 }
1053
1054 if (connections.alreadyConnected(address_with_type)) {
1055 log::info("Device already connected, return");
1056 return;
1057 }
1058
1059 bool already_in_accept_list = accept_list.find(address_with_type) != accept_list.end();
1060 // TODO: Configure default LE connection parameters?
1061 if (add_to_accept_list) {
1062 if (!already_in_accept_list) {
1063 add_device_to_accept_list(address_with_type);
1064 }
1065
1066 bool in_accept_list_due_to_direct_connect =
1067 direct_connections_.find(address_with_type) != direct_connections_.end();
1068
1069 if (already_in_accept_list && (in_accept_list_due_to_direct_connect || !is_direct)) {
1070 log::info("Device {} already in accept list. Stop here.", address_with_type);
1071 return;
1072 }
1073
1074 if (is_direct) {
1075 direct_connect_add(address_with_type);
1076 }
1077 }
1078
1079 if (!address_manager_registered) {
1080 auto policy = le_address_manager_->Register(this);
1081 address_manager_registered = true;
1082
1083 // Pause connection, wait for set random address complete
1084 if (policy == LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS ||
1085 policy == LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
1086 pause_connection = true;
1087 }
1088 }
1089
1090 if (pause_connection) {
1091 arm_on_resume_ = true;
1092 return;
1093 }
1094
1095 log::verbose("{}, already_in_accept_list: {}, pause_connection {}, state: {}",
1096 address_with_type, already_in_accept_list, pause_connection,
1097 connectability_state_machine_text(connectability_state_));
1098
1099 switch (connectability_state_) {
1100 case ConnectabilityState::ARMED:
1101 case ConnectabilityState::ARMING:
1102 if (already_in_accept_list) {
1103 arm_on_disarm_ = true;
1104 disarm_connectability();
1105 } else {
1106 // Ignored, if we add new device to the filter accept list, create connection command will
1107 // be sent by OnResume.
1108 log::debug("Deferred until filter accept list updated create connection state {}",
1109 connectability_state_machine_text(connectability_state_));
1110 }
1111 break;
1112 default:
1113 // If we added to filter accept list then the arming of the le state machine
1114 // must wait until the filter accept list command as completed
1115 if (add_to_accept_list) {
1116 arm_on_resume_ = true;
1117 log::debug("Deferred until filter accept list has completed");
1118 } else {
1119 handler_->CallOn(this, &le_impl::arm_connectability);
1120 }
1121 break;
1122 }
1123 }
1124
on_create_connection_timeoutle_impl1125 void on_create_connection_timeout(AddressWithType address_with_type) {
1126 log::info("on_create_connection_timeout, address: {}", address_with_type);
1127 direct_connect_remove(address_with_type);
1128
1129 if (background_connections_.find(address_with_type) != background_connections_.end()) {
1130 disarm_connectability();
1131 } else {
1132 remove_device_from_accept_list(address_with_type);
1133 }
1134 // Temporary mapping the error code to PAGE_TIMEOUT
1135 bluetooth::shim::LogMetricLeConnectionCompletion(address_with_type.GetAddress(),
1136 ErrorCode::PAGE_TIMEOUT,
1137 true /* is locally initiated */);
1138 le_client_handler_->Post(common::BindOnce(
1139 &LeConnectionCallbacks::OnLeConnectFail, common::Unretained(le_client_callbacks_),
1140 address_with_type, ErrorCode::CONNECTION_ACCEPT_TIMEOUT));
1141 }
1142
cancel_connectle_impl1143 void cancel_connect(AddressWithType address_with_type) {
1144 direct_connect_remove(address_with_type);
1145 // the connection will be canceled by LeAddressManager.OnPause()
1146 remove_device_from_accept_list(address_with_type);
1147 }
1148
clear_resolving_listle_impl1149 void clear_resolving_list() { le_address_manager_->ClearResolvingList(); }
1150
set_privacy_policy_for_initiator_addressle_impl1151 void set_privacy_policy_for_initiator_address(LeAddressManager::AddressPolicy address_policy,
1152 AddressWithType fixed_address, Octet16 rotation_irk,
1153 std::chrono::milliseconds minimum_rotation_time,
1154 std::chrono::milliseconds maximum_rotation_time) {
1155 le_address_manager_->SetPrivacyPolicyForInitiatorAddress(
1156 address_policy, fixed_address, rotation_irk,
1157 controller_->SupportsBlePrivacy() &&
1158 os::GetSystemPropertyBool(kPropertyEnableBlePrivacy, kEnableBlePrivacy),
1159 minimum_rotation_time, maximum_rotation_time);
1160 }
1161
1162 // TODO(jpawlowski): remove once we have config file abstraction in cert tests
set_privacy_policy_for_initiator_address_for_testle_impl1163 void set_privacy_policy_for_initiator_address_for_test(
1164 LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address,
1165 Octet16 rotation_irk, std::chrono::milliseconds minimum_rotation_time,
1166 std::chrono::milliseconds maximum_rotation_time) {
1167 le_address_manager_->SetPrivacyPolicyForInitiatorAddressForTest(
1168 address_policy, fixed_address, rotation_irk, minimum_rotation_time,
1169 maximum_rotation_time);
1170 }
1171
handle_register_le_callbacksle_impl1172 void handle_register_le_callbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) {
1173 log::assert_that(le_client_callbacks_ == nullptr,
1174 "assert failed: le_client_callbacks_ == nullptr");
1175 log::assert_that(le_client_handler_ == nullptr, "assert failed: le_client_handler_ == nullptr");
1176 le_client_callbacks_ = callbacks;
1177 le_client_handler_ = handler;
1178 }
1179
handle_register_le_acceptlist_callbacksle_impl1180 void handle_register_le_acceptlist_callbacks(LeAcceptlistCallbacks* callbacks) {
1181 log::assert_that(le_acceptlist_callbacks_ == nullptr,
1182 "assert failed: le_acceptlist_callbacks_ == nullptr");
1183 le_acceptlist_callbacks_ = callbacks;
1184 }
1185
handle_unregister_le_callbacksle_impl1186 void handle_unregister_le_callbacks(LeConnectionCallbacks* callbacks,
1187 std::promise<void> promise) {
1188 log::assert_that(le_client_callbacks_ == callbacks,
1189 "Registered le callback entity is different then unregister request");
1190 le_client_callbacks_ = nullptr;
1191 le_client_handler_ = nullptr;
1192 promise.set_value();
1193 }
1194
handle_unregister_le_acceptlist_callbacksle_impl1195 void handle_unregister_le_acceptlist_callbacks(LeAcceptlistCallbacks* callbacks,
1196 std::promise<void> promise) {
1197 log::assert_that(le_acceptlist_callbacks_ == callbacks,
1198 "Registered le callback entity is different then unregister request");
1199 le_acceptlist_callbacks_ = nullptr;
1200 promise.set_value();
1201 }
1202
check_connection_parametersle_impl1203 bool check_connection_parameters(uint16_t conn_interval_min, uint16_t conn_interval_max,
1204 uint16_t conn_latency, uint16_t supervision_timeout) {
1205 if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
1206 conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
1207 supervision_timeout > 0x0C80) {
1208 log::error("Invalid parameter");
1209 return false;
1210 }
1211
1212 // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
1213 // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
1214 // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where
1215 // Interval_Max is given in milliseconds.
1216 uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
1217 if (supervision_timeout * 8 < supervision_timeout_min ||
1218 conn_interval_max < conn_interval_min) {
1219 log::error("Invalid parameter");
1220 return false;
1221 }
1222
1223 return true;
1224 }
1225
add_device_to_background_connection_listle_impl1226 void add_device_to_background_connection_list(AddressWithType address_with_type) {
1227 background_connections_.insert(address_with_type);
1228 }
1229
remove_device_from_background_connection_listle_impl1230 void remove_device_from_background_connection_list(AddressWithType address_with_type) {
1231 background_connections_.erase(address_with_type);
1232 }
1233
OnPausele_impl1234 void OnPause() override { // bluetooth::hci::LeAddressManagerCallback
1235 if (!address_manager_registered) {
1236 log::warn("Unregistered!");
1237 return;
1238 }
1239 pause_connection = true;
1240 if (connectability_state_ == ConnectabilityState::DISARMED) {
1241 le_address_manager_->AckPause(this);
1242 return;
1243 }
1244 arm_on_resume_ = !connecting_le_.empty();
1245 disarm_connectability();
1246 }
1247
OnResumele_impl1248 void OnResume() override { // bluetooth::hci::LeAddressManagerCallback
1249 if (!address_manager_registered) {
1250 log::warn("Unregistered!");
1251 return;
1252 }
1253 pause_connection = false;
1254 if (arm_on_resume_) {
1255 arm_connectability();
1256 }
1257 arm_on_resume_ = false;
1258 le_address_manager_->AckResume(this);
1259 check_for_unregister();
1260 }
1261
on_create_connection_cancel_completele_impl1262 void on_create_connection_cancel_complete(CommandCompleteView view) {
1263 auto complete_view = LeCreateConnectionCancelCompleteView::Create(view);
1264 log::assert_that(complete_view.IsValid(), "assert failed: complete_view.IsValid()");
1265 if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1266 auto status = complete_view.GetStatus();
1267 std::string error_code = ErrorCodeText(status);
1268 log::warn("Received on_create_connection_cancel_complete with error code {}", error_code);
1269 if (pause_connection) {
1270 log::warn("AckPause");
1271 le_address_manager_->AckPause(this);
1272 return;
1273 }
1274 }
1275 if (connectability_state_ != ConnectabilityState::DISARMING) {
1276 log::error("Attempting to disarm le connection state machine in unexpected state:{}",
1277 connectability_state_machine_text(connectability_state_));
1278 }
1279 }
1280
register_with_address_managerle_impl1281 void register_with_address_manager() {
1282 if (!address_manager_registered) {
1283 le_address_manager_->Register(this);
1284 address_manager_registered = true;
1285 pause_connection = true;
1286 }
1287 }
1288
check_for_unregisterle_impl1289 void check_for_unregister() {
1290 if (connections.is_empty() && connecting_le_.empty() && address_manager_registered &&
1291 ready_to_unregister) {
1292 le_address_manager_->Unregister(this);
1293 address_manager_registered = false;
1294 pause_connection = false;
1295 ready_to_unregister = false;
1296 }
1297 }
1298
set_system_suspend_statele_impl1299 void set_system_suspend_state(bool suspended) { system_suspend_ = suspended; }
1300
add_device_to_relaxed_connection_interval_listle_impl1301 void add_device_to_relaxed_connection_interval_list(const Address address) {
1302 relaxed_connection_interval_devices_set_.insert(address);
1303 }
1304
1305 HciLayer* hci_layer_ = nullptr;
1306 Controller* controller_ = nullptr;
1307 os::Handler* handler_ = nullptr;
1308 RoundRobinScheduler* round_robin_scheduler_ = nullptr;
1309 LeAddressManager* le_address_manager_ = nullptr;
1310 LeAclConnectionInterface* le_acl_connection_interface_ = nullptr;
1311 classic_impl* classic_impl_ = nullptr;
1312 LeConnectionCallbacks* le_client_callbacks_ = nullptr;
1313 os::Handler* le_client_handler_ = nullptr;
1314 LeAcceptlistCallbacks* le_acceptlist_callbacks_ = nullptr;
1315 std::unordered_set<AddressWithType> connecting_le_{};
1316 bool arm_on_resume_{};
1317 bool arm_on_disarm_{};
1318 std::unordered_set<AddressWithType> direct_connections_{};
1319 // Set of devices that will not be removed from accept list after direct connect timeout
1320 std::unordered_set<AddressWithType> background_connections_;
1321 /* This is content of controller "Filter Accept List"*/
1322 std::unordered_set<AddressWithType> accept_list;
1323 AddressWithType connection_peer_address_with_type_; // Direct peer address UNSUPPORTEDD
1324 bool address_manager_registered = false;
1325 bool ready_to_unregister = false;
1326 bool pause_connection = false;
1327 bool disarmed_while_arming_ = false;
1328 bool system_suspend_ = false;
1329 ConnectabilityState connectability_state_{ConnectabilityState::DISARMED};
1330 std::map<AddressWithType, os::Alarm> create_connection_timeout_alarms_{};
1331 // Set of devices that should use the relaxed connection intervals.
1332 std::unordered_set<Address> relaxed_connection_interval_devices_set_;
1333 };
1334
1335 } // namespace acl_manager
1336 } // namespace hci
1337 } // namespace bluetooth
1338