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