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 #include "main/shim/acl.h"
18
19 #include <base/location.h>
20 #include <base/strings/stringprintf.h>
21 #include <bluetooth/log.h>
22 #include <time.h>
23
24 #include <chrono>
25 #include <cstdint>
26 #include <functional>
27 #include <future>
28 #include <map>
29 #include <memory>
30 #include <optional>
31 #include <string>
32 #include <unordered_set>
33
34 #include "common/bind.h"
35 #include "common/interfaces/ILoggable.h"
36 #include "common/strings.h"
37 #include "common/sync_map_count.h"
38 #include "hci/acl_manager.h"
39 #include "hci/acl_manager/acl_connection.h"
40 #include "hci/acl_manager/classic_acl_connection.h"
41 #include "hci/acl_manager/connection_management_callbacks.h"
42 #include "hci/acl_manager/le_acl_connection.h"
43 #include "hci/acl_manager/le_connection_management_callbacks.h"
44 #include "hci/address.h"
45 #include "hci/address_with_type.h"
46 #include "hci/class_of_device.h"
47 #include "hci/controller_interface.h"
48 #include "internal_include/bt_target.h"
49 #include "main/shim/dumpsys.h"
50 #include "main/shim/entry.h"
51 #include "main/shim/helpers.h"
52 #include "main/shim/stack.h"
53 #include "os/handler.h"
54 #include "osi/include/allocator.h"
55 #include "stack/acl/acl.h"
56 #include "stack/btm/btm_int_types.h"
57 #include "stack/btm/btm_sec_cb.h"
58 #include "stack/include/bt_hdr.h"
59 #include "stack/include/btm_log_history.h"
60 #include "stack/include/l2c_api.h"
61 #include "stack/include/main_thread.h"
62 #include "types/ble_address_with_type.h"
63 #include "types/raw_address.h"
64
65 extern tBTM_CB btm_cb;
66
67 using namespace bluetooth;
68
69 class ConnectAddressWithType : public bluetooth::common::IRedactableLoggable {
70 public:
ConnectAddressWithType(hci::AddressWithType address_with_type)71 explicit ConnectAddressWithType(hci::AddressWithType address_with_type)
72 : address_(address_with_type.GetAddress()),
73 type_(address_with_type.ToFilterAcceptListAddressType()) {}
74
75 // TODO: remove this method
ToString() const76 std::string const ToString() const {
77 std::stringstream ss;
78 ss << address_.ToString() << "[" << FilterAcceptListAddressTypeText(type_)
79 << "]";
80 return ss.str();
81 }
82
ToStringForLogging() const83 std::string ToStringForLogging() const override {
84 return ToString();
85 }
ToRedactedStringForLogging() const86 std::string ToRedactedStringForLogging() const override {
87 std::stringstream ss;
88 ss << address_.ToRedactedStringForLogging() << "["
89 << FilterAcceptListAddressTypeText(type_) << "]";
90 return ss.str();
91 }
operator ==(const ConnectAddressWithType & rhs) const92 bool operator==(const ConnectAddressWithType& rhs) const {
93 return address_ == rhs.address_ && type_ == rhs.type_;
94 }
95
96 private:
97 friend std::hash<ConnectAddressWithType>;
98 hci::Address address_;
99 hci::FilterAcceptListAddressType type_;
100 };
101
102 namespace std {
103 template <>
104 struct hash<ConnectAddressWithType> {
operator ()std::hash105 std::size_t operator()(const ConnectAddressWithType& val) const {
106 static_assert(sizeof(uint64_t) >=
107 (bluetooth::hci::Address::kLength +
108 sizeof(bluetooth::hci::FilterAcceptListAddressType)));
109 uint64_t int_addr = 0;
110 memcpy(reinterpret_cast<uint8_t*>(&int_addr), val.address_.data(),
111 bluetooth::hci::Address::kLength);
112 memcpy(reinterpret_cast<uint8_t*>(&int_addr) +
113 bluetooth::hci::Address::kLength,
114 &val.type_, sizeof(bluetooth::hci::FilterAcceptListAddressType));
115 return std::hash<uint64_t>{}(int_addr);
116 }
117 };
118 } // namespace std
119
120 namespace fmt {
121 template <>
122 struct formatter<ConnectAddressWithType> : formatter<std::string> {
123 template <class Context>
formatfmt::formatter124 typename Context::iterator format(const ConnectAddressWithType& address,
125 Context& ctx) const {
126 std::string repr = bluetooth::os::should_log_be_redacted()
127 ? address.ToRedactedStringForLogging()
128 : address.ToStringForLogging();
129 return fmt::formatter<std::string>::format(repr, ctx);
130 }
131 };
132 } // namespace fmt
133
134 namespace {
135
136 constexpr uint32_t kRunicBjarkan = 0x0016D2;
137 constexpr uint32_t kRunicHagall = 0x0016BC;
138
139 using HciHandle = uint16_t;
140 using PageNumber = uint8_t;
141
142 using CreationTime = std::chrono::time_point<std::chrono::system_clock>;
143 using TeardownTime = std::chrono::time_point<std::chrono::system_clock>;
144
145 constexpr char kBtmLogTag[] = "ACL";
146
147 using SendDataUpwards = void (*const)(BT_HDR*);
148 using OnDisconnect = std::function<void(HciHandle, hci::ErrorCode reason)>;
149
150 constexpr char kConnectionDescriptorTimeFormat[] = "%Y-%m-%d %H:%M:%S";
151
152 constexpr unsigned MillisPerSecond = 1000;
EpochMillisToString(long long time_ms)153 std::string EpochMillisToString(long long time_ms) {
154 time_t time_sec = time_ms / MillisPerSecond;
155 struct tm tm;
156 localtime_r(&time_sec, &tm);
157 std::string s = common::StringFormatTime(kConnectionDescriptorTimeFormat, tm);
158 return base::StringPrintf(
159 "%s.%03u", s.c_str(),
160 static_cast<unsigned int>(time_ms % MillisPerSecond));
161 }
162
IsRpa(const hci::AddressWithType address_with_type)163 inline bool IsRpa(const hci::AddressWithType address_with_type) {
164 return address_with_type.GetAddressType() ==
165 hci::AddressType::RANDOM_DEVICE_ADDRESS &&
166 ((address_with_type.GetAddress().address.data()[5] & 0xc0) == 0x40);
167 }
168
169 class ShadowAcceptlist {
170 public:
ShadowAcceptlist(uint8_t max_acceptlist_size)171 ShadowAcceptlist(uint8_t max_acceptlist_size)
172 : max_acceptlist_size_(max_acceptlist_size) {}
173
Add(const hci::AddressWithType & address_with_type)174 bool Add(const hci::AddressWithType& address_with_type) {
175 if (acceptlist_set_.size() == max_acceptlist_size_) {
176 log::error("Acceptlist is full size:{}", acceptlist_set_.size());
177 return false;
178 }
179 if (!acceptlist_set_.insert(ConnectAddressWithType(address_with_type))
180 .second) {
181 log::warn("Attempted to add duplicate le address to acceptlist:{}",
182 address_with_type);
183 }
184 return true;
185 }
186
Remove(const hci::AddressWithType & address_with_type)187 bool Remove(const hci::AddressWithType& address_with_type) {
188 auto iter = acceptlist_set_.find(ConnectAddressWithType(address_with_type));
189 if (iter == acceptlist_set_.end()) {
190 log::warn("Unknown device being removed from acceptlist:{}",
191 address_with_type);
192 return false;
193 }
194 acceptlist_set_.erase(ConnectAddressWithType(*iter));
195 return true;
196 }
197
GetCopy() const198 std::unordered_set<ConnectAddressWithType> GetCopy() const {
199 return acceptlist_set_;
200 }
201
IsFull() const202 bool IsFull() const {
203 return acceptlist_set_.size() == static_cast<size_t>(max_acceptlist_size_);
204 }
205
Clear()206 void Clear() { acceptlist_set_.clear(); }
207
GetMaxSize() const208 uint8_t GetMaxSize() const { return max_acceptlist_size_; }
209
210 private:
211 uint8_t max_acceptlist_size_{0};
212 std::unordered_set<ConnectAddressWithType> acceptlist_set_;
213 };
214
215 class ShadowAddressResolutionList {
216 public:
ShadowAddressResolutionList(uint8_t max_address_resolution_size)217 ShadowAddressResolutionList(uint8_t max_address_resolution_size)
218 : max_address_resolution_size_(max_address_resolution_size) {}
219
Add(const hci::AddressWithType & address_with_type)220 bool Add(const hci::AddressWithType& address_with_type) {
221 if (address_resolution_set_.size() == max_address_resolution_size_) {
222 log::error("Address Resolution is full size:{}",
223 address_resolution_set_.size());
224 return false;
225 }
226 if (!address_resolution_set_.insert(address_with_type).second) {
227 log::warn(
228 "Attempted to add duplicate le address to address_resolution:{}",
229 address_with_type);
230 }
231 return true;
232 }
233
Remove(const hci::AddressWithType & address_with_type)234 bool Remove(const hci::AddressWithType& address_with_type) {
235 auto iter = address_resolution_set_.find(address_with_type);
236 if (iter == address_resolution_set_.end()) {
237 log::warn("Unknown device being removed from address_resolution:{}",
238 address_with_type);
239 return false;
240 }
241 address_resolution_set_.erase(iter);
242 return true;
243 }
244
GetCopy() const245 std::unordered_set<hci::AddressWithType> GetCopy() const {
246 return address_resolution_set_;
247 }
248
IsFull() const249 bool IsFull() const {
250 return address_resolution_set_.size() ==
251 static_cast<size_t>(max_address_resolution_size_);
252 }
253
Size() const254 size_t Size() const { return address_resolution_set_.size(); }
255
Clear()256 void Clear() { address_resolution_set_.clear(); }
257
GetMaxSize() const258 uint8_t GetMaxSize() const { return max_address_resolution_size_; }
259
260 private:
261 uint8_t max_address_resolution_size_{0};
262 std::unordered_set<hci::AddressWithType> address_resolution_set_;
263 };
264
265 struct ConnectionDescriptor {
266 CreationTime creation_time_;
267 TeardownTime teardown_time_;
268 uint16_t handle_;
269 bool is_locally_initiated_;
270 hci::ErrorCode disconnect_reason_;
ConnectionDescriptor__anon7fa7f9c60111::ConnectionDescriptor271 ConnectionDescriptor(CreationTime creation_time, TeardownTime teardown_time,
272 uint16_t handle, bool is_locally_initiated,
273 hci::ErrorCode disconnect_reason)
274 : creation_time_(creation_time),
275 teardown_time_(teardown_time),
276 handle_(handle),
277 is_locally_initiated_(is_locally_initiated),
278 disconnect_reason_(disconnect_reason) {}
279 virtual std::string GetPrivateRemoteAddress() const = 0;
~ConnectionDescriptor__anon7fa7f9c60111::ConnectionDescriptor280 virtual ~ConnectionDescriptor() {}
ToString__anon7fa7f9c60111::ConnectionDescriptor281 std::string ToString() const {
282 return base::StringPrintf(
283 "peer:%s handle:0x%04x is_locally_initiated:%s"
284 " creation_time:%s teardown_time:%s disconnect_reason:%s",
285 GetPrivateRemoteAddress().c_str(), handle_,
286 is_locally_initiated_ ? "true" : "false",
287 common::StringFormatTimeWithMilliseconds(
288 kConnectionDescriptorTimeFormat, creation_time_)
289 .c_str(),
290 common::StringFormatTimeWithMilliseconds(
291 kConnectionDescriptorTimeFormat, teardown_time_)
292 .c_str(),
293 hci::ErrorCodeText(disconnect_reason_).c_str());
294 }
295 };
296
297 struct ClassicConnectionDescriptor : public ConnectionDescriptor {
298 const hci::Address remote_address_;
ClassicConnectionDescriptor__anon7fa7f9c60111::ClassicConnectionDescriptor299 ClassicConnectionDescriptor(const hci::Address& remote_address,
300 CreationTime creation_time,
301 TeardownTime teardown_time, uint16_t handle,
302 bool is_locally_initiated,
303 hci::ErrorCode disconnect_reason)
304 : ConnectionDescriptor(creation_time, teardown_time, handle,
305 is_locally_initiated, disconnect_reason),
306 remote_address_(remote_address) {}
GetPrivateRemoteAddress__anon7fa7f9c60111::ClassicConnectionDescriptor307 virtual std::string GetPrivateRemoteAddress() const {
308 return ADDRESS_TO_LOGGABLE_CSTR(remote_address_);
309 }
310 };
311
312 struct LeConnectionDescriptor : public ConnectionDescriptor {
313 const hci::AddressWithType remote_address_with_type_;
LeConnectionDescriptor__anon7fa7f9c60111::LeConnectionDescriptor314 LeConnectionDescriptor(hci::AddressWithType& remote_address_with_type,
315 CreationTime creation_time, TeardownTime teardown_time,
316 uint16_t handle, bool is_locally_initiated,
317 hci::ErrorCode disconnect_reason)
318 : ConnectionDescriptor(creation_time, teardown_time, handle,
319 is_locally_initiated, disconnect_reason),
320 remote_address_with_type_(remote_address_with_type) {}
GetPrivateRemoteAddress__anon7fa7f9c60111::LeConnectionDescriptor321 std::string GetPrivateRemoteAddress() const {
322 return ADDRESS_TO_LOGGABLE_CSTR(remote_address_with_type_);
323 }
324 };
325
326 template <typename T>
327 class FixedQueue {
328 public:
FixedQueue(size_t max_size)329 explicit FixedQueue(size_t max_size) : max_size_(max_size) {}
Push(T element)330 void Push(T element) {
331 if (queue_.size() == max_size_) {
332 queue_.pop_front();
333 }
334 queue_.push_back(std::move(element));
335 }
336
ReadElementsAsString() const337 std::vector<std::string> ReadElementsAsString() const {
338 std::vector<std::string> vector;
339 for (auto& entry : queue_) {
340 vector.push_back(entry->ToString());
341 }
342 return vector;
343 }
344
345 private:
346 size_t max_size_{1};
347 std::deque<T> queue_;
348 };
349
350 constexpr size_t kConnectionHistorySize = 40;
351
LowByte(uint16_t val)352 inline uint8_t LowByte(uint16_t val) { return val & 0xff; }
HighByte(uint16_t val)353 inline uint8_t HighByte(uint16_t val) { return val >> 8; }
354
ValidateAclInterface(const shim::legacy::acl_interface_t & acl_interface)355 void ValidateAclInterface(const shim::legacy::acl_interface_t& acl_interface) {
356 log::assert_that(acl_interface.on_send_data_upwards != nullptr,
357 "Must provide to receive data on acl links");
358 log::assert_that(acl_interface.on_packets_completed != nullptr,
359 "Must provide to receive completed packet indication");
360
361 log::assert_that(acl_interface.connection.classic.on_connected != nullptr,
362 "Must provide to respond to successful classic connections");
363 log::assert_that(
364 acl_interface.connection.classic.on_failed != nullptr,
365 "Must provide to respond when classic connection attempts fail");
366 log::assert_that(
367 acl_interface.connection.classic.on_disconnected != nullptr,
368 "Must provide to respond when active classic connection disconnects");
369
370 log::assert_that(acl_interface.connection.le.on_connected != nullptr,
371 "Must provide to respond to successful le connections");
372 log::assert_that(acl_interface.connection.le.on_failed != nullptr,
373 "Must provide to respond when le connection attempts fail");
374 log::assert_that(
375 acl_interface.connection.le.on_disconnected != nullptr,
376 "Must provide to respond when active le connection disconnects");
377 }
378
379 } // namespace
380
381 #define TRY_POSTING_ON_MAIN(cb, ...) \
382 do { \
383 if (cb == nullptr) { \
384 log::warn("Dropping ACL event with no callback"); \
385 } else { \
386 do_in_main_thread(FROM_HERE, base::BindOnce(cb, ##__VA_ARGS__)); \
387 } \
388 } while (0)
389
390 constexpr HciHandle kInvalidHciHandle = 0xffff;
391
392 class ShimAclConnection {
393 public:
ShimAclConnection(const HciHandle handle,SendDataUpwards send_data_upwards,os::Handler * handler,hci::acl_manager::AclConnection::QueueUpEnd * queue_up_end,CreationTime creation_time)394 ShimAclConnection(const HciHandle handle, SendDataUpwards send_data_upwards,
395 os::Handler* handler,
396 hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end,
397 CreationTime creation_time)
398 : handle_(handle),
399 handler_(handler),
400 send_data_upwards_(send_data_upwards),
401 queue_up_end_(queue_up_end),
402 creation_time_(creation_time) {
403 queue_up_end_->RegisterDequeue(
404 handler_, common::Bind(&ShimAclConnection::data_ready_callback,
405 common::Unretained(this)));
406 }
407
~ShimAclConnection()408 virtual ~ShimAclConnection() {
409 if (!queue_.empty())
410 log::error(
411 "ACL cleaned up with non-empty queue handle:0x{:04x} "
412 "stranded_pkts:{}",
413 handle_, queue_.size());
414 log::assert_that(is_disconnected_,
415 "Shim Acl was not properly disconnected handle:0x{:04x}",
416 handle_);
417 }
418
EnqueuePacket(std::unique_ptr<packet::RawBuilder> packet)419 void EnqueuePacket(std::unique_ptr<packet::RawBuilder> packet) {
420 // TODO Handle queue size exceeds some threshold
421 queue_.push(std::move(packet));
422 RegisterEnqueue();
423 }
424
handle_enqueue()425 std::unique_ptr<packet::BasePacketBuilder> handle_enqueue() {
426 auto packet = std::move(queue_.front());
427 queue_.pop();
428 if (queue_.empty()) {
429 UnregisterEnqueue();
430 }
431 return packet;
432 }
433
data_ready_callback()434 void data_ready_callback() {
435 auto packet = queue_up_end_->TryDequeue();
436 uint16_t length = packet->size();
437 std::vector<uint8_t> preamble;
438 preamble.push_back(LowByte(handle_));
439 preamble.push_back(HighByte(handle_));
440 preamble.push_back(LowByte(length));
441 preamble.push_back(HighByte(length));
442 BT_HDR* p_buf = MakeLegacyBtHdrPacket(std::move(packet), preamble);
443 log::assert_that(p_buf != nullptr,
444 "Unable to allocate BT_HDR legacy packet handle:{:04x}",
445 handle_);
446 if (send_data_upwards_ == nullptr) {
447 log::warn("Dropping ACL data with no callback");
448 osi_free(p_buf);
449 } else if (do_in_main_thread(FROM_HERE,
450 base::BindOnce(send_data_upwards_, p_buf)) !=
451 BT_STATUS_SUCCESS) {
452 osi_free(p_buf);
453 }
454 }
455
456 virtual void InitiateDisconnect(hci::DisconnectReason reason) = 0;
457 virtual bool IsLocallyInitiated() const = 0;
458
GetCreationTime() const459 CreationTime GetCreationTime() const { return creation_time_; }
Handle() const460 uint16_t Handle() const { return handle_; }
461
Shutdown()462 void Shutdown() {
463 Disconnect();
464 log::info("Shutdown and disconnect ACL connection handle:0x{:04x}",
465 handle_);
466 }
467
468 protected:
469 const uint16_t handle_{kInvalidHciHandle};
470 os::Handler* handler_;
471
UnregisterEnqueue()472 void UnregisterEnqueue() {
473 if (!is_enqueue_registered_) return;
474 is_enqueue_registered_ = false;
475 queue_up_end_->UnregisterEnqueue();
476 }
477
Disconnect()478 void Disconnect() {
479 if (is_disconnected_) {
480 log::error(
481 "Cannot disconnect ACL multiple times handle:{:04x} creation_time:{}",
482 handle_,
483 common::StringFormatTimeWithMilliseconds(
484 kConnectionDescriptorTimeFormat, creation_time_));
485 return;
486 }
487 is_disconnected_ = true;
488 UnregisterEnqueue();
489 queue_up_end_->UnregisterDequeue();
490 if (!queue_.empty())
491 log::warn(
492 "ACL disconnect with non-empty queue handle:{:04x} stranded_pkts::{}",
493 handle_, queue_.size());
494 }
495
496 virtual void ReadRemoteControllerInformation() = 0;
497
498 private:
499 SendDataUpwards send_data_upwards_;
500 hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end_;
501
502 std::queue<std::unique_ptr<packet::RawBuilder>> queue_;
503 bool is_enqueue_registered_{false};
504 bool is_disconnected_{false};
505 CreationTime creation_time_;
506
RegisterEnqueue()507 void RegisterEnqueue() {
508 log::assert_that(
509 !is_disconnected_,
510 "Unable to send data over disconnected channel handle:{:04x}", handle_);
511 if (is_enqueue_registered_) return;
512 is_enqueue_registered_ = true;
513 queue_up_end_->RegisterEnqueue(
514 handler_, common::Bind(&ShimAclConnection::handle_enqueue,
515 common::Unretained(this)));
516 }
517
518 virtual void RegisterCallbacks() = 0;
519 };
520
521 class ClassicShimAclConnection
522 : public ShimAclConnection,
523 public hci::acl_manager::ConnectionManagementCallbacks {
524 public:
ClassicShimAclConnection(SendDataUpwards send_data_upwards,OnDisconnect on_disconnect,const shim::legacy::acl_classic_link_interface_t & interface,os::Handler * handler,std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection,CreationTime creation_time)525 ClassicShimAclConnection(
526 SendDataUpwards send_data_upwards, OnDisconnect on_disconnect,
527 const shim::legacy::acl_classic_link_interface_t& interface,
528 os::Handler* handler,
529 std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection,
530 CreationTime creation_time)
531 : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler,
532 connection->GetAclQueueEnd(), creation_time),
533 on_disconnect_(on_disconnect),
534 interface_(interface),
535 connection_(std::move(connection)) {}
536
RegisterCallbacks()537 void RegisterCallbacks() override {
538 connection_->RegisterCallbacks(this, handler_);
539 }
540
ReadRemoteControllerInformation()541 void ReadRemoteControllerInformation() override {
542 connection_->ReadRemoteVersionInformation();
543 connection_->ReadRemoteSupportedFeatures();
544 }
545
OnConnectionPacketTypeChanged(uint16_t packet_type)546 void OnConnectionPacketTypeChanged(uint16_t packet_type) override {
547 TRY_POSTING_ON_MAIN(interface_.on_packet_type_changed, packet_type);
548 }
549
OnAuthenticationComplete(hci::ErrorCode hci_status)550 void OnAuthenticationComplete(hci::ErrorCode hci_status) override {
551 TRY_POSTING_ON_MAIN(interface_.on_authentication_complete, handle_,
552 ToLegacyHciErrorCode(hci_status));
553 }
554
OnEncryptionChange(hci::EncryptionEnabled enabled)555 void OnEncryptionChange(hci::EncryptionEnabled enabled) override {
556 bool is_enabled = (enabled == hci::EncryptionEnabled::ON ||
557 enabled == hci::EncryptionEnabled::BR_EDR_AES_CCM);
558 TRY_POSTING_ON_MAIN(interface_.on_encryption_change, is_enabled);
559 }
560
OnChangeConnectionLinkKeyComplete()561 void OnChangeConnectionLinkKeyComplete() override {
562 TRY_POSTING_ON_MAIN(interface_.on_change_connection_link_key_complete);
563 }
564
OnReadClockOffsetComplete(uint16_t)565 void OnReadClockOffsetComplete(uint16_t /* clock_offset */) override {
566 log::info("UNIMPLEMENTED");
567 }
568
OnModeChange(hci::ErrorCode status,hci::Mode current_mode,uint16_t interval)569 void OnModeChange(hci::ErrorCode status, hci::Mode current_mode,
570 uint16_t interval) override {
571 TRY_POSTING_ON_MAIN(interface_.on_mode_change, ToLegacyHciErrorCode(status),
572 handle_, ToLegacyHciMode(current_mode), interval);
573 }
574
OnSniffSubrating(hci::ErrorCode hci_status,uint16_t maximum_transmit_latency,uint16_t maximum_receive_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)575 void OnSniffSubrating(hci::ErrorCode hci_status,
576 uint16_t maximum_transmit_latency,
577 uint16_t maximum_receive_latency,
578 uint16_t minimum_remote_timeout,
579 uint16_t minimum_local_timeout) {
580 TRY_POSTING_ON_MAIN(interface_.on_sniff_subrating,
581 ToLegacyHciErrorCode(hci_status), handle_,
582 maximum_transmit_latency, maximum_receive_latency,
583 minimum_remote_timeout, minimum_local_timeout);
584 }
585
OnQosSetupComplete(hci::ServiceType,uint32_t,uint32_t,uint32_t,uint32_t)586 void OnQosSetupComplete(hci::ServiceType /* service_type */,
587 uint32_t /* token_rate */,
588 uint32_t /* peak_bandwidth */, uint32_t /* latency */,
589 uint32_t /* delay_variation */) override {
590 log::info("UNIMPLEMENTED");
591 }
592
OnFlowSpecificationComplete(hci::FlowDirection,hci::ServiceType,uint32_t,uint32_t,uint32_t,uint32_t)593 void OnFlowSpecificationComplete(hci::FlowDirection /* flow_direction */,
594 hci::ServiceType /* service_type */,
595 uint32_t /* token_rate */,
596 uint32_t /* token_bucket_size */,
597 uint32_t /* peak_bandwidth */,
598 uint32_t /* access_latency */) override {
599 log::info("UNIMPLEMENTED");
600 }
601
OnFlushOccurred()602 void OnFlushOccurred() override { log::info("UNIMPLEMENTED"); }
603
OnRoleDiscoveryComplete(hci::Role)604 void OnRoleDiscoveryComplete(hci::Role /* current_role */) override {
605 log::info("UNIMPLEMENTED");
606 }
607
OnReadLinkPolicySettingsComplete(uint16_t)608 void OnReadLinkPolicySettingsComplete(
609 uint16_t /* link_policy_settings */) override {
610 log::info("UNIMPLEMENTED");
611 }
612
OnReadAutomaticFlushTimeoutComplete(uint16_t)613 void OnReadAutomaticFlushTimeoutComplete(
614 uint16_t /* flush_timeout */) override {
615 log::info("UNIMPLEMENTED");
616 }
617
OnReadTransmitPowerLevelComplete(uint8_t)618 void OnReadTransmitPowerLevelComplete(
619 uint8_t /* transmit_power_level */) override {
620 log::info("UNIMPLEMENTED");
621 }
622
OnReadLinkSupervisionTimeoutComplete(uint16_t)623 void OnReadLinkSupervisionTimeoutComplete(
624 uint16_t /* link_supervision_timeout */) override {
625 log::info("UNIMPLEMENTED");
626 }
627
OnReadFailedContactCounterComplete(uint16_t)628 void OnReadFailedContactCounterComplete(
629 uint16_t /* failed_contact_counter */) override {
630 log::info("UNIMPLEMENTED");
631 }
632
OnReadLinkQualityComplete(uint8_t)633 void OnReadLinkQualityComplete(uint8_t /* link_quality */) override {
634 log::info("UNIMPLEMENTED");
635 }
636
OnReadAfhChannelMapComplete(hci::AfhMode,std::array<uint8_t,10>)637 void OnReadAfhChannelMapComplete(
638 hci::AfhMode /* afh_mode */,
639 std::array<uint8_t, 10> /* afh_channel_map */) override {
640 log::info("UNIMPLEMENTED");
641 }
642
OnReadRssiComplete(uint8_t)643 void OnReadRssiComplete(uint8_t /* rssi */) override {
644 log::info("UNIMPLEMENTED");
645 }
646
OnReadClockComplete(uint32_t,uint16_t)647 void OnReadClockComplete(uint32_t /* clock */,
648 uint16_t /* accuracy */) override {
649 log::info("UNIMPLEMENTED");
650 }
651
OnCentralLinkKeyComplete(hci::KeyFlag)652 void OnCentralLinkKeyComplete(hci::KeyFlag /* key_flag */) override {
653 log::info("UNIMPLEMENTED");
654 }
655
OnRoleChange(hci::ErrorCode hci_status,hci::Role new_role)656 void OnRoleChange(hci::ErrorCode hci_status, hci::Role new_role) override {
657 TRY_POSTING_ON_MAIN(
658 interface_.on_role_change, ToLegacyHciErrorCode(hci_status),
659 ToRawAddress(connection_->GetAddress()), ToLegacyRole(new_role));
660 BTM_LogHistory(kBtmLogTag, ToRawAddress(connection_->GetAddress()),
661 "Role change",
662 base::StringPrintf("classic New_role:%s status:%s",
663 hci::RoleText(new_role).c_str(),
664 hci::ErrorCodeText(hci_status).c_str()));
665 }
666
OnDisconnection(hci::ErrorCode reason)667 void OnDisconnection(hci::ErrorCode reason) override {
668 Disconnect();
669 on_disconnect_(handle_, reason);
670 }
671
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)672 void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,
673 uint8_t lmp_version,
674 uint16_t manufacturer_name,
675 uint16_t sub_version) override {
676 TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete,
677 ToLegacyHciErrorCode(hci_status), handle_, lmp_version,
678 manufacturer_name, sub_version);
679 }
680
OnReadRemoteSupportedFeaturesComplete(uint64_t features)681 void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override {
682 TRY_POSTING_ON_MAIN(interface_.on_read_remote_supported_features_complete,
683 handle_, features);
684
685 if (features & ((uint64_t(1) << 63))) {
686 connection_->ReadRemoteExtendedFeatures(1);
687 return;
688 }
689 log::debug("Device does not support extended features");
690 }
691
OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,uint8_t max_page_number,uint64_t features)692 void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,
693 uint8_t max_page_number,
694 uint64_t features) override {
695 TRY_POSTING_ON_MAIN(interface_.on_read_remote_extended_features_complete,
696 handle_, page_number, max_page_number, features);
697
698 // Supported features aliases to extended features page 0
699 if (page_number == 0 && !(features & ((uint64_t(1) << 63)))) {
700 log::debug("Device does not support extended features");
701 return;
702 }
703
704 if (max_page_number != 0 && page_number != max_page_number)
705 connection_->ReadRemoteExtendedFeatures(page_number + 1);
706 }
707
GetRemoteAddress() const708 hci::Address GetRemoteAddress() const { return connection_->GetAddress(); }
709
InitiateDisconnect(hci::DisconnectReason reason)710 void InitiateDisconnect(hci::DisconnectReason reason) override {
711 connection_->Disconnect(reason);
712 }
713
HoldMode(uint16_t max_interval,uint16_t min_interval)714 void HoldMode(uint16_t max_interval, uint16_t min_interval) {
715 log::assert_that(
716 connection_->HoldMode(max_interval, min_interval),
717 "assert failed: connection_->HoldMode(max_interval, min_interval)");
718 }
719
SniffMode(uint16_t max_interval,uint16_t min_interval,uint16_t attempt,uint16_t timeout)720 void SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt,
721 uint16_t timeout) {
722 log::assert_that(
723 connection_->SniffMode(max_interval, min_interval, attempt, timeout),
724 "assert failed: connection_->SniffMode(max_interval, min_interval, "
725 "attempt, timeout)");
726 }
727
ExitSniffMode()728 void ExitSniffMode() {
729 log::assert_that(connection_->ExitSniffMode(),
730 "assert failed: connection_->ExitSniffMode()");
731 }
732
SniffSubrating(uint16_t maximum_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)733 void SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout,
734 uint16_t minimum_local_timeout) {
735 log::assert_that(
736 connection_->SniffSubrating(maximum_latency, minimum_remote_timeout,
737 minimum_local_timeout),
738 "assert failed: connection_->SniffSubrating(maximum_latency, "
739 "minimum_remote_timeout, minimum_local_timeout)");
740 }
741
SetConnectionEncryption(hci::Enable is_encryption_enabled)742 void SetConnectionEncryption(hci::Enable is_encryption_enabled) {
743 log::assert_that(
744 connection_->SetConnectionEncryption(is_encryption_enabled),
745 "assert failed: "
746 "connection_->SetConnectionEncryption(is_encryption_enabled)");
747 }
748
IsLocallyInitiated() const749 bool IsLocallyInitiated() const override {
750 return connection_->locally_initiated_;
751 }
752
Flush()753 void Flush() { connection_->Flush(); }
754
755 private:
756 OnDisconnect on_disconnect_;
757 const shim::legacy::acl_classic_link_interface_t interface_;
758 std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection_;
759 };
760
761 class LeShimAclConnection
762 : public ShimAclConnection,
763 public hci::acl_manager::LeConnectionManagementCallbacks {
764 public:
LeShimAclConnection(SendDataUpwards send_data_upwards,OnDisconnect on_disconnect,const shim::legacy::acl_le_link_interface_t & interface,os::Handler * handler,std::unique_ptr<hci::acl_manager::LeAclConnection> connection,std::chrono::time_point<std::chrono::system_clock> creation_time)765 LeShimAclConnection(
766 SendDataUpwards send_data_upwards, OnDisconnect on_disconnect,
767 const shim::legacy::acl_le_link_interface_t& interface,
768 os::Handler* handler,
769 std::unique_ptr<hci::acl_manager::LeAclConnection> connection,
770 std::chrono::time_point<std::chrono::system_clock> creation_time)
771 : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler,
772 connection->GetAclQueueEnd(), creation_time),
773 on_disconnect_(on_disconnect),
774 interface_(interface),
775 connection_(std::move(connection)) {}
776
RegisterCallbacks()777 void RegisterCallbacks() override {
778 connection_->RegisterCallbacks(this, handler_);
779 }
780
LeSubrateRequest(uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t sup_tout)781 void LeSubrateRequest(uint16_t subrate_min, uint16_t subrate_max,
782 uint16_t max_latency, uint16_t cont_num,
783 uint16_t sup_tout) {
784 connection_->LeSubrateRequest(subrate_min, subrate_max, max_latency,
785 cont_num, sup_tout);
786 }
787
ReadRemoteControllerInformation()788 void ReadRemoteControllerInformation() override {
789 // TODO Issue LeReadRemoteFeatures Command
790 }
791
GetLocalAddressWithType()792 bluetooth::hci::AddressWithType GetLocalAddressWithType() {
793 return connection_->GetLocalAddress();
794 }
795
GetLocalOtaAddressWithType()796 bluetooth::hci::AddressWithType GetLocalOtaAddressWithType() {
797 return connection_->GetLocalOtaAddress();
798 }
799
GetPeerAddressWithType()800 bluetooth::hci::AddressWithType GetPeerAddressWithType() {
801 return connection_->GetPeerAddress();
802 }
803
GetPeerOtaAddressWithType()804 bluetooth::hci::AddressWithType GetPeerOtaAddressWithType() {
805 return connection_->GetPeerOtaAddress();
806 }
807
GetAdvertisingSetConnectedTo()808 std::optional<uint8_t> GetAdvertisingSetConnectedTo() {
809 return std::visit(
810 [](auto&& data) {
811 using T = std::decay_t<decltype(data)>;
812 if constexpr (std::is_same_v<T, hci::acl_manager::DataAsPeripheral>) {
813 return data.advertising_set_id;
814 } else {
815 return std::optional<uint8_t>{};
816 }
817 },
818 connection_->GetRoleSpecificData());
819 }
820
OnConnectionUpdate(hci::ErrorCode hci_status,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)821 void OnConnectionUpdate(hci::ErrorCode hci_status,
822 uint16_t connection_interval,
823 uint16_t connection_latency,
824 uint16_t supervision_timeout) {
825 TRY_POSTING_ON_MAIN(
826 interface_.on_connection_update, ToLegacyHciErrorCode(hci_status),
827 handle_, connection_interval, connection_latency, supervision_timeout);
828 }
OnDataLengthChange(uint16_t max_tx_octets,uint16_t max_tx_time,uint16_t max_rx_octets,uint16_t max_rx_time)829 void OnDataLengthChange(uint16_t max_tx_octets, uint16_t max_tx_time,
830 uint16_t max_rx_octets, uint16_t max_rx_time) {
831 TRY_POSTING_ON_MAIN(interface_.on_data_length_change, handle_,
832 max_tx_octets, max_tx_time, max_rx_octets, max_rx_time);
833 }
OnLeSubrateChange(hci::ErrorCode hci_status,uint16_t subrate_factor,uint16_t peripheral_latency,uint16_t continuation_number,uint16_t supervision_timeout)834 void OnLeSubrateChange(hci::ErrorCode hci_status, uint16_t subrate_factor,
835 uint16_t peripheral_latency,
836 uint16_t continuation_number,
837 uint16_t supervision_timeout) {
838 TRY_POSTING_ON_MAIN(interface_.on_le_subrate_change, handle_,
839 subrate_factor, peripheral_latency, continuation_number,
840 supervision_timeout, ToLegacyHciErrorCode(hci_status));
841 }
842
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)843 void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,
844 uint8_t lmp_version,
845 uint16_t manufacturer_name,
846 uint16_t sub_version) override {
847 TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete,
848 ToLegacyHciErrorCode(hci_status), handle_, lmp_version,
849 manufacturer_name, sub_version);
850 }
851
OnLeReadRemoteFeaturesComplete(hci::ErrorCode,uint64_t)852 void OnLeReadRemoteFeaturesComplete(hci::ErrorCode /* hci_status */,
853 uint64_t /* features */) {
854 // TODO
855 }
856
OnPhyUpdate(hci::ErrorCode hci_status,uint8_t tx_phy,uint8_t rx_phy)857 void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy,
858 uint8_t rx_phy) override {
859 TRY_POSTING_ON_MAIN(interface_.on_phy_update,
860 ToLegacyHciErrorCode(hci_status), handle_, tx_phy,
861 rx_phy);
862 }
863
OnDisconnection(hci::ErrorCode reason)864 void OnDisconnection(hci::ErrorCode reason) {
865 Disconnect();
866 on_disconnect_(handle_, reason);
867 }
868
GetRemoteAddressWithType() const869 hci::AddressWithType GetRemoteAddressWithType() const {
870 return connection_->GetRemoteAddress();
871 }
872
InitiateDisconnect(hci::DisconnectReason reason)873 void InitiateDisconnect(hci::DisconnectReason reason) override {
874 connection_->Disconnect(reason);
875 }
876
IsLocallyInitiated() const877 bool IsLocallyInitiated() const override {
878 return connection_->locally_initiated_;
879 }
880
IsInFilterAcceptList() const881 bool IsInFilterAcceptList() const {
882 return connection_->IsInFilterAcceptList();
883 }
884
UpdateConnectionParameters(uint16_t conn_int_min,uint16_t conn_int_max,uint16_t conn_latency,uint16_t conn_timeout,uint16_t min_ce_len,uint16_t max_ce_len)885 void UpdateConnectionParameters(uint16_t conn_int_min, uint16_t conn_int_max,
886 uint16_t conn_latency, uint16_t conn_timeout,
887 uint16_t min_ce_len, uint16_t max_ce_len) {
888 connection_->LeConnectionUpdate(conn_int_min, conn_int_max, conn_latency,
889 conn_timeout, min_ce_len, max_ce_len);
890 }
891
892 private:
893 OnDisconnect on_disconnect_;
894 const shim::legacy::acl_le_link_interface_t interface_;
895 std::unique_ptr<hci::acl_manager::LeAclConnection> connection_;
896 };
897
898 struct shim::legacy::Acl::impl {
implshim::legacy::Acl::impl899 impl(uint8_t max_acceptlist_size, uint8_t max_address_resolution_size)
900 : shadow_acceptlist_(ShadowAcceptlist(max_acceptlist_size)),
901 shadow_address_resolution_list_(
902 ShadowAddressResolutionList(max_address_resolution_size)) {}
903
904 std::map<HciHandle, std::unique_ptr<ClassicShimAclConnection>>
905 handle_to_classic_connection_map_;
906 std::map<HciHandle, std::unique_ptr<LeShimAclConnection>>
907 handle_to_le_connection_map_;
908
909 SyncMapCount<std::string> classic_acl_disconnect_reason_;
910 SyncMapCount<std::string> le_acl_disconnect_reason_;
911
912 FixedQueue<std::unique_ptr<ConnectionDescriptor>> connection_history_ =
913 FixedQueue<std::unique_ptr<ConnectionDescriptor>>(kConnectionHistorySize);
914
915 ShadowAcceptlist shadow_acceptlist_;
916 ShadowAddressResolutionList shadow_address_resolution_list_;
917
IsClassicAclshim::legacy::Acl::impl918 bool IsClassicAcl(HciHandle handle) {
919 return handle_to_classic_connection_map_.find(handle) !=
920 handle_to_classic_connection_map_.end();
921 }
922
EnqueueClassicPacketshim::legacy::Acl::impl923 void EnqueueClassicPacket(HciHandle handle,
924 std::unique_ptr<packet::RawBuilder> packet) {
925 log::assert_that(IsClassicAcl(handle),
926 "handle {} is not a classic connection", handle);
927 handle_to_classic_connection_map_[handle]->EnqueuePacket(std::move(packet));
928 }
929
Flushshim::legacy::Acl::impl930 void Flush(HciHandle handle) {
931 if (IsClassicAcl(handle)) {
932 handle_to_classic_connection_map_[handle]->Flush();
933 } else {
934 log::error("handle {} is not a classic connection", handle);
935 }
936 }
937
IsLeAclshim::legacy::Acl::impl938 bool IsLeAcl(HciHandle handle) {
939 return handle_to_le_connection_map_.find(handle) !=
940 handle_to_le_connection_map_.end();
941 }
942
EnqueueLePacketshim::legacy::Acl::impl943 void EnqueueLePacket(HciHandle handle,
944 std::unique_ptr<packet::RawBuilder> packet) {
945 log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection",
946 handle);
947 handle_to_le_connection_map_[handle]->EnqueuePacket(std::move(packet));
948 }
949
DisconnectClassicConnectionsshim::legacy::Acl::impl950 void DisconnectClassicConnections(std::promise<void> promise) {
951 log::info("Disconnect gd acl shim classic connections");
952 std::vector<HciHandle> disconnect_handles;
953 for (auto& connection : handle_to_classic_connection_map_) {
954 disconnect_classic(connection.first, HCI_ERR_REMOTE_POWER_OFF,
955 "Suspend disconnect");
956 disconnect_handles.push_back(connection.first);
957 }
958
959 // Since this is a suspend disconnect, we immediately also call
960 // |OnClassicSuspendInitiatedDisconnect| without waiting for it to happen.
961 // We want the stack to clean up ahead of the link layer (since we will mask
962 // away that event). The reason we do this in a separate loop is that this
963 // will also remove the handle from the connection map.
964 for (auto& handle : disconnect_handles) {
965 auto found = handle_to_classic_connection_map_.find(handle);
966 if (found != handle_to_classic_connection_map_.end()) {
967 GetAclManager()->OnClassicSuspendInitiatedDisconnect(
968 found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST);
969 }
970 }
971
972 promise.set_value();
973 }
974
ShutdownClassicConnectionsshim::legacy::Acl::impl975 void ShutdownClassicConnections(std::promise<void> promise) {
976 log::info("Shutdown gd acl shim classic connections");
977 for (auto& connection : handle_to_classic_connection_map_) {
978 connection.second->Shutdown();
979 }
980 handle_to_classic_connection_map_.clear();
981 promise.set_value();
982 }
983
DisconnectLeConnectionsshim::legacy::Acl::impl984 void DisconnectLeConnections(std::promise<void> promise) {
985 log::info("Disconnect gd acl shim le connections");
986 std::vector<HciHandle> disconnect_handles;
987 for (auto& connection : handle_to_le_connection_map_) {
988 disconnect_le(connection.first, HCI_ERR_REMOTE_POWER_OFF,
989 "Suspend disconnect");
990 disconnect_handles.push_back(connection.first);
991 }
992
993 // Since this is a suspend disconnect, we immediately also call
994 // |OnLeSuspendInitiatedDisconnect| without waiting for it to happen. We
995 // want the stack to clean up ahead of the link layer (since we will mask
996 // away that event). The reason we do this in a separate loop is that this
997 // will also remove the handle from the connection map.
998 for (auto& handle : disconnect_handles) {
999 auto found = handle_to_le_connection_map_.find(handle);
1000 if (found != handle_to_le_connection_map_.end()) {
1001 GetAclManager()->OnLeSuspendInitiatedDisconnect(
1002 found->first, hci::ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST);
1003 }
1004 }
1005 promise.set_value();
1006 }
1007
ShutdownLeConnectionsshim::legacy::Acl::impl1008 void ShutdownLeConnections(std::promise<void> promise) {
1009 log::info("Shutdown gd acl shim le connections");
1010 for (auto& connection : handle_to_le_connection_map_) {
1011 connection.second->Shutdown();
1012 }
1013 handle_to_le_connection_map_.clear();
1014 promise.set_value();
1015 }
1016
FinalShutdownshim::legacy::Acl::impl1017 void FinalShutdown(std::promise<void> promise) {
1018 if (!handle_to_classic_connection_map_.empty()) {
1019 for (auto& connection : handle_to_classic_connection_map_) {
1020 connection.second->Shutdown();
1021 }
1022 handle_to_classic_connection_map_.clear();
1023 log::info("Cleared all classic connections count:{}",
1024 handle_to_classic_connection_map_.size());
1025 }
1026
1027 if (!handle_to_le_connection_map_.empty()) {
1028 for (auto& connection : handle_to_le_connection_map_) {
1029 connection.second->Shutdown();
1030 }
1031 handle_to_le_connection_map_.clear();
1032 log::info("Cleared all le connections count:{}",
1033 handle_to_le_connection_map_.size());
1034 }
1035 promise.set_value();
1036 }
1037
HoldModeshim::legacy::Acl::impl1038 void HoldMode(HciHandle handle, uint16_t max_interval,
1039 uint16_t min_interval) {
1040 log::assert_that(IsClassicAcl(handle),
1041 "handle {} is not a classic connection", handle);
1042 handle_to_classic_connection_map_[handle]->HoldMode(max_interval,
1043 min_interval);
1044 }
1045
ExitSniffModeshim::legacy::Acl::impl1046 void ExitSniffMode(HciHandle handle) {
1047 log::assert_that(IsClassicAcl(handle),
1048 "handle {} is not a classic connection", handle);
1049 handle_to_classic_connection_map_[handle]->ExitSniffMode();
1050 }
1051
SniffModeshim::legacy::Acl::impl1052 void SniffMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval,
1053 uint16_t attempt, uint16_t timeout) {
1054 log::assert_that(IsClassicAcl(handle),
1055 "handle {} is not a classic connection", handle);
1056 handle_to_classic_connection_map_[handle]->SniffMode(
1057 max_interval, min_interval, attempt, timeout);
1058 }
1059
SniffSubratingshim::legacy::Acl::impl1060 void SniffSubrating(HciHandle handle, uint16_t maximum_latency,
1061 uint16_t minimum_remote_timeout,
1062 uint16_t minimum_local_timeout) {
1063 log::assert_that(IsClassicAcl(handle),
1064 "handle {} is not a classic connection", handle);
1065 handle_to_classic_connection_map_[handle]->SniffSubrating(
1066 maximum_latency, minimum_remote_timeout, minimum_local_timeout);
1067 }
1068
LeSetDefaultSubrateshim::legacy::Acl::impl1069 void LeSetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max,
1070 uint16_t max_latency, uint16_t cont_num,
1071 uint16_t sup_tout) {
1072 GetAclManager()->LeSetDefaultSubrate(subrate_min, subrate_max, max_latency,
1073 cont_num, sup_tout);
1074 }
1075
LeSubrateRequestshim::legacy::Acl::impl1076 void LeSubrateRequest(HciHandle handle, uint16_t subrate_min,
1077 uint16_t subrate_max, uint16_t max_latency,
1078 uint16_t cont_num, uint16_t sup_tout) {
1079 log::assert_that(IsLeAcl(handle), "handle {} is not a LE connection",
1080 handle);
1081 handle_to_le_connection_map_[handle]->LeSubrateRequest(
1082 subrate_min, subrate_max, max_latency, cont_num, sup_tout);
1083 }
1084
SetConnectionEncryptionshim::legacy::Acl::impl1085 void SetConnectionEncryption(HciHandle handle, hci::Enable enable) {
1086 log::assert_that(IsClassicAcl(handle),
1087 "handle {} is not a classic connection", handle);
1088 handle_to_classic_connection_map_[handle]->SetConnectionEncryption(enable);
1089 }
1090
disconnect_classicshim::legacy::Acl::impl1091 void disconnect_classic(uint16_t handle, tHCI_STATUS reason,
1092 std::string comment) {
1093 auto connection = handle_to_classic_connection_map_.find(handle);
1094 if (connection != handle_to_classic_connection_map_.end()) {
1095 auto remote_address = connection->second->GetRemoteAddress();
1096 connection->second->InitiateDisconnect(
1097 ToDisconnectReasonFromLegacy(reason));
1098 log::debug("Disconnection initiated classic remote:{} handle:{}",
1099 remote_address, handle);
1100 BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address),
1101 "Disconnection initiated",
1102 base::StringPrintf("classic reason:%s comment:%s",
1103 hci_status_code_text(reason).c_str(),
1104 comment.c_str()));
1105 classic_acl_disconnect_reason_.Put(comment);
1106 } else {
1107 log::warn(
1108 "Unable to disconnect unknown classic connection handle:0x{:04x}",
1109 handle);
1110 }
1111 }
1112
disconnect_leshim::legacy::Acl::impl1113 void disconnect_le(uint16_t handle, tHCI_STATUS reason, std::string comment) {
1114 auto connection = handle_to_le_connection_map_.find(handle);
1115 if (connection != handle_to_le_connection_map_.end()) {
1116 auto remote_address_with_type =
1117 connection->second->GetRemoteAddressWithType();
1118 if (!common::init_flags::use_unified_connection_manager_is_enabled()) {
1119 GetAclManager()->RemoveFromBackgroundList(remote_address_with_type);
1120 }
1121 connection->second->InitiateDisconnect(
1122 ToDisconnectReasonFromLegacy(reason));
1123 log::debug("Disconnection initiated le remote:{} handle:{}",
1124 remote_address_with_type, handle);
1125 BTM_LogHistory(kBtmLogTag,
1126 ToLegacyAddressWithType(remote_address_with_type),
1127 "Disconnection initiated",
1128 base::StringPrintf("Le reason:%s comment:%s",
1129 hci_status_code_text(reason).c_str(),
1130 comment.c_str()));
1131 le_acl_disconnect_reason_.Put(comment);
1132 } else {
1133 log::warn("Unable to disconnect unknown le connection handle:0x{:04x}",
1134 handle);
1135 }
1136 }
1137
update_connection_parametersshim::legacy::Acl::impl1138 void update_connection_parameters(uint16_t handle, uint16_t conn_int_min,
1139 uint16_t conn_int_max,
1140 uint16_t conn_latency,
1141 uint16_t conn_timeout, uint16_t min_ce_len,
1142 uint16_t max_ce_len) {
1143 auto connection = handle_to_le_connection_map_.find(handle);
1144 if (connection == handle_to_le_connection_map_.end()) {
1145 log::warn("Unknown le connection handle:0x{:04x}", handle);
1146 return;
1147 }
1148 connection->second->UpdateConnectionParameters(conn_int_min, conn_int_max,
1149 conn_latency, conn_timeout,
1150 min_ce_len, max_ce_len);
1151 }
1152
accept_le_connection_fromshim::legacy::Acl::impl1153 void accept_le_connection_from(const hci::AddressWithType& address_with_type,
1154 bool is_direct, std::promise<bool> promise) {
1155 if (shadow_acceptlist_.IsFull()) {
1156 log::error("Acceptlist is full preventing new Le connection");
1157 promise.set_value(false);
1158 return;
1159 }
1160 shadow_acceptlist_.Add(address_with_type);
1161 promise.set_value(true);
1162 GetAclManager()->CreateLeConnection(address_with_type, is_direct);
1163 log::debug("Allow Le connection from remote:{}", address_with_type);
1164 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1165 "Allow connection from", "Le");
1166 }
1167
ignore_le_connection_fromshim::legacy::Acl::impl1168 void ignore_le_connection_from(
1169 const hci::AddressWithType& address_with_type) {
1170 shadow_acceptlist_.Remove(address_with_type);
1171 GetAclManager()->CancelLeConnect(address_with_type);
1172 log::debug("Ignore Le connection from remote:{}", address_with_type);
1173 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1174 "Ignore connection from", "Le");
1175 }
1176
clear_acceptlistshim::legacy::Acl::impl1177 void clear_acceptlist() {
1178 auto shadow_acceptlist = shadow_acceptlist_.GetCopy();
1179 size_t count = shadow_acceptlist.size();
1180 GetAclManager()->ClearFilterAcceptList();
1181 shadow_acceptlist_.Clear();
1182 log::debug("Cleared entire Le address acceptlist count:{}", count);
1183 }
1184
AddToAddressResolutionshim::legacy::Acl::impl1185 void AddToAddressResolution(const hci::AddressWithType& address_with_type,
1186 const std::array<uint8_t, 16>& peer_irk,
1187 const std::array<uint8_t, 16>& local_irk) {
1188 if (shadow_address_resolution_list_.IsFull()) {
1189 log::warn("Le Address Resolution list is full size:{}",
1190 shadow_address_resolution_list_.Size());
1191 return;
1192 }
1193 // TODO This should really be added upon successful completion
1194 shadow_address_resolution_list_.Add(address_with_type);
1195 GetAclManager()->AddDeviceToResolvingList(address_with_type, peer_irk,
1196 local_irk);
1197 }
1198
RemoveFromAddressResolutionshim::legacy::Acl::impl1199 void RemoveFromAddressResolution(
1200 const hci::AddressWithType& address_with_type) {
1201 // TODO This should really be removed upon successful removal
1202 if (!shadow_address_resolution_list_.Remove(address_with_type)) {
1203 log::warn("Unable to remove from Le Address Resolution list device:{}",
1204 address_with_type);
1205 }
1206 GetAclManager()->RemoveDeviceFromResolvingList(address_with_type);
1207 }
1208
ClearResolvingListshim::legacy::Acl::impl1209 void ClearResolvingList() {
1210 GetAclManager()->ClearResolvingList();
1211 // TODO This should really be cleared after successful clear status
1212 shadow_address_resolution_list_.Clear();
1213 }
1214
SetSystemSuspendStateshim::legacy::Acl::impl1215 void SetSystemSuspendState(bool suspended) {
1216 GetAclManager()->SetSystemSuspendState(suspended);
1217 }
1218
DumpConnectionHistoryshim::legacy::Acl::impl1219 void DumpConnectionHistory() const {
1220 std::vector<std::string> history =
1221 connection_history_.ReadElementsAsString();
1222 for (auto& entry : history) {
1223 log::debug("{}", entry);
1224 }
1225 const auto acceptlist = shadow_acceptlist_.GetCopy();
1226 log::debug("Shadow le accept list size:{:<3} controller_max_size:{}",
1227 acceptlist.size(), shadow_acceptlist_.GetMaxSize());
1228 for (auto& entry : acceptlist) {
1229 log::debug("acceptlist:{}", entry);
1230 }
1231 }
1232
1233 #define DUMPSYS_TAG "shim::acl"
DumpConnectionHistoryshim::legacy::Acl::impl1234 void DumpConnectionHistory(int fd) const {
1235 std::vector<std::string> history =
1236 connection_history_.ReadElementsAsString();
1237 for (auto& entry : history) {
1238 LOG_DUMPSYS(fd, "%s", entry.c_str());
1239 }
1240 if (classic_acl_disconnect_reason_.Size() > 0) {
1241 LOG_DUMPSYS(fd, "Classic sources of initiated disconnects");
1242 for (const auto& item :
1243 classic_acl_disconnect_reason_.GetSortedHighToLow()) {
1244 LOG_DUMPSYS(fd, " %s:%zu", item.item.c_str(), item.count);
1245 }
1246 }
1247 if (le_acl_disconnect_reason_.Size() > 0) {
1248 LOG_DUMPSYS(fd, "Le sources of initiated disconnects");
1249 for (const auto& item : le_acl_disconnect_reason_.GetSortedHighToLow()) {
1250 LOG_DUMPSYS(fd, " %s:%zu", item.item.c_str(), item.count);
1251 }
1252 }
1253
1254 auto acceptlist = shadow_acceptlist_.GetCopy();
1255 LOG_DUMPSYS(fd,
1256 "Shadow le accept list size:%-3zu "
1257 "controller_max_size:%hhu",
1258 acceptlist.size(), shadow_acceptlist_.GetMaxSize());
1259 unsigned cnt = 0;
1260 for (auto& entry : acceptlist) {
1261 LOG_DUMPSYS(fd, " %03u %s", ++cnt, ADDRESS_TO_LOGGABLE_CSTR(entry));
1262 }
1263 auto address_resolution_list = shadow_address_resolution_list_.GetCopy();
1264 LOG_DUMPSYS(fd,
1265 "Shadow le address resolution list size:%-3zu "
1266 "controller_max_size:%hhu",
1267 address_resolution_list.size(),
1268 shadow_address_resolution_list_.GetMaxSize());
1269 cnt = 0;
1270 for (auto& entry : address_resolution_list) {
1271 LOG_DUMPSYS(fd, " %03u %s", ++cnt, ADDRESS_TO_LOGGABLE_CSTR(entry));
1272 }
1273 }
1274 #undef DUMPSYS_TAG
1275 };
1276
1277 #define DUMPSYS_TAG "shim::legacy::acl"
DumpsysAcl(int fd)1278 void DumpsysAcl(int fd) {
1279 const tACL_CB& acl_cb = btm_cb.acl_cb_;
1280
1281 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1282
1283 if (shim::Stack::GetInstance()->IsRunning()) {
1284 shim::Stack::GetInstance()->GetAcl()->DumpConnectionHistory(fd);
1285 }
1286
1287 for (int i = 0; i < MAX_L2CAP_LINKS; i++) {
1288 const tACL_CONN& link = acl_cb.acl_db[i];
1289 if (!link.in_use) continue;
1290
1291 LOG_DUMPSYS(fd, "remote_addr:%s handle:0x%04x transport:%s",
1292 ADDRESS_TO_LOGGABLE_CSTR(link.remote_addr), link.hci_handle,
1293 bt_transport_text(link.transport).c_str());
1294 LOG_DUMPSYS(fd, " link_up_issued:%5s",
1295 (link.link_up_issued) ? "true" : "false");
1296 LOG_DUMPSYS(fd, " flush_timeout:0x%04x", link.flush_timeout_in_ticks);
1297 LOG_DUMPSYS(fd, " link_supervision_timeout:%.3f sec",
1298 ticks_to_seconds(link.link_super_tout));
1299 LOG_DUMPSYS(fd, " disconnect_reason:0x%02x", link.disconnect_reason);
1300
1301 if (link.is_transport_br_edr()) {
1302 for (int j = 0; j < HCI_EXT_FEATURES_PAGE_MAX + 1; j++) {
1303 if (!link.peer_lmp_feature_valid[j]) continue;
1304 LOG_DUMPSYS(fd, " peer_lmp_features[%d] valid:%s data:%s", j,
1305 common::ToString(link.peer_lmp_feature_valid[j]).c_str(),
1306 bd_features_text(link.peer_lmp_feature_pages[j]).c_str());
1307 }
1308 LOG_DUMPSYS(fd, " [classic] link_policy:%s",
1309 link_policy_text(static_cast<tLINK_POLICY>(link.link_policy))
1310 .c_str());
1311 LOG_DUMPSYS(fd, " [classic] sniff_subrating:%s",
1312 common::ToString(HCI_SNIFF_SUB_RATE_SUPPORTED(
1313 link.peer_lmp_feature_pages[0]))
1314 .c_str());
1315
1316 LOG_DUMPSYS(fd, " pkt_types_mask:0x%04x", link.pkt_types_mask);
1317 LOG_DUMPSYS(fd, " role:%s", RoleText(link.link_role).c_str());
1318 } else if (link.is_transport_ble()) {
1319 LOG_DUMPSYS(fd, " [le] peer_features valid:%s data:%s",
1320 common::ToString(link.peer_le_features_valid).c_str(),
1321 bd_features_text(link.peer_le_features).c_str());
1322
1323 LOG_DUMPSYS(fd, " [le] active_remote_addr:%s[%s]",
1324 ADDRESS_TO_LOGGABLE_CSTR(link.active_remote_addr),
1325 AddressTypeText(link.active_remote_addr_type).c_str());
1326 }
1327 }
1328 }
1329 #undef DUMPSYS_TAG
1330
1331 using Record = common::TimestampedEntry<std::string>;
1332 const std::string kTimeFormat("%Y-%m-%d %H:%M:%S");
1333
1334 #define DUMPSYS_TAG "shim::legacy::btm"
DumpsysBtm(int fd)1335 void DumpsysBtm(int fd) {
1336 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1337 if (btm_cb.history_ != nullptr) {
1338 std::vector<Record> history = btm_cb.history_->Pull();
1339 for (auto& record : history) {
1340 time_t then = record.timestamp / 1000;
1341 struct tm tm;
1342 localtime_r(&then, &tm);
1343 auto s2 = common::StringFormatTime(kTimeFormat, tm);
1344 LOG_DUMPSYS(fd, " %s.%03u %s", s2.c_str(),
1345 static_cast<unsigned int>(record.timestamp % 1000),
1346 record.entry.c_str());
1347 }
1348 }
1349 }
1350 #undef DUMPSYS_TAG
1351
1352 #define DUMPSYS_TAG "shim::legacy::record"
DumpsysRecord(int fd)1353 void DumpsysRecord(int fd) {
1354 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1355
1356 if (btm_sec_cb.sec_dev_rec == nullptr) {
1357 LOG_DUMPSYS(fd, "Record is empty - no devices");
1358 return;
1359 }
1360
1361 unsigned cnt = 0;
1362 list_node_t* end = list_end(btm_sec_cb.sec_dev_rec);
1363 for (list_node_t* node = list_begin(btm_sec_cb.sec_dev_rec); node != end;
1364 node = list_next(node)) {
1365 tBTM_SEC_DEV_REC* p_dev_rec =
1366 static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
1367 // TODO: handle in tBTM_SEC_DEV_REC.ToString
1368 LOG_DUMPSYS(fd, "%03u %s", ++cnt, p_dev_rec->ToString().c_str());
1369 }
1370 }
1371 #undef DUMPSYS_TAG
1372
1373 #define DUMPSYS_TAG "shim::legacy::stack"
DumpsysNeighbor(int fd)1374 void DumpsysNeighbor(int fd) {
1375 LOG_DUMPSYS(fd, "Stack information %lc%lc", kRunicBjarkan, kRunicHagall);
1376 if (btm_cb.neighbor.classic_inquiry.start_time_ms == 0) {
1377 LOG_DUMPSYS(fd, "Classic inquiry:disabled");
1378 } else {
1379 LOG_DUMPSYS(fd, "Classic inquiry:enabled duration_s:%.3f results:%lu",
1380 (timestamper_in_milliseconds.GetTimestamp() -
1381 btm_cb.neighbor.classic_inquiry.start_time_ms) /
1382 1000.0,
1383 btm_cb.neighbor.classic_inquiry.results);
1384 }
1385 if (btm_cb.neighbor.le_scan.start_time_ms == 0) {
1386 LOG_DUMPSYS(fd, "Le scan:disabled");
1387 } else {
1388 LOG_DUMPSYS(fd, "Le scan:enabled duration_s:%.3f results:%lu",
1389 (timestamper_in_milliseconds.GetTimestamp() -
1390 btm_cb.neighbor.le_scan.start_time_ms) /
1391 1000.0,
1392 btm_cb.neighbor.le_scan.results);
1393 }
1394 const auto copy = btm_cb.neighbor.inquiry_history_->Pull();
1395 LOG_DUMPSYS(fd, "Last %zu inquiry scans:", copy.size());
1396 for (const auto& it : copy) {
1397 LOG_DUMPSYS(fd,
1398 " %s - %s duration_ms:%-5llu num_resp:%-2u"
1399 " std:%-2u rssi:%-2u ext:%-2u %12s",
1400 EpochMillisToString(it.entry.start_time_ms).c_str(),
1401 EpochMillisToString(it.timestamp).c_str(),
1402 it.timestamp - it.entry.start_time_ms, it.entry.num_resp,
1403 it.entry.resp_type[BTM_INQ_RESULT_STANDARD],
1404 it.entry.resp_type[BTM_INQ_RESULT_WITH_RSSI],
1405 it.entry.resp_type[BTM_INQ_RESULT_EXTENDED],
1406 btm_inquiry_cmpl_status_text(it.entry.status).c_str());
1407 }
1408 }
1409 #undef DUMPSYS_TAG
1410
Dump(int fd) const1411 void shim::legacy::Acl::Dump(int fd) const {
1412 DumpsysRecord(fd);
1413 DumpsysNeighbor(fd);
1414 DumpsysAcl(fd);
1415 L2CA_Dumpsys(fd);
1416 DumpsysBtm(fd);
1417 }
1418
Acl(os::Handler * handler,const acl_interface_t & acl_interface,uint8_t max_acceptlist_size,uint8_t max_address_resolution_size)1419 shim::legacy::Acl::Acl(os::Handler* handler,
1420 const acl_interface_t& acl_interface,
1421 uint8_t max_acceptlist_size,
1422 uint8_t max_address_resolution_size)
1423 : handler_(handler), acl_interface_(acl_interface) {
1424 log::assert_that(handler_ != nullptr, "assert failed: handler_ != nullptr");
1425 ValidateAclInterface(acl_interface_);
1426 pimpl_ = std::make_unique<Acl::impl>(max_acceptlist_size,
1427 max_address_resolution_size);
1428 GetAclManager()->RegisterCallbacks(this, handler_);
1429 GetAclManager()->RegisterLeCallbacks(this, handler_);
1430 GetController()->RegisterCompletedMonitorAclPacketsCallback(
1431 handler->BindOn(this, &Acl::on_incoming_acl_credits));
1432 shim::RegisterDumpsysFunction(static_cast<void*>(this),
1433 [this](int fd) { Dump(fd); });
1434 }
1435
~Acl()1436 shim::legacy::Acl::~Acl() {
1437 shim::UnregisterDumpsysFunction(static_cast<void*>(this));
1438 GetController()->UnregisterCompletedMonitorAclPacketsCallback();
1439
1440 if (CheckForOrphanedAclConnections()) {
1441 pimpl_->DumpConnectionHistory();
1442 }
1443 }
1444
CheckForOrphanedAclConnections() const1445 bool shim::legacy::Acl::CheckForOrphanedAclConnections() const {
1446 bool orphaned_acl_connections = false;
1447
1448 if (!pimpl_->handle_to_classic_connection_map_.empty()) {
1449 log::error("About to destroy classic active ACL");
1450 for (const auto& connection : pimpl_->handle_to_classic_connection_map_) {
1451 log::error("Orphaned classic ACL handle:0x{:04x} bd_addr:{} created:{}",
1452 connection.second->Handle(),
1453 connection.second->GetRemoteAddress(),
1454 common::StringFormatTimeWithMilliseconds(
1455 kConnectionDescriptorTimeFormat,
1456 connection.second->GetCreationTime()));
1457 }
1458 orphaned_acl_connections = true;
1459 }
1460
1461 if (!pimpl_->handle_to_le_connection_map_.empty()) {
1462 log::error("About to destroy le active ACL");
1463 for (const auto& connection : pimpl_->handle_to_le_connection_map_) {
1464 log::error("Orphaned le ACL handle:0x{:04x} bd_addr:{} created:{}",
1465 connection.second->Handle(),
1466 connection.second->GetRemoteAddressWithType(),
1467 common::StringFormatTimeWithMilliseconds(
1468 kConnectionDescriptorTimeFormat,
1469 connection.second->GetCreationTime()));
1470 }
1471 orphaned_acl_connections = true;
1472 }
1473 return orphaned_acl_connections;
1474 }
1475
on_incoming_acl_credits(uint16_t handle,uint16_t credits)1476 void shim::legacy::Acl::on_incoming_acl_credits(uint16_t handle,
1477 uint16_t credits) {
1478 TRY_POSTING_ON_MAIN(acl_interface_.on_packets_completed, handle, credits);
1479 }
1480
write_data_sync(HciHandle handle,std::unique_ptr<packet::RawBuilder> packet)1481 void shim::legacy::Acl::write_data_sync(
1482 HciHandle handle, std::unique_ptr<packet::RawBuilder> packet) {
1483 if (pimpl_->IsClassicAcl(handle)) {
1484 pimpl_->EnqueueClassicPacket(handle, std::move(packet));
1485 } else if (pimpl_->IsLeAcl(handle)) {
1486 pimpl_->EnqueueLePacket(handle, std::move(packet));
1487 } else {
1488 log::error("Unable to find destination to write data\n");
1489 }
1490 }
1491
WriteData(HciHandle handle,std::unique_ptr<packet::RawBuilder> packet)1492 void shim::legacy::Acl::WriteData(HciHandle handle,
1493 std::unique_ptr<packet::RawBuilder> packet) {
1494 handler_->Post(common::BindOnce(&Acl::write_data_sync,
1495 common::Unretained(this), handle,
1496 std::move(packet)));
1497 }
1498
flush(HciHandle handle)1499 void shim::legacy::Acl::flush(HciHandle handle) { pimpl_->Flush(handle); }
1500
Flush(HciHandle handle)1501 void shim::legacy::Acl::Flush(HciHandle handle) {
1502 handler_->Post(
1503 common::BindOnce(&Acl::flush, common::Unretained(this), handle));
1504 }
1505
CreateClassicConnection(const hci::Address & address)1506 void shim::legacy::Acl::CreateClassicConnection(const hci::Address& address) {
1507 GetAclManager()->CreateConnection(address);
1508 log::debug("Connection initiated for classic to remote:{}", address);
1509 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Initiated connection",
1510 "classic");
1511 }
1512
CancelClassicConnection(const hci::Address & address)1513 void shim::legacy::Acl::CancelClassicConnection(const hci::Address& address) {
1514 GetAclManager()->CancelConnect(address);
1515 log::debug("Connection cancelled for classic to remote:{}", address);
1516 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Cancelled connection",
1517 "classic");
1518 }
1519
AcceptLeConnectionFrom(const hci::AddressWithType & address_with_type,bool is_direct,std::promise<bool> promise)1520 void shim::legacy::Acl::AcceptLeConnectionFrom(
1521 const hci::AddressWithType& address_with_type, bool is_direct,
1522 std::promise<bool> promise) {
1523 log::debug("AcceptLeConnectionFrom {}", address_with_type.GetAddress());
1524 handler_->CallOn(pimpl_.get(), &Acl::impl::accept_le_connection_from,
1525 address_with_type, is_direct, std::move(promise));
1526 }
1527
IgnoreLeConnectionFrom(const hci::AddressWithType & address_with_type)1528 void shim::legacy::Acl::IgnoreLeConnectionFrom(
1529 const hci::AddressWithType& address_with_type) {
1530 log::debug("IgnoreLeConnectionFrom {}", address_with_type.GetAddress());
1531 handler_->CallOn(pimpl_.get(), &Acl::impl::ignore_le_connection_from,
1532 address_with_type);
1533 }
1534
OnClassicLinkDisconnected(HciHandle handle,hci::ErrorCode reason)1535 void shim::legacy::Acl::OnClassicLinkDisconnected(HciHandle handle,
1536 hci::ErrorCode reason) {
1537 hci::Address remote_address =
1538 pimpl_->handle_to_classic_connection_map_[handle]->GetRemoteAddress();
1539 CreationTime creation_time =
1540 pimpl_->handle_to_classic_connection_map_[handle]->GetCreationTime();
1541 bool is_locally_initiated =
1542 pimpl_->handle_to_classic_connection_map_[handle]->IsLocallyInitiated();
1543
1544 TeardownTime teardown_time = std::chrono::system_clock::now();
1545
1546 pimpl_->handle_to_classic_connection_map_.erase(handle);
1547 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_disconnected,
1548 ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
1549 ToLegacyHciErrorCode(reason));
1550 log::debug("Disconnected classic link remote:{} handle:{} reason:{}",
1551 remote_address, handle, ErrorCodeText(reason));
1552 BTM_LogHistory(
1553 kBtmLogTag, ToRawAddress(remote_address), "Disconnected",
1554 base::StringPrintf("classic reason:%s", ErrorCodeText(reason).c_str()));
1555 pimpl_->connection_history_.Push(
1556 std::make_unique<ClassicConnectionDescriptor>(
1557 remote_address, creation_time, teardown_time, handle,
1558 is_locally_initiated, reason));
1559 }
1560
GetConnectionLocalAddress(uint16_t handle,bool ota_address)1561 bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress(
1562 uint16_t handle, bool ota_address) {
1563 bluetooth::hci::AddressWithType address_with_type;
1564
1565 for (auto& [acl_handle, connection] : pimpl_->handle_to_le_connection_map_) {
1566 if (acl_handle != handle) {
1567 continue;
1568 }
1569
1570 if (ota_address) {
1571 return connection->GetLocalOtaAddressWithType();
1572 }
1573 return connection->GetLocalAddressWithType();
1574 }
1575 log::warn("address not found!");
1576 return address_with_type;
1577 }
1578
GetConnectionPeerAddress(uint16_t handle,bool ota_address)1579 bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionPeerAddress(
1580 uint16_t handle, bool ota_address) {
1581 bluetooth::hci::AddressWithType address_with_type;
1582 for (auto& [acl_handle, connection] : pimpl_->handle_to_le_connection_map_) {
1583 if (acl_handle != handle) {
1584 continue;
1585 }
1586
1587 if (ota_address) {
1588 return connection->GetPeerOtaAddressWithType();
1589 }
1590 return connection->GetPeerAddressWithType();
1591 }
1592 log::warn("address not found!");
1593 return address_with_type;
1594 }
1595
GetAdvertisingSetConnectedTo(const RawAddress & remote_bda)1596 std::optional<uint8_t> shim::legacy::Acl::GetAdvertisingSetConnectedTo(
1597 const RawAddress& remote_bda) {
1598 auto remote_address = ToGdAddress(remote_bda);
1599 for (auto& [handle, connection] : pimpl_->handle_to_le_connection_map_) {
1600 if (connection->GetRemoteAddressWithType().GetAddress() == remote_address) {
1601 return connection->GetAdvertisingSetConnectedTo();
1602 }
1603 }
1604 log::warn("address not found!");
1605 return {};
1606 }
1607
OnLeLinkDisconnected(HciHandle handle,hci::ErrorCode reason)1608 void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle handle,
1609 hci::ErrorCode reason) {
1610 hci::AddressWithType remote_address_with_type =
1611 pimpl_->handle_to_le_connection_map_[handle]->GetRemoteAddressWithType();
1612 CreationTime creation_time =
1613 pimpl_->handle_to_le_connection_map_[handle]->GetCreationTime();
1614 bool is_locally_initiated =
1615 pimpl_->handle_to_le_connection_map_[handle]->IsLocallyInitiated();
1616
1617 TeardownTime teardown_time = std::chrono::system_clock::now();
1618
1619 pimpl_->handle_to_le_connection_map_.erase(handle);
1620 TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_disconnected,
1621 ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
1622 ToLegacyHciErrorCode(reason));
1623 log::debug("Disconnected le link remote:{} handle:{} reason:{}",
1624 remote_address_with_type, handle, ErrorCodeText(reason));
1625 BTM_LogHistory(
1626 kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type),
1627 "Disconnected",
1628 base::StringPrintf("Le reason:%s", ErrorCodeText(reason).c_str()));
1629 pimpl_->connection_history_.Push(std::make_unique<LeConnectionDescriptor>(
1630 remote_address_with_type, creation_time, teardown_time, handle,
1631 is_locally_initiated, reason));
1632 }
1633
OnConnectSuccess(std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection)1634 void shim::legacy::Acl::OnConnectSuccess(
1635 std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection) {
1636 log::assert_that(connection != nullptr,
1637 "assert failed: connection != nullptr");
1638 auto handle = connection->GetHandle();
1639 bool locally_initiated = connection->locally_initiated_;
1640 const hci::Address remote_address = connection->GetAddress();
1641 const RawAddress bd_addr = ToRawAddress(remote_address);
1642
1643 pimpl_->handle_to_classic_connection_map_.emplace(
1644 handle, std::make_unique<ClassicShimAclConnection>(
1645 acl_interface_.on_send_data_upwards,
1646 std::bind(&shim::legacy::Acl::OnClassicLinkDisconnected, this,
1647 std::placeholders::_1, std::placeholders::_2),
1648 acl_interface_.link.classic, handler_, std::move(connection),
1649 std::chrono::system_clock::now()));
1650 pimpl_->handle_to_classic_connection_map_[handle]->RegisterCallbacks();
1651 pimpl_->handle_to_classic_connection_map_[handle]
1652 ->ReadRemoteControllerInformation();
1653
1654 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connected, bd_addr,
1655 handle, false, locally_initiated);
1656 log::debug("Connection successful classic remote:{} handle:{} initiator:{}",
1657 remote_address, handle, (locally_initiated) ? "local" : "remote");
1658 BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address),
1659 "Connection successful",
1660 (locally_initiated) ? "classic Local initiated"
1661 : "classic Remote initiated");
1662 }
1663
OnConnectRequest(hci::Address address,hci::ClassOfDevice cod)1664 void shim::legacy::Acl::OnConnectRequest(hci::Address address,
1665 hci::ClassOfDevice cod) {
1666 const RawAddress bd_addr = ToRawAddress(address);
1667 const DEV_CLASS dev_class = ToDevClass(cod);
1668
1669 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connect_request,
1670 bd_addr, cod);
1671 log::debug("Received connect request remote:{} gd_cod:{} legacy_dev_class:{}",
1672 address, cod.ToString(), dev_class_text(dev_class));
1673 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection request",
1674 base::StringPrintf("gd_cod:%s legacy_dev_class:%s",
1675 cod.ToString().c_str(),
1676 dev_class_text(dev_class).c_str()));
1677 }
1678
OnConnectFail(hci::Address address,hci::ErrorCode reason,bool locally_initiated)1679 void shim::legacy::Acl::OnConnectFail(hci::Address address,
1680 hci::ErrorCode reason,
1681 bool locally_initiated) {
1682 const RawAddress bd_addr = ToRawAddress(address);
1683 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_failed, bd_addr,
1684 ToLegacyHciErrorCode(reason), locally_initiated);
1685 log::warn("Connection failed classic remote:{} reason:{}", address,
1686 hci::ErrorCodeText(reason));
1687 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection failed",
1688 base::StringPrintf("classic reason:%s",
1689 hci::ErrorCodeText(reason).c_str()));
1690 }
1691
OnLeConnectSuccess(hci::AddressWithType address_with_type,std::unique_ptr<hci::acl_manager::LeAclConnection> connection)1692 void shim::legacy::Acl::OnLeConnectSuccess(
1693 hci::AddressWithType address_with_type,
1694 std::unique_ptr<hci::acl_manager::LeAclConnection> connection) {
1695 log::assert_that(connection != nullptr,
1696 "assert failed: connection != nullptr");
1697 auto handle = connection->GetHandle();
1698
1699 // Save the peer address, if any
1700 hci::AddressWithType peer_address_with_type =
1701 connection->peer_address_with_type_;
1702
1703 hci::Role connection_role = connection->GetRole();
1704 bool locally_initiated = connection->locally_initiated_;
1705
1706 uint16_t conn_interval = connection->interval_;
1707 uint16_t conn_latency = connection->latency_;
1708 uint16_t conn_timeout = connection->supervision_timeout_;
1709
1710 RawAddress local_rpa =
1711 ToRawAddress(connection->local_resolvable_private_address_);
1712 RawAddress peer_rpa =
1713 ToRawAddress(connection->peer_resolvable_private_address_);
1714 tBLE_ADDR_TYPE peer_addr_type =
1715 (tBLE_ADDR_TYPE)connection->peer_address_with_type_.GetAddressType();
1716
1717 auto can_read_discoverable_characteristics = std::visit(
1718 [&](auto&& data) {
1719 using T = std::decay_t<decltype(data)>;
1720 if constexpr (std::is_same_v<T, hci::acl_manager::DataAsPeripheral>) {
1721 return data.connected_to_discoverable;
1722 } else {
1723 // if we are the central, the peer can always see discoverable
1724 // characteristics
1725 return true;
1726 }
1727 },
1728 connection->GetRoleSpecificData());
1729
1730 pimpl_->handle_to_le_connection_map_.emplace(
1731 handle, std::make_unique<LeShimAclConnection>(
1732 acl_interface_.on_send_data_upwards,
1733 std::bind(&shim::legacy::Acl::OnLeLinkDisconnected, this,
1734 std::placeholders::_1, std::placeholders::_2),
1735 acl_interface_.link.le, handler_, std::move(connection),
1736 std::chrono::system_clock::now()));
1737 pimpl_->handle_to_le_connection_map_[handle]->RegisterCallbacks();
1738
1739 // Once an le connection has successfully been established
1740 // the device address is removed from the controller accept list.
1741
1742 if (IsRpa(address_with_type)) {
1743 log::debug("Connection address is rpa:{} identity_addr:{}",
1744 address_with_type, peer_address_with_type);
1745 pimpl_->shadow_acceptlist_.Remove(peer_address_with_type);
1746 } else {
1747 log::debug("Connection address is not rpa addr:{}", address_with_type);
1748 pimpl_->shadow_acceptlist_.Remove(address_with_type);
1749 }
1750
1751 if (!pimpl_->handle_to_le_connection_map_[handle]->IsInFilterAcceptList() &&
1752 connection_role == hci::Role::CENTRAL) {
1753 pimpl_->handle_to_le_connection_map_[handle]->InitiateDisconnect(
1754 hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
1755 log::info("Disconnected ACL after connection canceled");
1756 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1757 "Connection canceled", "Le");
1758 return;
1759 }
1760
1761 pimpl_->handle_to_le_connection_map_[handle]
1762 ->ReadRemoteControllerInformation();
1763
1764 tBLE_BD_ADDR legacy_address_with_type =
1765 ToLegacyAddressWithType(address_with_type);
1766
1767 TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_connected,
1768 legacy_address_with_type, handle,
1769 ToLegacyRole(connection_role), conn_interval,
1770 conn_latency, conn_timeout, local_rpa, peer_rpa,
1771 peer_addr_type, can_read_discoverable_characteristics);
1772
1773 log::debug("Connection successful le remote:{} handle:{} initiator:{}",
1774 address_with_type, handle,
1775 (locally_initiated) ? "local" : "remote");
1776 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1777 "Connection successful", "Le");
1778 }
1779
OnLeConnectFail(hci::AddressWithType address_with_type,hci::ErrorCode reason)1780 void shim::legacy::Acl::OnLeConnectFail(hci::AddressWithType address_with_type,
1781 hci::ErrorCode reason) {
1782 tBLE_BD_ADDR legacy_address_with_type =
1783 ToLegacyAddressWithType(address_with_type);
1784
1785 uint16_t handle = 0; /* TODO Unneeded */
1786 bool enhanced = true; /* TODO logging metrics only */
1787 tHCI_STATUS status = ToLegacyHciErrorCode(reason);
1788
1789 TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_failed,
1790 legacy_address_with_type, handle, enhanced, status);
1791
1792 pimpl_->shadow_acceptlist_.Remove(address_with_type);
1793 log::warn("Connection failed le remote:{}", address_with_type);
1794 BTM_LogHistory(
1795 kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1796 "Connection failed",
1797 base::StringPrintf("le reason:%s", hci::ErrorCodeText(reason).c_str()));
1798 }
1799
DisconnectClassic(uint16_t handle,tHCI_STATUS reason,std::string comment)1800 void shim::legacy::Acl::DisconnectClassic(uint16_t handle, tHCI_STATUS reason,
1801 std::string comment) {
1802 handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_classic, handle, reason,
1803 comment);
1804 }
1805
DisconnectLe(uint16_t handle,tHCI_STATUS reason,std::string comment)1806 void shim::legacy::Acl::DisconnectLe(uint16_t handle, tHCI_STATUS reason,
1807 std::string comment) {
1808 handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_le, handle, reason,
1809 comment);
1810 }
1811
UpdateConnectionParameters(uint16_t handle,uint16_t conn_int_min,uint16_t conn_int_max,uint16_t conn_latency,uint16_t conn_timeout,uint16_t min_ce_len,uint16_t max_ce_len)1812 void shim::legacy::Acl::UpdateConnectionParameters(
1813 uint16_t handle, uint16_t conn_int_min, uint16_t conn_int_max,
1814 uint16_t conn_latency, uint16_t conn_timeout, uint16_t min_ce_len,
1815 uint16_t max_ce_len) {
1816 handler_->CallOn(pimpl_.get(), &Acl::impl::update_connection_parameters,
1817 handle, conn_int_min, conn_int_max, conn_latency,
1818 conn_timeout, min_ce_len, max_ce_len);
1819 }
1820
LeSetDefaultSubrate(uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t sup_tout)1821 void shim::legacy::Acl::LeSetDefaultSubrate(uint16_t subrate_min,
1822 uint16_t subrate_max,
1823 uint16_t max_latency,
1824 uint16_t cont_num,
1825 uint16_t sup_tout) {
1826 handler_->CallOn(pimpl_.get(), &Acl::impl::LeSetDefaultSubrate, subrate_min,
1827 subrate_max, max_latency, cont_num, sup_tout);
1828 }
1829
LeSubrateRequest(uint16_t hci_handle,uint16_t subrate_min,uint16_t subrate_max,uint16_t max_latency,uint16_t cont_num,uint16_t sup_tout)1830 void shim::legacy::Acl::LeSubrateRequest(uint16_t hci_handle,
1831 uint16_t subrate_min,
1832 uint16_t subrate_max,
1833 uint16_t max_latency,
1834 uint16_t cont_num, uint16_t sup_tout) {
1835 handler_->CallOn(pimpl_.get(), &Acl::impl::LeSubrateRequest, hci_handle,
1836 subrate_min, subrate_max, max_latency, cont_num, sup_tout);
1837 }
1838
DumpConnectionHistory(int fd) const1839 void shim::legacy::Acl::DumpConnectionHistory(int fd) const {
1840 pimpl_->DumpConnectionHistory(fd);
1841 }
1842
DisconnectAllForSuspend()1843 void shim::legacy::Acl::DisconnectAllForSuspend() {
1844 if (CheckForOrphanedAclConnections()) {
1845 std::promise<void> disconnect_promise;
1846 auto disconnect_future = disconnect_promise.get_future();
1847 handler_->CallOn(pimpl_.get(), &Acl::impl::DisconnectClassicConnections,
1848 std::move(disconnect_promise));
1849 disconnect_future.wait();
1850
1851 disconnect_promise = std::promise<void>();
1852
1853 disconnect_future = disconnect_promise.get_future();
1854 handler_->CallOn(pimpl_.get(), &Acl::impl::DisconnectLeConnections,
1855 std::move(disconnect_promise));
1856 disconnect_future.wait();
1857 log::warn("Disconnected open ACL connections");
1858 }
1859 }
1860
Shutdown()1861 void shim::legacy::Acl::Shutdown() {
1862 if (CheckForOrphanedAclConnections()) {
1863 std::promise<void> shutdown_promise;
1864 auto shutdown_future = shutdown_promise.get_future();
1865 handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownClassicConnections,
1866 std::move(shutdown_promise));
1867 shutdown_future.wait();
1868
1869 shutdown_promise = std::promise<void>();
1870
1871 shutdown_future = shutdown_promise.get_future();
1872 handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownLeConnections,
1873 std::move(shutdown_promise));
1874 shutdown_future.wait();
1875 log::warn("Flushed open ACL connections");
1876 } else {
1877 log::info("All ACL connections have been previously closed");
1878 }
1879 }
1880
FinalShutdown()1881 void shim::legacy::Acl::FinalShutdown() {
1882 std::promise<void> promise;
1883 auto future = promise.get_future();
1884 GetAclManager()->UnregisterCallbacks(this, std::move(promise));
1885 future.wait();
1886 log::debug("Unregistered classic callbacks from gd acl manager");
1887
1888 promise = std::promise<void>();
1889 future = promise.get_future();
1890 GetAclManager()->UnregisterLeCallbacks(this, std::move(promise));
1891 future.wait();
1892 log::debug("Unregistered le callbacks from gd acl manager");
1893
1894 promise = std::promise<void>();
1895 future = promise.get_future();
1896 handler_->CallOn(pimpl_.get(), &Acl::impl::FinalShutdown, std::move(promise));
1897 future.wait();
1898 log::info("Unregistered and cleared any orphaned ACL connections");
1899 }
1900
ClearFilterAcceptList()1901 void shim::legacy::Acl::ClearFilterAcceptList() {
1902 handler_->CallOn(pimpl_.get(), &Acl::impl::clear_acceptlist);
1903 }
1904
AddToAddressResolution(const hci::AddressWithType & address_with_type,const std::array<uint8_t,16> & peer_irk,const std::array<uint8_t,16> & local_irk)1905 void shim::legacy::Acl::AddToAddressResolution(
1906 const hci::AddressWithType& address_with_type,
1907 const std::array<uint8_t, 16>& peer_irk,
1908 const std::array<uint8_t, 16>& local_irk) {
1909 handler_->CallOn(pimpl_.get(), &Acl::impl::AddToAddressResolution,
1910 address_with_type, peer_irk, local_irk);
1911 }
1912
RemoveFromAddressResolution(const hci::AddressWithType & address_with_type)1913 void shim::legacy::Acl::RemoveFromAddressResolution(
1914 const hci::AddressWithType& address_with_type) {
1915 handler_->CallOn(pimpl_.get(), &Acl::impl::RemoveFromAddressResolution,
1916 address_with_type);
1917 }
1918
ClearAddressResolution()1919 void shim::legacy::Acl::ClearAddressResolution() {
1920 handler_->CallOn(pimpl_.get(), &Acl::impl::ClearResolvingList);
1921 }
1922
SetSystemSuspendState(bool suspended)1923 void shim::legacy::Acl::SetSystemSuspendState(bool suspended) {
1924 handler_->CallOn(pimpl_.get(), &Acl::impl::SetSystemSuspendState, suspended);
1925 }
1926