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
21 #include <atomic>
22 #include <cstddef>
23 #include <cstdint>
24 #include <memory>
25 #include <optional>
26 #include <string>
27 #include <unordered_set>
28
29 #include "common/bind.h"
30 #include "common/init_flags.h"
31 #include "crypto_toolbox/crypto_toolbox.h"
32 #include "hci/acl_manager/assembler.h"
33 #include "hci/acl_manager/le_acceptlist_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 "os/alarm.h"
41 #include "os/handler.h"
42 #include "os/metrics.h"
43 #include "os/system_properties.h"
44 #include "packet/packet_view.h"
45
46 using bluetooth::crypto_toolbox::Octet16;
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 = "bluetooth.core.le.connection_supervision_timeout";
78 static const std::string kPropertyDirectConnTimeout = "bluetooth.core.le.direct_connection_timeout";
79 static const std::string kPropertyConnScanIntervalFast = "bluetooth.core.le.connection_scan_interval_fast";
80 static const std::string kPropertyConnScanWindowFast = "bluetooth.core.le.connection_scan_window_fast";
81 static const std::string kPropertyConnScanWindow2mFast = "bluetooth.core.le.connection_scan_window_2m_fast";
82 static const std::string kPropertyConnScanWindowCodedFast = "bluetooth.core.le.connection_scan_window_coded_fast";
83 static const std::string kPropertyConnScanIntervalSlow = "bluetooth.core.le.connection_scan_interval_slow";
84 static const std::string kPropertyConnScanWindowSlow = "bluetooth.core.le.connection_scan_window_slow";
85 static const std::string kPropertyEnableBlePrivacy = "bluetooth.core.gap.le.privacy.enabled";
86 static const std::string kPropertyEnableBleOnlyInit1mPhy = "bluetooth.core.gap.le.conn.only_init_1m_phy.enabled";
87
88 enum class ConnectabilityState {
89 DISARMED = 0,
90 ARMING = 1,
91 ARMED = 2,
92 DISARMING = 3,
93 };
94
95 #define CASE_RETURN_TEXT(code) \
96 case code: \
97 return #code
98
connectability_state_machine_text(const ConnectabilityState & state)99 inline std::string connectability_state_machine_text(const ConnectabilityState& state) {
100 switch (state) {
101 CASE_RETURN_TEXT(ConnectabilityState::DISARMED);
102 CASE_RETURN_TEXT(ConnectabilityState::ARMING);
103 CASE_RETURN_TEXT(ConnectabilityState::ARMED);
104 CASE_RETURN_TEXT(ConnectabilityState::DISARMING);
105 default:
106 return base::StringPrintf("UNKNOWN[%d]", state);
107 }
108 }
109 #undef CASE_RETURN_TEXT
110
111 struct le_acl_connection {
le_acl_connectionle_acl_connection112 le_acl_connection(
113 AddressWithType remote_address,
114 std::unique_ptr<LeAclConnection> pending_connection,
115 AclConnection::QueueDownEnd* queue_down_end,
116 os::Handler* handler)
117 : remote_address_(remote_address),
118 pending_connection_(std::move(pending_connection)),
119 assembler_(new acl_manager::assembler(remote_address, queue_down_end, handler)) {}
~le_acl_connectionle_acl_connection120 ~le_acl_connection() {
121 delete assembler_;
122 }
123 AddressWithType remote_address_;
124 std::unique_ptr<LeAclConnection> pending_connection_;
125 acl_manager::assembler* assembler_;
126 LeConnectionManagementCallbacks* le_connection_management_callbacks_ = nullptr;
127 };
128
129 struct le_impl : public bluetooth::hci::LeAddressManagerCallback {
le_implle_impl130 le_impl(
131 HciLayer* hci_layer,
132 Controller* controller,
133 os::Handler* handler,
134 RoundRobinScheduler* round_robin_scheduler,
135 bool crash_on_unknown_handle)
136 : hci_layer_(hci_layer), controller_(controller), round_robin_scheduler_(round_robin_scheduler) {
137 hci_layer_ = hci_layer;
138 controller_ = controller;
139 handler_ = handler;
140 connections.crash_on_unknown_handle_ = crash_on_unknown_handle;
141 le_acl_connection_interface_ = hci_layer_->GetLeAclConnectionInterface(
142 handler_->BindOn(this, &le_impl::on_le_event),
143 handler_->BindOn(this, &le_impl::on_le_disconnect),
144 handler_->BindOn(this, &le_impl::on_le_read_remote_version_information));
145 le_address_manager_ = new LeAddressManager(
146 common::Bind(&le_impl::enqueue_command, common::Unretained(this)),
147 handler_,
148 controller->GetMacAddress(),
149 controller->GetLeFilterAcceptListSize(),
150 controller->GetLeResolvingListSize());
151 }
152
~le_implle_impl153 ~le_impl() {
154 if (address_manager_registered) {
155 le_address_manager_->UnregisterSync(this);
156 }
157 delete le_address_manager_;
158 hci_layer_->PutLeAclConnectionInterface();
159 connections.reset();
160 }
161
on_le_eventle_impl162 void on_le_event(LeMetaEventView event_packet) {
163 SubeventCode code = event_packet.GetSubeventCode();
164 switch (code) {
165 case SubeventCode::CONNECTION_COMPLETE:
166 on_le_connection_complete(event_packet);
167 break;
168 case SubeventCode::ENHANCED_CONNECTION_COMPLETE:
169 on_le_enhanced_connection_complete(event_packet);
170 break;
171 case SubeventCode::CONNECTION_UPDATE_COMPLETE:
172 on_le_connection_update_complete(event_packet);
173 break;
174 case SubeventCode::PHY_UPDATE_COMPLETE:
175 on_le_phy_update_complete(event_packet);
176 break;
177 case SubeventCode::DATA_LENGTH_CHANGE:
178 on_data_length_change(event_packet);
179 break;
180 case SubeventCode::REMOTE_CONNECTION_PARAMETER_REQUEST:
181 on_remote_connection_parameter_request(event_packet);
182 break;
183 case SubeventCode::LE_SUBRATE_CHANGE:
184 on_le_subrate_change(event_packet);
185 break;
186 default:
187 LOG_ALWAYS_FATAL("Unhandled event code %s", SubeventCodeText(code).c_str());
188 }
189 }
190
191 private:
192 static constexpr uint16_t kIllegalConnectionHandle = 0xffff;
193 struct {
194 private:
195 std::map<uint16_t, le_acl_connection> le_acl_connections_;
196 mutable std::mutex le_acl_connections_guard_;
find_callbacksle_impl::__anondbd707610108197 LeConnectionManagementCallbacks* find_callbacks(uint16_t handle) {
198 auto connection = le_acl_connections_.find(handle);
199 if (connection == le_acl_connections_.end()) return nullptr;
200 return connection->second.le_connection_management_callbacks_;
201 }
removele_impl::__anondbd707610108202 void remove(uint16_t handle) {
203 auto connection = le_acl_connections_.find(handle);
204 if (connection != le_acl_connections_.end()) {
205 connection->second.le_connection_management_callbacks_ = nullptr;
206 le_acl_connections_.erase(handle);
207 }
208 }
209
210 public:
211 bool crash_on_unknown_handle_ = false;
is_emptyle_impl::__anondbd707610108212 bool is_empty() const {
213 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
214 return le_acl_connections_.empty();
215 }
resetle_impl::__anondbd707610108216 void reset() {
217 std::map<uint16_t, le_acl_connection> le_acl_connections{};
218 {
219 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
220 le_acl_connections = std::move(le_acl_connections_);
221 }
222 le_acl_connections.clear();
223 }
invalidatele_impl::__anondbd707610108224 void invalidate(uint16_t handle) {
225 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
226 remove(handle);
227 }
228 void execute(
229 uint16_t handle,
230 std::function<void(LeConnectionManagementCallbacks* callbacks)> execute,
231 bool remove_afterwards = false) {
232 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
233 auto callbacks = find_callbacks(handle);
234 if (callbacks != nullptr)
235 execute(callbacks);
236 else
237 ASSERT_LOG(!crash_on_unknown_handle_, "Received command for unknown handle:0x%x", handle);
238 if (remove_afterwards) remove(handle);
239 }
send_packet_upwardle_impl::__anondbd707610108240 bool send_packet_upward(uint16_t handle, std::function<void(struct acl_manager::assembler* assembler)> cb) {
241 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
242 auto connection = le_acl_connections_.find(handle);
243 if (connection != le_acl_connections_.end()) cb(connection->second.assembler_);
244 return connection != le_acl_connections_.end();
245 }
addle_impl::__anondbd707610108246 void add(
247 uint16_t handle,
248 const AddressWithType& remote_address,
249 std::unique_ptr<LeAclConnection> pending_connection,
250 AclConnection::QueueDownEnd* queue_end,
251 os::Handler* handler,
252 LeConnectionManagementCallbacks* le_connection_management_callbacks) {
253 std::unique_lock<std::mutex> lock(le_acl_connections_guard_);
254 auto emplace_pair = le_acl_connections_.emplace(
255 std::piecewise_construct,
256 std::forward_as_tuple(handle),
257 std::forward_as_tuple(remote_address, std::move(pending_connection), queue_end, handler));
258 ASSERT(emplace_pair.second); // Make sure the connection is unique
259 emplace_pair.first->second.le_connection_management_callbacks_ = le_connection_management_callbacks;
260 }
261
record_peripheral_data_and_extract_pending_connectionle_impl::__anondbd707610108262 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::__anondbd707610108274 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::__anondbd707610108284 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::__anondbd707610108294 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
303 } connections;
304
305 public:
enqueue_commandle_impl306 void enqueue_command(std::unique_ptr<CommandBuilder> command_packet) {
307 hci_layer_->EnqueueCommand(
308 std::move(command_packet),
309 handler_->BindOnce(&LeAddressManager::OnCommandComplete, common::Unretained(le_address_manager_)));
310 }
311
send_packet_upwardle_impl312 bool send_packet_upward(uint16_t handle, 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(
318 &LeConnectionCallbacks::OnLeConnectFail,
319 common::Unretained(le_client_callbacks_),
320 address,
321 status));
322 if (le_acceptlist_callbacks_ != nullptr) {
323 le_acceptlist_callbacks_->OnLeConnectFail(address, status);
324 }
325 }
326
327 // connection canceled by LeAddressManager.OnPause(), will auto reconnect by LeAddressManager.OnResume()
on_le_connection_canceled_on_pausele_impl328 void on_le_connection_canceled_on_pause() {
329 ASSERT_LOG(pause_connection, "Connection must be paused to ack the le address manager");
330 arm_on_resume_ = true;
331 connectability_state_ = ConnectabilityState::DISARMED;
332 le_address_manager_->AckPause(this);
333 }
334
on_common_le_connection_completele_impl335 void on_common_le_connection_complete(AddressWithType address_with_type) {
336 auto connecting_addr_with_type = connecting_le_.find(address_with_type);
337 if (connecting_addr_with_type == connecting_le_.end()) {
338 LOG_WARN("No prior connection request for %s", ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
339 }
340 connecting_le_.clear();
341
342 if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
343 create_connection_timeout_alarms_.at(address_with_type).Cancel();
344 create_connection_timeout_alarms_.erase(address_with_type);
345 }
346 }
347
on_le_connection_completele_impl348 void on_le_connection_complete(LeMetaEventView packet) {
349 LeConnectionCompleteView connection_complete = LeConnectionCompleteView::Create(packet);
350 ASSERT(connection_complete.IsValid());
351 auto status = connection_complete.GetStatus();
352 auto address = connection_complete.GetPeerAddress();
353 auto peer_address_type = connection_complete.GetPeerAddressType();
354 auto role = connection_complete.GetRole();
355 AddressWithType remote_address(address, peer_address_type);
356 AddressWithType local_address = le_address_manager_->GetInitiatorAddress();
357 const bool in_filter_accept_list = is_device_in_connect_list(remote_address);
358 auto argument_list = std::vector<std::pair<bluetooth::os::ArgumentType, int>>();
359 argument_list.push_back(
360 std::make_pair(os::ArgumentType::ACL_STATUS_CODE, static_cast<int>(status)));
361
362 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
363 address,
364 android::bluetooth::le::LeConnectionOriginType::ORIGIN_NATIVE,
365 android::bluetooth::le::LeConnectionType::CONNECTION_TYPE_LE_ACL,
366 android::bluetooth::le::LeConnectionState::STATE_LE_ACL_END,
367 argument_list);
368
369 if (role == hci::Role::CENTRAL) {
370 connectability_state_ = ConnectabilityState::DISARMED;
371 if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
372 on_le_connection_canceled_on_pause();
373 return;
374 }
375 on_common_le_connection_complete(remote_address);
376 if (status == ErrorCode::UNKNOWN_CONNECTION) {
377 if (remote_address.GetAddress() != Address::kEmpty) {
378 LOG_INFO("Controller send non-empty address field:%s",
379 ADDRESS_TO_LOGGABLE_CSTR(remote_address.GetAddress()));
380 }
381 // direct connect canceled due to connection timeout, start background connect
382 create_le_connection(remote_address, false, false);
383 return;
384 }
385
386 arm_on_resume_ = false;
387 ready_to_unregister = true;
388 remove_device_from_connect_list(remote_address);
389
390 if (!connect_list.empty()) {
391 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
392 handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
393 }
394
395 if (le_client_handler_ == nullptr) {
396 LOG_ERROR("No callbacks to call");
397 return;
398 }
399
400 if (status != ErrorCode::SUCCESS) {
401 report_le_connection_failure(remote_address, status);
402 return;
403 }
404 } else {
405 LOG_INFO("Received connection complete with Peripheral role");
406 if (le_client_handler_ == nullptr) {
407 LOG_ERROR("No callbacks to call");
408 return;
409 }
410
411 if (status != ErrorCode::SUCCESS) {
412 std::string error_code = ErrorCodeText(status);
413 LOG_WARN("Received on_le_connection_complete with error code %s", error_code.c_str());
414 report_le_connection_failure(remote_address, status);
415 return;
416 }
417
418 if (in_filter_accept_list) {
419 LOG_INFO(
420 "Received incoming connection of device in filter accept_list, %s",
421 ADDRESS_TO_LOGGABLE_CSTR(remote_address));
422 remove_device_from_connect_list(remote_address);
423 if (create_connection_timeout_alarms_.find(remote_address) != create_connection_timeout_alarms_.end()) {
424 create_connection_timeout_alarms_.at(remote_address).Cancel();
425 create_connection_timeout_alarms_.erase(remote_address);
426 }
427 }
428 }
429
430 uint16_t conn_interval = connection_complete.GetConnInterval();
431 uint16_t conn_latency = connection_complete.GetConnLatency();
432 uint16_t supervision_timeout = connection_complete.GetSupervisionTimeout();
433 if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
434 LOG_ERROR("Receive connection complete with invalid connection parameters");
435 return;
436 }
437
438 uint16_t handle = connection_complete.GetConnectionHandle();
439 auto role_specific_data = initialize_role_specific_data(role);
440 auto queue = std::make_shared<AclConnection::Queue>(10);
441 auto queue_down_end = queue->GetDownEnd();
442 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
443 std::unique_ptr<LeAclConnection> connection(new LeAclConnection(
444 std::move(queue),
445 le_acl_connection_interface_,
446 handle,
447 role_specific_data,
448 remote_address));
449 connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
450 connection->interval_ = conn_interval;
451 connection->latency_ = conn_latency;
452 connection->supervision_timeout_ = supervision_timeout;
453 connection->in_filter_accept_list_ = in_filter_accept_list;
454 connection->locally_initiated_ = (role == hci::Role::CENTRAL);
455 auto connection_callbacks = connection->GetEventCallbacks(
456 [this](uint16_t handle) { this->connections.invalidate(handle); });
457 if (std::holds_alternative<DataAsUninitializedPeripheral>(role_specific_data)) {
458 // the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated
459 // event, since we need it to know what local_address / advertising set the peer connected to.
460 // In the meantime, we store it as a pending_connection.
461 connections.add(
462 handle,
463 remote_address,
464 std::move(connection),
465 queue_down_end,
466 handler_,
467 connection_callbacks);
468 } else {
469 connections.add(
470 handle, remote_address, nullptr, queue_down_end, handler_, connection_callbacks);
471 le_client_handler_->Post(common::BindOnce(
472 &LeConnectionCallbacks::OnLeConnectSuccess,
473 common::Unretained(le_client_callbacks_),
474 remote_address,
475 std::move(connection)));
476 if (le_acceptlist_callbacks_ != nullptr) {
477 le_acceptlist_callbacks_->OnLeConnectSuccess(remote_address);
478 }
479 }
480 }
481
on_le_enhanced_connection_completele_impl482 void on_le_enhanced_connection_complete(LeMetaEventView packet) {
483 LeEnhancedConnectionCompleteView connection_complete = LeEnhancedConnectionCompleteView::Create(packet);
484 ASSERT(connection_complete.IsValid());
485 auto status = connection_complete.GetStatus();
486 auto address = connection_complete.GetPeerAddress();
487 auto peer_address_type = connection_complete.GetPeerAddressType();
488 auto peer_resolvable_address = connection_complete.GetPeerResolvablePrivateAddress();
489 auto role = connection_complete.GetRole();
490
491 AddressType remote_address_type;
492 switch (peer_address_type) {
493 case AddressType::PUBLIC_DEVICE_ADDRESS:
494 case AddressType::PUBLIC_IDENTITY_ADDRESS:
495 remote_address_type = AddressType::PUBLIC_DEVICE_ADDRESS;
496 break;
497 case AddressType::RANDOM_DEVICE_ADDRESS:
498 case AddressType::RANDOM_IDENTITY_ADDRESS:
499 remote_address_type = AddressType::RANDOM_DEVICE_ADDRESS;
500 break;
501 }
502 AddressWithType remote_address(address, remote_address_type);
503 const bool in_filter_accept_list = is_device_in_connect_list(remote_address);
504 auto argument_list = std::vector<std::pair<bluetooth::os::ArgumentType, int>>();
505 argument_list.push_back(
506 std::make_pair(os::ArgumentType::ACL_STATUS_CODE, static_cast<int>(status)));
507
508 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
509 address,
510 android::bluetooth::le::LeConnectionOriginType::ORIGIN_NATIVE,
511 android::bluetooth::le::LeConnectionType::CONNECTION_TYPE_LE_ACL,
512 android::bluetooth::le::LeConnectionState::STATE_LE_ACL_END,
513 argument_list);
514
515 if (role == hci::Role::CENTRAL) {
516 connectability_state_ = ConnectabilityState::DISARMED;
517
518 if (status == ErrorCode::UNKNOWN_CONNECTION && pause_connection) {
519 on_le_connection_canceled_on_pause();
520 return;
521 }
522
523 on_common_le_connection_complete(remote_address);
524 if (status == ErrorCode::UNKNOWN_CONNECTION) {
525 if (remote_address.GetAddress() != Address::kEmpty) {
526 LOG_INFO("Controller send non-empty address field:%s",
527 ADDRESS_TO_LOGGABLE_CSTR(remote_address.GetAddress()));
528 }
529 // direct connect canceled due to connection timeout, start background connect
530 create_le_connection(remote_address, false, false);
531 return;
532 }
533
534 arm_on_resume_ = false;
535 ready_to_unregister = true;
536 remove_device_from_connect_list(remote_address);
537
538 if (!connect_list.empty()) {
539 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
540 handler_->Post(common::BindOnce(&le_impl::create_le_connection, common::Unretained(this), empty, false, false));
541 }
542
543 if (le_client_handler_ == nullptr) {
544 LOG_ERROR("No callbacks to call");
545 return;
546 }
547
548 if (status != ErrorCode::SUCCESS) {
549 report_le_connection_failure(remote_address, status);
550 return;
551 }
552
553 } else {
554 LOG_INFO("Received connection complete with Peripheral role");
555 if (le_client_handler_ == nullptr) {
556 LOG_ERROR("No callbacks to call");
557 return;
558 }
559
560 if (status != ErrorCode::SUCCESS) {
561 std::string error_code = ErrorCodeText(status);
562 LOG_WARN("Received on_le_enhanced_connection_complete with error code %s", error_code.c_str());
563 report_le_connection_failure(remote_address, status);
564 return;
565 }
566
567 if (in_filter_accept_list) {
568 LOG_INFO(
569 "Received incoming connection of device in filter accept_list, %s",
570 ADDRESS_TO_LOGGABLE_CSTR(remote_address));
571 remove_device_from_connect_list(remote_address);
572 if (create_connection_timeout_alarms_.find(remote_address) != create_connection_timeout_alarms_.end()) {
573 create_connection_timeout_alarms_.at(remote_address).Cancel();
574 create_connection_timeout_alarms_.erase(remote_address);
575 }
576 }
577 }
578
579 auto role_specific_data = initialize_role_specific_data(role);
580 uint16_t conn_interval = connection_complete.GetConnInterval();
581 uint16_t conn_latency = connection_complete.GetConnLatency();
582 uint16_t supervision_timeout = connection_complete.GetSupervisionTimeout();
583 if (!check_connection_parameters(conn_interval, conn_interval, conn_latency, supervision_timeout)) {
584 LOG_ERROR("Receive enhenced connection complete with invalid connection parameters");
585 return;
586 }
587 uint16_t handle = connection_complete.GetConnectionHandle();
588 auto queue = std::make_shared<AclConnection::Queue>(10);
589 auto queue_down_end = queue->GetDownEnd();
590 round_robin_scheduler_->Register(RoundRobinScheduler::ConnectionType::LE, handle, queue);
591 std::unique_ptr<LeAclConnection> connection(new LeAclConnection(
592 std::move(queue),
593 le_acl_connection_interface_,
594 handle,
595 role_specific_data,
596 remote_address));
597 connection->peer_address_with_type_ = AddressWithType(address, peer_address_type);
598 connection->interval_ = conn_interval;
599 connection->latency_ = conn_latency;
600 connection->supervision_timeout_ = supervision_timeout;
601 connection->local_resolvable_private_address_ = connection_complete.GetLocalResolvablePrivateAddress();
602 connection->peer_resolvable_private_address_ = connection_complete.GetPeerResolvablePrivateAddress();
603 connection->in_filter_accept_list_ = in_filter_accept_list;
604 connection->locally_initiated_ = (role == hci::Role::CENTRAL);
605
606 auto connection_callbacks = connection->GetEventCallbacks(
607 [this](uint16_t handle) { this->connections.invalidate(handle); });
608
609 if (std::holds_alternative<DataAsUninitializedPeripheral>(role_specific_data)) {
610 // the OnLeConnectSuccess event will be sent after receiving the On Advertising Set Terminated
611 // event, since we need it to know what local_address / advertising set the peer connected to.
612 // In the meantime, we store it as a pending_connection.
613 connections.add(
614 handle,
615 remote_address,
616 std::move(connection),
617 queue_down_end,
618 handler_,
619 connection_callbacks);
620 } else {
621 connections.add(
622 handle, remote_address, nullptr, queue_down_end, handler_, connection_callbacks);
623 le_client_handler_->Post(common::BindOnce(
624 &LeConnectionCallbacks::OnLeConnectSuccess,
625 common::Unretained(le_client_callbacks_),
626 remote_address,
627 std::move(connection)));
628 if (le_acceptlist_callbacks_ != nullptr) {
629 le_acceptlist_callbacks_->OnLeConnectSuccess(remote_address);
630 }
631 }
632 }
633
initialize_role_specific_datale_impl634 RoleSpecificData initialize_role_specific_data(Role role) {
635 if (role == hci::Role::CENTRAL) {
636 return DataAsCentral{le_address_manager_->GetInitiatorAddress()};
637 } else if (
638 controller_->SupportsBleExtendedAdvertising() ||
639 controller_->IsSupported(hci::OpCode::LE_MULTI_ADVT)) {
640 // when accepting connection, we must obtain the address from the advertiser.
641 // When we receive "set terminated event", we associate connection handle with advertiser
642 // address
643 return DataAsUninitializedPeripheral{};
644 } else {
645 // the exception is if we only support legacy advertising - here, our current address is also
646 // our advertised address
647 return DataAsPeripheral{
648 le_address_manager_->GetInitiatorAddress(),
649 {},
650 true /* For now, ignore non-discoverable legacy advertising TODO(b/254314964) */};
651 }
652 }
653
654 static constexpr bool kRemoveConnectionAfterwards = true;
on_le_disconnectle_impl655 void on_le_disconnect(uint16_t handle, ErrorCode reason) {
656 AddressWithType remote_address = connections.getAddressWithType(handle);
657 bool event_also_routes_to_other_receivers = connections.crash_on_unknown_handle_;
658 connections.crash_on_unknown_handle_ = false;
659 connections.execute(
660 handle,
661 [=](LeConnectionManagementCallbacks* callbacks) {
662 round_robin_scheduler_->Unregister(handle);
663 callbacks->OnDisconnection(reason);
664 },
665 kRemoveConnectionAfterwards);
666 if (le_acceptlist_callbacks_ != nullptr) {
667 le_acceptlist_callbacks_->OnLeDisconnection(remote_address);
668 }
669 connections.crash_on_unknown_handle_ = event_also_routes_to_other_receivers;
670
671 if (background_connections_.count(remote_address) == 1) {
672 LOG_INFO("re-add device to connect list");
673 arm_on_resume_ = true;
674 add_device_to_connect_list(remote_address);
675 }
676 }
677
on_le_connection_update_completele_impl678 void on_le_connection_update_complete(LeMetaEventView view) {
679 auto complete_view = LeConnectionUpdateCompleteView::Create(view);
680 if (!complete_view.IsValid()) {
681 LOG_ERROR("Received on_le_connection_update_complete with invalid packet");
682 return;
683 }
684 auto handle = complete_view.GetConnectionHandle();
685 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
686 callbacks->OnConnectionUpdate(
687 complete_view.GetStatus(),
688 complete_view.GetConnInterval(),
689 complete_view.GetConnLatency(),
690 complete_view.GetSupervisionTimeout());
691 });
692 }
693
on_le_phy_update_completele_impl694 void on_le_phy_update_complete(LeMetaEventView view) {
695 auto complete_view = LePhyUpdateCompleteView::Create(view);
696 if (!complete_view.IsValid()) {
697 LOG_ERROR("Received on_le_phy_update_complete with invalid packet");
698 return;
699 }
700 auto handle = complete_view.GetConnectionHandle();
701 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
702 callbacks->OnPhyUpdate(complete_view.GetStatus(), complete_view.GetTxPhy(), complete_view.GetRxPhy());
703 });
704 }
705
on_le_read_remote_version_informationle_impl706 void on_le_read_remote_version_information(
707 hci::ErrorCode hci_status, uint16_t handle, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version) {
708 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
709 callbacks->OnReadRemoteVersionInformationComplete(hci_status, version, manufacturer_name, sub_version);
710 });
711 }
712
on_data_length_changele_impl713 void on_data_length_change(LeMetaEventView view) {
714 auto data_length_view = LeDataLengthChangeView::Create(view);
715 if (!data_length_view.IsValid()) {
716 LOG_ERROR("Invalid packet");
717 return;
718 }
719 auto handle = data_length_view.GetConnectionHandle();
720 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
721 callbacks->OnDataLengthChange(
722 data_length_view.GetMaxTxOctets(),
723 data_length_view.GetMaxTxTime(),
724 data_length_view.GetMaxRxOctets(),
725 data_length_view.GetMaxRxTime());
726 });
727 }
728
on_remote_connection_parameter_requestle_impl729 void on_remote_connection_parameter_request(LeMetaEventView view) {
730 auto request_view = LeRemoteConnectionParameterRequestView::Create(view);
731 if (!request_view.IsValid()) {
732 LOG_ERROR("Invalid packet");
733 return;
734 }
735
736 auto handle = request_view.GetConnectionHandle();
737 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
738 // TODO: this is blindly accepting any parameters, just so we don't hang connection
739 // have proper parameter negotiation
740 le_acl_connection_interface_->EnqueueCommand(
741 LeRemoteConnectionParameterRequestReplyBuilder::Create(
742 handle,
743 request_view.GetIntervalMin(),
744 request_view.GetIntervalMax(),
745 request_view.GetLatency(),
746 request_view.GetTimeout(),
747 0,
748 0),
749 handler_->BindOnce([](CommandCompleteView status) {}));
750 });
751 }
752
on_le_subrate_changele_impl753 void on_le_subrate_change(LeMetaEventView view) {
754 auto subrate_change_view = LeSubrateChangeView::Create(view);
755 if (!subrate_change_view.IsValid()) {
756 LOG_ERROR("Invalid packet");
757 return;
758 }
759 auto handle = subrate_change_view.GetConnectionHandle();
760 connections.execute(handle, [=](LeConnectionManagementCallbacks* callbacks) {
761 callbacks->OnLeSubrateChange(
762 subrate_change_view.GetStatus(),
763 subrate_change_view.GetSubrateFactor(),
764 subrate_change_view.GetPeripheralLatency(),
765 subrate_change_view.GetContinuationNumber(),
766 subrate_change_view.GetSupervisionTimeout());
767 });
768 }
769
HACK_get_handlele_impl770 uint16_t HACK_get_handle(Address address) {
771 return connections.HACK_get_handle(address);
772 }
773
OnAdvertisingSetTerminatedle_impl774 void OnAdvertisingSetTerminated(
775 uint16_t conn_handle,
776 uint8_t adv_set_id,
777 hci::AddressWithType adv_set_address,
778 bool is_discoverable) {
779 auto connection = connections.record_peripheral_data_and_extract_pending_connection(
780 conn_handle, DataAsPeripheral{adv_set_address, adv_set_id, is_discoverable});
781
782 if (connection != nullptr) {
783 if (le_acceptlist_callbacks_ != nullptr) {
784 le_acceptlist_callbacks_->OnLeConnectSuccess(connection->GetRemoteAddress());
785 }
786 le_client_handler_->Post(common::BindOnce(
787 &LeConnectionCallbacks::OnLeConnectSuccess,
788 common::Unretained(le_client_callbacks_),
789 connection->GetRemoteAddress(),
790 std::move(connection)));
791 }
792 }
793
add_device_to_connect_listle_impl794 void add_device_to_connect_list(AddressWithType address_with_type) {
795 if (connections.alreadyConnected(address_with_type)) {
796 LOG_INFO("Device already connected, return");
797 return;
798 }
799
800 if (connect_list.find(address_with_type) != connect_list.end()) {
801 LOG_WARN(
802 "Device already exists in acceptlist and cannot be added:%s",
803 ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
804 return;
805 }
806
807 connect_list.insert(address_with_type);
808 register_with_address_manager();
809 le_address_manager_->AddDeviceToFilterAcceptList(
810 address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
811 }
812
is_device_in_connect_listle_impl813 bool is_device_in_connect_list(AddressWithType address_with_type) {
814 return (connect_list.find(address_with_type) != connect_list.end());
815 }
816
remove_device_from_connect_listle_impl817 void remove_device_from_connect_list(AddressWithType address_with_type) {
818 if (connect_list.find(address_with_type) == connect_list.end()) {
819 LOG_WARN("Device not in acceptlist and cannot be removed:%s",
820 ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
821 return;
822 }
823 connect_list.erase(address_with_type);
824 connecting_le_.erase(address_with_type);
825 direct_connections_.erase(address_with_type);
826 register_with_address_manager();
827 le_address_manager_->RemoveDeviceFromFilterAcceptList(
828 address_with_type.ToFilterAcceptListAddressType(), address_with_type.GetAddress());
829 }
830
clear_filter_accept_listle_impl831 void clear_filter_accept_list() {
832 connect_list.clear();
833 register_with_address_manager();
834 le_address_manager_->ClearFilterAcceptList();
835 }
836
add_device_to_resolving_listle_impl837 void add_device_to_resolving_list(
838 AddressWithType address_with_type,
839 const std::array<uint8_t, 16>& peer_irk,
840 const std::array<uint8_t, 16>& local_irk) {
841 register_with_address_manager();
842 le_address_manager_->AddDeviceToResolvingList(
843 address_with_type.ToPeerAddressType(), address_with_type.GetAddress(), peer_irk, local_irk);
844 if (le_acceptlist_callbacks_ != nullptr) {
845 le_acceptlist_callbacks_->OnResolvingListChange();
846 }
847 }
848
remove_device_from_resolving_listle_impl849 void remove_device_from_resolving_list(AddressWithType address_with_type) {
850 register_with_address_manager();
851 le_address_manager_->RemoveDeviceFromResolvingList(
852 address_with_type.ToPeerAddressType(), address_with_type.GetAddress());
853 if (le_acceptlist_callbacks_ != nullptr) {
854 le_acceptlist_callbacks_->OnResolvingListChange();
855 }
856 }
857
update_connectability_state_after_armedle_impl858 void update_connectability_state_after_armed(const ErrorCode& status) {
859 switch (connectability_state_) {
860 case ConnectabilityState::DISARMED:
861 case ConnectabilityState::ARMED:
862 case ConnectabilityState::DISARMING:
863 LOG_ERROR(
864 "Received connectability arm notification for unexpected state:%s status:%s",
865 connectability_state_machine_text(connectability_state_).c_str(),
866 ErrorCodeText(status).c_str());
867 break;
868 case ConnectabilityState::ARMING:
869 if (status != ErrorCode::SUCCESS) {
870 LOG_ERROR("Le connection state machine armed failed status:%s", ErrorCodeText(status).c_str());
871 }
872 connectability_state_ =
873 (status == ErrorCode::SUCCESS) ? ConnectabilityState::ARMED : ConnectabilityState::DISARMED;
874 LOG_INFO(
875 "Le connection state machine armed state:%s status:%s",
876 connectability_state_machine_text(connectability_state_).c_str(),
877 ErrorCodeText(status).c_str());
878 if (disarmed_while_arming_) {
879 disarmed_while_arming_ = false;
880 disarm_connectability();
881 }
882 }
883 }
884
on_extended_create_connectionle_impl885 void on_extended_create_connection(CommandStatusView status) {
886 ASSERT(status.IsValid());
887 ASSERT(status.GetCommandOpCode() == OpCode::LE_EXTENDED_CREATE_CONNECTION);
888 update_connectability_state_after_armed(status.GetStatus());
889 }
890
on_create_connectionle_impl891 void on_create_connection(CommandStatusView status) {
892 ASSERT(status.IsValid());
893 ASSERT(status.GetCommandOpCode() == OpCode::LE_CREATE_CONNECTION);
894 update_connectability_state_after_armed(status.GetStatus());
895 }
896
arm_connectabilityle_impl897 void arm_connectability() {
898 if (connectability_state_ != ConnectabilityState::DISARMED) {
899 LOG_ERROR(
900 "Attempting to re-arm le connection state machine in unexpected state:%s",
901 connectability_state_machine_text(connectability_state_).c_str());
902 return;
903 }
904 if (connect_list.empty()) {
905 LOG_INFO("Ignored request to re-arm le connection state machine when filter accept list is empty");
906 return;
907 }
908 AddressWithType empty(Address::kEmpty, AddressType::RANDOM_DEVICE_ADDRESS);
909 connectability_state_ = ConnectabilityState::ARMING;
910 connecting_le_ = connect_list;
911
912 uint16_t le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalSlow, kScanIntervalSlow);
913 uint16_t le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowSlow, kScanWindowSlow);
914 uint16_t le_scan_window_2m = le_scan_window;
915 uint16_t le_scan_window_coded = le_scan_window;
916 // If there is any direct connection in the connection list, use the fast parameter
917 if (!direct_connections_.empty()) {
918 le_scan_interval = os::GetSystemPropertyUint32(kPropertyConnScanIntervalFast, kScanIntervalFast);
919 le_scan_window = os::GetSystemPropertyUint32(kPropertyConnScanWindowFast, kScanWindowFast);
920 le_scan_window_2m = os::GetSystemPropertyUint32(kPropertyConnScanWindow2mFast, kScanWindow2mFast);
921 le_scan_window_coded = os::GetSystemPropertyUint32(kPropertyConnScanWindowCodedFast, kScanWindowCodedFast);
922 }
923 // Use specific parameters when in system suspend.
924 if (system_suspend_) {
925 le_scan_interval = kScanIntervalSystemSuspend;
926 le_scan_window = kScanWindowSystemSuspend;
927 le_scan_window_2m = le_scan_window;
928 le_scan_window_coded = le_scan_window;
929 }
930 InitiatorFilterPolicy initiator_filter_policy = InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST;
931 OwnAddressType own_address_type =
932 static_cast<OwnAddressType>(le_address_manager_->GetInitiatorAddress().GetAddressType());
933 uint16_t conn_interval_min = os::GetSystemPropertyUint32(kPropertyMinConnInterval, kConnIntervalMin);
934 uint16_t conn_interval_max = os::GetSystemPropertyUint32(kPropertyMaxConnInterval, kConnIntervalMax);
935 uint16_t conn_latency = os::GetSystemPropertyUint32(kPropertyConnLatency, kConnLatency);
936 uint16_t supervision_timeout = os::GetSystemPropertyUint32(kPropertyConnSupervisionTimeout, kSupervisionTimeout);
937 ASSERT(check_connection_parameters(conn_interval_min, conn_interval_max, conn_latency, supervision_timeout));
938
939 AddressWithType address_with_type = connection_peer_address_with_type_;
940 if (initiator_filter_policy == InitiatorFilterPolicy::USE_FILTER_ACCEPT_LIST) {
941 address_with_type = AddressWithType();
942 }
943
944 if (controller_->IsSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION)) {
945 bool only_init_1m_phy = os::GetSystemPropertyBool(kPropertyEnableBleOnlyInit1mPhy, kEnableBleOnlyInit1mPhy);
946
947 uint8_t initiating_phys = PHY_LE_1M;
948 std::vector<LeCreateConnPhyScanParameters> parameters = {};
949 LeCreateConnPhyScanParameters scan_parameters;
950 scan_parameters.scan_interval_ = le_scan_interval;
951 scan_parameters.scan_window_ = le_scan_window;
952 scan_parameters.conn_interval_min_ = conn_interval_min;
953 scan_parameters.conn_interval_max_ = conn_interval_max;
954 scan_parameters.conn_latency_ = conn_latency;
955 scan_parameters.supervision_timeout_ = supervision_timeout;
956 scan_parameters.min_ce_length_ = 0x00;
957 scan_parameters.max_ce_length_ = 0x00;
958 parameters.push_back(scan_parameters);
959
960 if (controller_->SupportsBle2mPhy() && !only_init_1m_phy) {
961 LeCreateConnPhyScanParameters scan_parameters_2m;
962 scan_parameters_2m.scan_interval_ = le_scan_interval;
963 scan_parameters_2m.scan_window_ = le_scan_window_2m;
964 scan_parameters_2m.conn_interval_min_ = conn_interval_min;
965 scan_parameters_2m.conn_interval_max_ = conn_interval_max;
966 scan_parameters_2m.conn_latency_ = conn_latency;
967 scan_parameters_2m.supervision_timeout_ = supervision_timeout;
968 scan_parameters_2m.min_ce_length_ = 0x00;
969 scan_parameters_2m.max_ce_length_ = 0x00;
970 parameters.push_back(scan_parameters_2m);
971 initiating_phys |= PHY_LE_2M;
972 }
973 if (controller_->SupportsBleCodedPhy() && !only_init_1m_phy) {
974 LeCreateConnPhyScanParameters scan_parameters_coded;
975 scan_parameters_coded.scan_interval_ = le_scan_interval;
976 scan_parameters_coded.scan_window_ = le_scan_window_coded;
977 scan_parameters_coded.conn_interval_min_ = conn_interval_min;
978 scan_parameters_coded.conn_interval_max_ = conn_interval_max;
979 scan_parameters_coded.conn_latency_ = conn_latency;
980 scan_parameters_coded.supervision_timeout_ = supervision_timeout;
981 scan_parameters_coded.min_ce_length_ = 0x00;
982 scan_parameters_coded.max_ce_length_ = 0x00;
983 parameters.push_back(scan_parameters_coded);
984 initiating_phys |= PHY_LE_CODED;
985 }
986
987 le_acl_connection_interface_->EnqueueCommand(
988 LeExtendedCreateConnectionBuilder::Create(
989 initiator_filter_policy,
990 own_address_type,
991 address_with_type.GetAddressType(),
992 address_with_type.GetAddress(),
993 initiating_phys,
994 parameters),
995 handler_->BindOnce(&le_impl::on_extended_create_connection, common::Unretained(this)));
996 } else {
997 le_acl_connection_interface_->EnqueueCommand(
998 LeCreateConnectionBuilder::Create(
999 le_scan_interval,
1000 le_scan_window,
1001 initiator_filter_policy,
1002 address_with_type.GetAddressType(),
1003 address_with_type.GetAddress(),
1004 own_address_type,
1005 conn_interval_min,
1006 conn_interval_max,
1007 conn_latency,
1008 supervision_timeout,
1009 0x00,
1010 0x00),
1011 handler_->BindOnce(&le_impl::on_create_connection, common::Unretained(this)));
1012 }
1013 }
1014
disarm_connectabilityle_impl1015 void disarm_connectability() {
1016
1017 auto argument_list = std::vector<std::pair<os::ArgumentType, int>>();
1018 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
1019 Address::kEmpty,
1020 os::LeConnectionOriginType::ORIGIN_UNSPECIFIED,
1021 os::LeConnectionType::CONNECTION_TYPE_LE_ACL,
1022 os::LeConnectionState::STATE_LE_ACL_CANCEL,
1023 argument_list);
1024
1025 switch (connectability_state_) {
1026 case ConnectabilityState::ARMED:
1027 LOG_INFO("Disarming LE connection state machine with create connection cancel");
1028 connectability_state_ = ConnectabilityState::DISARMING;
1029 le_acl_connection_interface_->EnqueueCommand(
1030 LeCreateConnectionCancelBuilder::Create(),
1031 handler_->BindOnce(&le_impl::on_create_connection_cancel_complete, common::Unretained(this)));
1032 break;
1033
1034 case ConnectabilityState::ARMING:
1035 LOG_INFO("Queueing cancel connect until after connection state machine is armed");
1036 disarmed_while_arming_ = true;
1037 break;
1038 case ConnectabilityState::DISARMING:
1039 case ConnectabilityState::DISARMED:
1040 LOG_ERROR(
1041 "Attempting to disarm le connection state machine in unexpected state:%s",
1042 connectability_state_machine_text(connectability_state_).c_str());
1043 break;
1044 }
1045 }
1046
create_le_connectionle_impl1047 void create_le_connection(AddressWithType address_with_type, bool add_to_connect_list, bool is_direct) {
1048 if (le_client_callbacks_ == nullptr) {
1049 LOG_ERROR("No callbacks to call");
1050 return;
1051 }
1052
1053 if (connections.alreadyConnected(address_with_type)) {
1054 LOG_INFO("Device already connected, return");
1055 return;
1056 }
1057
1058 // TODO: Configure default LE connection parameters?
1059 if (add_to_connect_list) {
1060 add_device_to_connect_list(address_with_type);
1061 if (is_direct) {
1062 direct_connections_.insert(address_with_type);
1063 if (create_connection_timeout_alarms_.find(address_with_type) == create_connection_timeout_alarms_.end()) {
1064 create_connection_timeout_alarms_.emplace(
1065 std::piecewise_construct,
1066 std::forward_as_tuple(address_with_type.GetAddress(), address_with_type.GetAddressType()),
1067 std::forward_as_tuple(handler_));
1068 uint32_t connection_timeout =
1069 os::GetSystemPropertyUint32(kPropertyDirectConnTimeout, kCreateConnectionTimeoutMs);
1070 create_connection_timeout_alarms_.at(address_with_type)
1071 .Schedule(
1072 common::BindOnce(&le_impl::on_create_connection_timeout, common::Unretained(this), address_with_type),
1073 std::chrono::milliseconds(connection_timeout));
1074 }
1075 }
1076 }
1077
1078 if (!address_manager_registered) {
1079 auto policy = le_address_manager_->Register(this);
1080 address_manager_registered = true;
1081
1082 // Pause connection, wait for set random address complete
1083 if (policy == LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS ||
1084 policy == LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS) {
1085 pause_connection = true;
1086 }
1087 }
1088
1089 if (pause_connection) {
1090 arm_on_resume_ = true;
1091 return;
1092 }
1093
1094 switch (connectability_state_) {
1095 case ConnectabilityState::ARMED:
1096 case ConnectabilityState::ARMING:
1097 // Ignored, if we add new device to the filter accept list, create connection command will be sent by OnResume.
1098 LOG_DEBUG(
1099 "Deferred until filter accept list updated create connection state %s",
1100 connectability_state_machine_text(connectability_state_).c_str());
1101 break;
1102 default:
1103 // If we added to filter accept list then the arming of the le state machine
1104 // must wait until the filter accept list command as completed
1105 if (add_to_connect_list) {
1106 arm_on_resume_ = true;
1107 LOG_DEBUG("Deferred until filter accept list has completed");
1108 } else {
1109 handler_->CallOn(this, &le_impl::arm_connectability);
1110 }
1111 break;
1112 }
1113 }
1114
on_create_connection_timeoutle_impl1115 void on_create_connection_timeout(AddressWithType address_with_type) {
1116 LOG_INFO("on_create_connection_timeout, address: %s",
1117 ADDRESS_TO_LOGGABLE_CSTR(address_with_type));
1118 if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
1119 create_connection_timeout_alarms_.at(address_with_type).Cancel();
1120 create_connection_timeout_alarms_.erase(address_with_type);
1121 auto argument_list = std::vector<std::pair<os::ArgumentType, int>>();
1122 argument_list.push_back(std::make_pair(
1123 os::ArgumentType::ACL_STATUS_CODE,
1124 static_cast<int>(android::bluetooth::hci::StatusEnum::STATUS_CONNECTION_TOUT)));
1125 bluetooth::os::LogMetricBluetoothLEConnectionMetricEvent(
1126 address_with_type.GetAddress(),
1127 android::bluetooth::le::LeConnectionOriginType::ORIGIN_NATIVE,
1128 android::bluetooth::le::LeConnectionType::CONNECTION_TYPE_LE_ACL,
1129 android::bluetooth::le::LeConnectionState::STATE_LE_ACL_TIMEOUT,
1130 argument_list);
1131
1132 if (background_connections_.find(address_with_type) != background_connections_.end()) {
1133 direct_connections_.erase(address_with_type);
1134 disarm_connectability();
1135 } else {
1136 cancel_connect(address_with_type);
1137 }
1138 le_client_handler_->Post(common::BindOnce(
1139 &LeConnectionCallbacks::OnLeConnectFail,
1140 common::Unretained(le_client_callbacks_),
1141 address_with_type,
1142 ErrorCode::CONNECTION_ACCEPT_TIMEOUT));
1143 }
1144 }
1145
cancel_connectle_impl1146 void cancel_connect(AddressWithType address_with_type) {
1147 // Remove any alarms for this peer, if any
1148 if (create_connection_timeout_alarms_.find(address_with_type) != create_connection_timeout_alarms_.end()) {
1149 create_connection_timeout_alarms_.at(address_with_type).Cancel();
1150 create_connection_timeout_alarms_.erase(address_with_type);
1151 }
1152 // the connection will be canceled by LeAddressManager.OnPause()
1153 remove_device_from_connect_list(address_with_type);
1154 }
1155
set_le_suggested_default_data_parametersle_impl1156 void set_le_suggested_default_data_parameters(uint16_t length, uint16_t time) {
1157 auto packet = LeWriteSuggestedDefaultDataLengthBuilder::Create(length, time);
1158 le_acl_connection_interface_->EnqueueCommand(
1159 std::move(packet), handler_->BindOnce([](CommandCompleteView complete) {}));
1160 }
1161
LeSetDefaultSubratele_impl1162 void LeSetDefaultSubrate(
1163 uint16_t subrate_min, uint16_t subrate_max, uint16_t max_latency, uint16_t cont_num, uint16_t sup_tout) {
1164 le_acl_connection_interface_->EnqueueCommand(
1165 LeSetDefaultSubrateBuilder::Create(subrate_min, subrate_max, max_latency, cont_num, sup_tout),
1166 handler_->BindOnce([](CommandCompleteView complete) {
1167 auto complete_view = LeSetDefaultSubrateCompleteView::Create(complete);
1168 ASSERT(complete_view.IsValid());
1169 ErrorCode status = complete_view.GetStatus();
1170 ASSERT_LOG(status == ErrorCode::SUCCESS, "Status 0x%02hhx, %s", status, ErrorCodeText(status).c_str());
1171 }));
1172 }
1173
clear_resolving_listle_impl1174 void clear_resolving_list() {
1175 le_address_manager_->ClearResolvingList();
1176 }
1177
set_privacy_policy_for_initiator_addressle_impl1178 void set_privacy_policy_for_initiator_address(
1179 LeAddressManager::AddressPolicy address_policy,
1180 AddressWithType fixed_address,
1181 crypto_toolbox::Octet16 rotation_irk,
1182 std::chrono::milliseconds minimum_rotation_time,
1183 std::chrono::milliseconds maximum_rotation_time) {
1184 le_address_manager_->SetPrivacyPolicyForInitiatorAddress(
1185 address_policy,
1186 fixed_address,
1187 rotation_irk,
1188 controller_->SupportsBlePrivacy() && os::GetSystemPropertyBool(kPropertyEnableBlePrivacy, kEnableBlePrivacy),
1189 minimum_rotation_time,
1190 maximum_rotation_time);
1191 }
1192
1193 // TODO(jpawlowski): remove once we have config file abstraction in cert tests
set_privacy_policy_for_initiator_address_for_testle_impl1194 void set_privacy_policy_for_initiator_address_for_test(
1195 LeAddressManager::AddressPolicy address_policy,
1196 AddressWithType fixed_address,
1197 crypto_toolbox::Octet16 rotation_irk,
1198 std::chrono::milliseconds minimum_rotation_time,
1199 std::chrono::milliseconds maximum_rotation_time) {
1200 le_address_manager_->SetPrivacyPolicyForInitiatorAddressForTest(
1201 address_policy, fixed_address, rotation_irk, minimum_rotation_time, maximum_rotation_time);
1202 }
1203
handle_register_le_callbacksle_impl1204 void handle_register_le_callbacks(LeConnectionCallbacks* callbacks, os::Handler* handler) {
1205 ASSERT(le_client_callbacks_ == nullptr);
1206 ASSERT(le_client_handler_ == nullptr);
1207 le_client_callbacks_ = callbacks;
1208 le_client_handler_ = handler;
1209 }
1210
handle_register_le_acceptlist_callbacksle_impl1211 void handle_register_le_acceptlist_callbacks(LeAcceptlistCallbacks* callbacks) {
1212 ASSERT(le_acceptlist_callbacks_ == nullptr);
1213 le_acceptlist_callbacks_ = callbacks;
1214 }
1215
handle_unregister_le_callbacksle_impl1216 void handle_unregister_le_callbacks(LeConnectionCallbacks* callbacks, std::promise<void> promise) {
1217 ASSERT_LOG(le_client_callbacks_ == callbacks, "Registered le callback entity is different then unregister request");
1218 le_client_callbacks_ = nullptr;
1219 le_client_handler_ = nullptr;
1220 promise.set_value();
1221 }
1222
handle_unregister_le_acceptlist_callbacksle_impl1223 void handle_unregister_le_acceptlist_callbacks(
1224 LeAcceptlistCallbacks* callbacks, std::promise<void> promise) {
1225 ASSERT_LOG(
1226 le_acceptlist_callbacks_ == callbacks,
1227 "Registered le callback entity is different then unregister request");
1228 le_acceptlist_callbacks_ = nullptr;
1229 promise.set_value();
1230 }
1231
check_connection_parametersle_impl1232 bool check_connection_parameters(
1233 uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout) {
1234 if (conn_interval_min < 0x0006 || conn_interval_min > 0x0C80 || conn_interval_max < 0x0006 ||
1235 conn_interval_max > 0x0C80 || conn_latency > 0x01F3 || supervision_timeout < 0x000A ||
1236 supervision_timeout > 0x0C80) {
1237 LOG_ERROR("Invalid parameter");
1238 return false;
1239 }
1240
1241 // The Maximum interval in milliseconds will be conn_interval_max * 1.25 ms
1242 // The Timeout in milliseconds will be expected_supervision_timeout * 10 ms
1243 // The Timeout in milliseconds shall be larger than (1 + Latency) * Interval_Max * 2, where Interval_Max is given in
1244 // milliseconds.
1245 uint32_t supervision_timeout_min = (uint32_t)(1 + conn_latency) * conn_interval_max * 2 + 1;
1246 if (supervision_timeout * 8 < supervision_timeout_min || conn_interval_max < conn_interval_min) {
1247 LOG_ERROR("Invalid parameter");
1248 return false;
1249 }
1250
1251 return true;
1252 }
1253
add_device_to_background_connection_listle_impl1254 void add_device_to_background_connection_list(AddressWithType address_with_type) {
1255 background_connections_.insert(address_with_type);
1256 }
1257
remove_device_from_background_connection_listle_impl1258 void remove_device_from_background_connection_list(AddressWithType address_with_type) {
1259 background_connections_.erase(address_with_type);
1260 }
1261
is_on_background_connection_listle_impl1262 void is_on_background_connection_list(AddressWithType address_with_type, std::promise<bool> promise) {
1263 promise.set_value(background_connections_.find(address_with_type) != background_connections_.end());
1264 }
1265
OnPausele_impl1266 void OnPause() override { // bluetooth::hci::LeAddressManagerCallback
1267 if (!address_manager_registered) {
1268 LOG_WARN("Unregistered!");
1269 return;
1270 }
1271 pause_connection = true;
1272 if (connectability_state_ == ConnectabilityState::DISARMED) {
1273 le_address_manager_->AckPause(this);
1274 return;
1275 }
1276 arm_on_resume_ = !connecting_le_.empty();
1277 disarm_connectability();
1278 }
1279
OnResumele_impl1280 void OnResume() override { // bluetooth::hci::LeAddressManagerCallback
1281 if (!address_manager_registered) {
1282 LOG_WARN("Unregistered!");
1283 return;
1284 }
1285 pause_connection = false;
1286 if (arm_on_resume_) {
1287 arm_connectability();
1288 }
1289 arm_on_resume_ = false;
1290 le_address_manager_->AckResume(this);
1291 check_for_unregister();
1292 }
1293
on_create_connection_cancel_completele_impl1294 void on_create_connection_cancel_complete(CommandCompleteView view) {
1295 auto complete_view = LeCreateConnectionCancelCompleteView::Create(view);
1296 ASSERT(complete_view.IsValid());
1297 if (complete_view.GetStatus() != ErrorCode::SUCCESS) {
1298 auto status = complete_view.GetStatus();
1299 std::string error_code = ErrorCodeText(status);
1300 LOG_WARN("Received on_create_connection_cancel_complete with error code %s", error_code.c_str());
1301 if (pause_connection) {
1302 LOG_WARN("AckPause");
1303 le_address_manager_->AckPause(this);
1304 return;
1305 }
1306 }
1307 if (connectability_state_ != ConnectabilityState::DISARMING) {
1308 LOG_ERROR(
1309 "Attempting to disarm le connection state machine in unexpected state:%s",
1310 connectability_state_machine_text(connectability_state_).c_str());
1311 }
1312 }
1313
register_with_address_managerle_impl1314 void register_with_address_manager() {
1315 if (!address_manager_registered) {
1316 le_address_manager_->Register(this);
1317 address_manager_registered = true;
1318 pause_connection = true;
1319 }
1320 }
1321
check_for_unregisterle_impl1322 void check_for_unregister() {
1323 if (connections.is_empty() && connecting_le_.empty() && address_manager_registered && ready_to_unregister) {
1324 le_address_manager_->Unregister(this);
1325 address_manager_registered = false;
1326 pause_connection = false;
1327 ready_to_unregister = false;
1328 }
1329 }
1330
set_system_suspend_statele_impl1331 void set_system_suspend_state(bool suspended) {
1332 system_suspend_ = suspended;
1333 }
1334
1335 HciLayer* hci_layer_ = nullptr;
1336 Controller* controller_ = nullptr;
1337 os::Handler* handler_ = nullptr;
1338 RoundRobinScheduler* round_robin_scheduler_ = nullptr;
1339 LeAddressManager* le_address_manager_ = nullptr;
1340 LeAclConnectionInterface* le_acl_connection_interface_ = nullptr;
1341 LeConnectionCallbacks* le_client_callbacks_ = nullptr;
1342 os::Handler* le_client_handler_ = nullptr;
1343 LeAcceptlistCallbacks* le_acceptlist_callbacks_ = nullptr;
1344 std::unordered_set<AddressWithType> connecting_le_{};
1345 bool arm_on_resume_{};
1346 std::unordered_set<AddressWithType> direct_connections_{};
1347 // Set of devices that will not be removed from connect list after direct connect timeout
1348 std::unordered_set<AddressWithType> background_connections_;
1349 std::unordered_set<AddressWithType> connect_list;
1350 AddressWithType connection_peer_address_with_type_; // Direct peer address UNSUPPORTEDD
1351 bool address_manager_registered = false;
1352 bool ready_to_unregister = false;
1353 bool pause_connection = false;
1354 bool disarmed_while_arming_ = false;
1355 bool system_suspend_ = false;
1356 ConnectabilityState connectability_state_{ConnectabilityState::DISARMED};
1357 std::map<AddressWithType, os::Alarm> create_connection_timeout_alarms_{};
1358 };
1359
1360 } // namespace acl_manager
1361 } // namespace hci
1362 } // namespace bluetooth
1363