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 <time.h>
22
23 #include <chrono>
24 #include <cstdint>
25 #include <functional>
26 #include <future>
27 #include <map>
28 #include <memory>
29 #include <string>
30 #include <unordered_set>
31
32 #include "btif/include/btif_hh.h"
33 #include "device/include/controller.h"
34 #include "gd/common/bidi_queue.h"
35 #include "gd/common/bind.h"
36 #include "gd/common/init_flags.h"
37 #include "gd/common/strings.h"
38 #include "gd/common/sync_map_count.h"
39 #include "gd/hci/acl_manager.h"
40 #include "gd/hci/acl_manager/acl_connection.h"
41 #include "gd/hci/acl_manager/classic_acl_connection.h"
42 #include "gd/hci/acl_manager/connection_management_callbacks.h"
43 #include "gd/hci/acl_manager/le_acl_connection.h"
44 #include "gd/hci/acl_manager/le_connection_management_callbacks.h"
45 #include "gd/hci/acl_manager/le_impl.h"
46 #include "gd/hci/address.h"
47 #include "gd/hci/address_with_type.h"
48 #include "gd/hci/class_of_device.h"
49 #include "gd/hci/controller.h"
50 #include "gd/os/handler.h"
51 #include "gd/os/queue.h"
52 #include "main/shim/btm.h"
53 #include "main/shim/dumpsys.h"
54 #include "main/shim/entry.h"
55 #include "main/shim/helpers.h"
56 #include "main/shim/stack.h"
57 #include "osi/include/allocator.h"
58 #include "stack/acl/acl.h"
59 #include "stack/btm/btm_int_types.h"
60 #include "stack/include/acl_hci_link_interface.h"
61 #include "stack/include/ble_acl_interface.h"
62 #include "stack/include/bt_hdr.h"
63 #include "stack/include/btm_api.h"
64 #include "stack/include/btm_status.h"
65 #include "stack/include/gatt_api.h"
66 #include "stack/include/pan_api.h"
67 #include "stack/include/sec_hci_link_interface.h"
68 #include "stack/l2cap/l2c_int.h"
69 #include "types/ble_address_with_type.h"
70 #include "types/raw_address.h"
71
72 extern tBTM_CB btm_cb;
73
74 bt_status_t do_in_main_thread(const base::Location& from_here,
75 base::OnceClosure task);
76
77 using namespace bluetooth;
78
79 class ConnectAddressWithType {
80 public:
ConnectAddressWithType(hci::AddressWithType address_with_type)81 explicit ConnectAddressWithType(hci::AddressWithType address_with_type)
82 : address_(address_with_type.GetAddress()),
83 type_(address_with_type.ToFilterAcceptListAddressType()) {}
84
ToString() const85 std::string const ToString() const {
86 std::stringstream ss;
87 ss << address_ << "[" << FilterAcceptListAddressTypeText(type_) << "]";
88 return ss.str();
89 }
90
operator ==(const ConnectAddressWithType & rhs) const91 bool operator==(const ConnectAddressWithType& rhs) const {
92 return address_ == rhs.address_ && type_ == rhs.type_;
93 }
94
95 private:
96 friend std::hash<ConnectAddressWithType>;
97 hci::Address address_;
98 hci::FilterAcceptListAddressType type_;
99 };
100
101 namespace std {
102 template <>
103 struct hash<ConnectAddressWithType> {
operator ()std::hash104 std::size_t operator()(const ConnectAddressWithType& val) const {
105 static_assert(sizeof(uint64_t) >=
106 (bluetooth::hci::Address::kLength +
107 sizeof(bluetooth::hci::FilterAcceptListAddressType)));
108 uint64_t int_addr = 0;
109 memcpy(reinterpret_cast<uint8_t*>(&int_addr), val.address_.data(),
110 bluetooth::hci::Address::kLength);
111 memcpy(reinterpret_cast<uint8_t*>(&int_addr) +
112 bluetooth::hci::Address::kLength,
113 &val.type_, sizeof(bluetooth::hci::FilterAcceptListAddressType));
114 return std::hash<uint64_t>{}(int_addr);
115 }
116 };
117 } // namespace std
118
119 namespace {
120
121 using HciHandle = uint16_t;
122 using PageNumber = uint8_t;
123
124 using CreationTime = std::chrono::time_point<std::chrono::system_clock>;
125 using TeardownTime = std::chrono::time_point<std::chrono::system_clock>;
126
127 constexpr char kBtmLogTag[] = "ACL";
128
129 using SendDataUpwards = void (*const)(BT_HDR*);
130 using OnDisconnect = std::function<void(HciHandle, hci::ErrorCode reason)>;
131
132 constexpr char kConnectionDescriptorTimeFormat[] = "%Y-%m-%d %H:%M:%S";
133
IsRpa(const hci::AddressWithType address_with_type)134 inline bool IsRpa(const hci::AddressWithType address_with_type) {
135 return address_with_type.GetAddressType() ==
136 hci::AddressType::RANDOM_DEVICE_ADDRESS &&
137 ((address_with_type.GetAddress().address.data()[5] & 0xc0) == 0x40);
138 }
139
140 class ShadowAcceptlist {
141 public:
ShadowAcceptlist(uint8_t max_acceptlist_size)142 ShadowAcceptlist(uint8_t max_acceptlist_size)
143 : max_acceptlist_size_(max_acceptlist_size) {}
144
Add(const hci::AddressWithType & address_with_type)145 bool Add(const hci::AddressWithType& address_with_type) {
146 if (acceptlist_set_.size() == max_acceptlist_size_) {
147 LOG_ERROR("Acceptlist is full size:%zu", acceptlist_set_.size());
148 return false;
149 }
150 if (!acceptlist_set_.insert(ConnectAddressWithType(address_with_type))
151 .second) {
152 LOG_WARN("Attempted to add duplicate le address to acceptlist:%s",
153 PRIVATE_ADDRESS(address_with_type));
154 }
155 return true;
156 }
157
Remove(const hci::AddressWithType & address_with_type)158 bool Remove(const hci::AddressWithType& address_with_type) {
159 auto iter = acceptlist_set_.find(ConnectAddressWithType(address_with_type));
160 if (iter == acceptlist_set_.end()) {
161 LOG_WARN("Unknown device being removed from acceptlist:%s",
162 PRIVATE_ADDRESS(address_with_type));
163 return false;
164 }
165 acceptlist_set_.erase(ConnectAddressWithType(*iter));
166 return true;
167 }
168
GetCopy() const169 std::unordered_set<ConnectAddressWithType> GetCopy() const {
170 return acceptlist_set_;
171 }
172
IsFull() const173 bool IsFull() const {
174 return acceptlist_set_.size() == static_cast<size_t>(max_acceptlist_size_);
175 }
176
Clear()177 void Clear() { acceptlist_set_.clear(); }
178
179 private:
180 uint8_t max_acceptlist_size_{0};
181 std::unordered_set<ConnectAddressWithType> acceptlist_set_;
182 };
183
184 class ShadowAddressResolutionList {
185 public:
ShadowAddressResolutionList(uint8_t max_address_resolution_size)186 ShadowAddressResolutionList(uint8_t max_address_resolution_size)
187 : max_address_resolution_size_(max_address_resolution_size) {}
188
Add(const hci::AddressWithType & address_with_type)189 bool Add(const hci::AddressWithType& address_with_type) {
190 if (address_resolution_set_.size() == max_address_resolution_size_) {
191 LOG_ERROR("Address Resolution is full size:%zu",
192 address_resolution_set_.size());
193 return false;
194 }
195 if (!address_resolution_set_.insert(address_with_type).second) {
196 LOG_WARN("Attempted to add duplicate le address to address_resolution:%s",
197 PRIVATE_ADDRESS(address_with_type));
198 }
199 return true;
200 }
201
Remove(const hci::AddressWithType & address_with_type)202 bool Remove(const hci::AddressWithType& address_with_type) {
203 auto iter = address_resolution_set_.find(address_with_type);
204 if (iter == address_resolution_set_.end()) {
205 LOG_WARN("Unknown device being removed from address_resolution:%s",
206 PRIVATE_ADDRESS(address_with_type));
207 return false;
208 }
209 address_resolution_set_.erase(iter);
210 return true;
211 }
212
GetCopy() const213 std::unordered_set<hci::AddressWithType> GetCopy() const {
214 return address_resolution_set_;
215 }
216
IsFull() const217 bool IsFull() const {
218 return address_resolution_set_.size() ==
219 static_cast<size_t>(max_address_resolution_size_);
220 }
221
Size() const222 size_t Size() const { return address_resolution_set_.size(); }
223
Clear()224 void Clear() { address_resolution_set_.clear(); }
225
226 private:
227 uint8_t max_address_resolution_size_{0};
228 std::unordered_set<hci::AddressWithType> address_resolution_set_;
229 };
230
231 struct ConnectionDescriptor {
232 CreationTime creation_time_;
233 TeardownTime teardown_time_;
234 uint16_t handle_;
235 bool is_locally_initiated_;
236 hci::ErrorCode disconnect_reason_;
ConnectionDescriptor__anonfdc6d7f20111::ConnectionDescriptor237 ConnectionDescriptor(CreationTime creation_time, TeardownTime teardown_time,
238 uint16_t handle, bool is_locally_initiated,
239 hci::ErrorCode disconnect_reason)
240 : creation_time_(creation_time),
241 teardown_time_(teardown_time),
242 handle_(handle),
243 is_locally_initiated_(is_locally_initiated),
244 disconnect_reason_(disconnect_reason) {}
245 virtual std::string GetPrivateRemoteAddress() const = 0;
~ConnectionDescriptor__anonfdc6d7f20111::ConnectionDescriptor246 virtual ~ConnectionDescriptor() {}
ToString__anonfdc6d7f20111::ConnectionDescriptor247 std::string ToString() const {
248 return base::StringPrintf(
249 "peer:%s handle:0x%04x is_locally_initiated:%s"
250 " creation_time:%s teardown_time:%s disconnect_reason:%s",
251 GetPrivateRemoteAddress().c_str(), handle_,
252 logbool(is_locally_initiated_).c_str(),
253 common::StringFormatTimeWithMilliseconds(
254 kConnectionDescriptorTimeFormat, creation_time_)
255 .c_str(),
256 common::StringFormatTimeWithMilliseconds(
257 kConnectionDescriptorTimeFormat, teardown_time_)
258 .c_str(),
259 hci::ErrorCodeText(disconnect_reason_).c_str());
260 }
261 };
262
263 struct ClassicConnectionDescriptor : public ConnectionDescriptor {
264 const hci::Address remote_address_;
ClassicConnectionDescriptor__anonfdc6d7f20111::ClassicConnectionDescriptor265 ClassicConnectionDescriptor(const hci::Address& remote_address,
266 CreationTime creation_time,
267 TeardownTime teardown_time, uint16_t handle,
268 bool is_locally_initiated,
269 hci::ErrorCode disconnect_reason)
270 : ConnectionDescriptor(creation_time, teardown_time, handle,
271 is_locally_initiated, disconnect_reason),
272 remote_address_(remote_address) {}
GetPrivateRemoteAddress__anonfdc6d7f20111::ClassicConnectionDescriptor273 virtual std::string GetPrivateRemoteAddress() const {
274 return PRIVATE_ADDRESS(remote_address_);
275 }
276 };
277
278 struct LeConnectionDescriptor : public ConnectionDescriptor {
279 const hci::AddressWithType remote_address_with_type_;
LeConnectionDescriptor__anonfdc6d7f20111::LeConnectionDescriptor280 LeConnectionDescriptor(hci::AddressWithType& remote_address_with_type,
281 CreationTime creation_time, TeardownTime teardown_time,
282 uint16_t handle, bool is_locally_initiated,
283 hci::ErrorCode disconnect_reason)
284 : ConnectionDescriptor(creation_time, teardown_time, handle,
285 is_locally_initiated, disconnect_reason),
286 remote_address_with_type_(remote_address_with_type) {}
GetPrivateRemoteAddress__anonfdc6d7f20111::LeConnectionDescriptor287 std::string GetPrivateRemoteAddress() const {
288 return PRIVATE_ADDRESS(remote_address_with_type_);
289 }
290 };
291
292 template <typename T>
293 class FixedQueue {
294 public:
FixedQueue(size_t max_size)295 explicit FixedQueue(size_t max_size) : max_size_(max_size) {}
Push(T element)296 void Push(T element) {
297 if (queue_.size() == max_size_) {
298 queue_.pop_front();
299 }
300 queue_.push_back(std::move(element));
301 }
302
ReadElementsAsString() const303 std::vector<std::string> ReadElementsAsString() const {
304 std::vector<std::string> vector;
305 for (auto& entry : queue_) {
306 vector.push_back(entry->ToString());
307 }
308 return vector;
309 }
310
311 private:
312 size_t max_size_{1};
313 std::deque<T> queue_;
314 };
315
316 constexpr size_t kConnectionHistorySize = 40;
317
LowByte(uint16_t val)318 inline uint8_t LowByte(uint16_t val) { return val & 0xff; }
HighByte(uint16_t val)319 inline uint8_t HighByte(uint16_t val) { return val >> 8; }
320
ValidateAclInterface(const shim::legacy::acl_interface_t & acl_interface)321 void ValidateAclInterface(const shim::legacy::acl_interface_t& acl_interface) {
322 ASSERT_LOG(acl_interface.on_send_data_upwards != nullptr,
323 "Must provide to receive data on acl links");
324 ASSERT_LOG(acl_interface.on_packets_completed != nullptr,
325 "Must provide to receive completed packet indication");
326
327 ASSERT_LOG(acl_interface.connection.classic.on_connected != nullptr,
328 "Must provide to respond to successful classic connections");
329 ASSERT_LOG(acl_interface.connection.classic.on_failed != nullptr,
330 "Must provide to respond when classic connection attempts fail");
331 ASSERT_LOG(
332 acl_interface.connection.classic.on_disconnected != nullptr,
333 "Must provide to respond when active classic connection disconnects");
334
335 ASSERT_LOG(acl_interface.connection.le.on_connected != nullptr,
336 "Must provide to respond to successful le connections");
337 ASSERT_LOG(acl_interface.connection.le.on_failed != nullptr,
338 "Must provide to respond when le connection attempts fail");
339 ASSERT_LOG(acl_interface.connection.le.on_disconnected != nullptr,
340 "Must provide to respond when active le connection disconnects");
341 }
342
343 } // namespace
344
345 #define TRY_POSTING_ON_MAIN(cb, ...) \
346 do { \
347 if (cb == nullptr) { \
348 LOG_WARN("Dropping ACL event with no callback"); \
349 } else { \
350 do_in_main_thread(FROM_HERE, base::Bind(cb, ##__VA_ARGS__)); \
351 } \
352 } while (0)
353
354 constexpr HciHandle kInvalidHciHandle = 0xffff;
355
356 class ShimAclConnection {
357 public:
ShimAclConnection(const HciHandle handle,SendDataUpwards send_data_upwards,os::Handler * handler,hci::acl_manager::AclConnection::QueueUpEnd * queue_up_end,CreationTime creation_time)358 ShimAclConnection(const HciHandle handle, SendDataUpwards send_data_upwards,
359 os::Handler* handler,
360 hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end,
361 CreationTime creation_time)
362 : handle_(handle),
363 handler_(handler),
364 send_data_upwards_(send_data_upwards),
365 queue_up_end_(queue_up_end),
366 creation_time_(creation_time) {
367 queue_up_end_->RegisterDequeue(
368 handler_, common::Bind(&ShimAclConnection::data_ready_callback,
369 common::Unretained(this)));
370 }
371
~ShimAclConnection()372 virtual ~ShimAclConnection() {
373 if (!queue_.empty())
374 LOG_ERROR(
375 "ACL cleaned up with non-empty queue handle:0x%04x stranded_pkts:%zu",
376 handle_, queue_.size());
377 ASSERT_LOG(is_disconnected_,
378 "Shim Acl was not properly disconnected handle:0x%04x", handle_);
379 }
380
EnqueuePacket(std::unique_ptr<packet::RawBuilder> packet)381 void EnqueuePacket(std::unique_ptr<packet::RawBuilder> packet) {
382 // TODO Handle queue size exceeds some threshold
383 queue_.push(std::move(packet));
384 RegisterEnqueue();
385 }
386
handle_enqueue()387 std::unique_ptr<packet::BasePacketBuilder> handle_enqueue() {
388 auto packet = std::move(queue_.front());
389 queue_.pop();
390 if (queue_.empty()) {
391 UnregisterEnqueue();
392 }
393 return packet;
394 }
395
data_ready_callback()396 void data_ready_callback() {
397 auto packet = queue_up_end_->TryDequeue();
398 uint16_t length = packet->size();
399 std::vector<uint8_t> preamble;
400 preamble.push_back(LowByte(handle_));
401 preamble.push_back(HighByte(handle_));
402 preamble.push_back(LowByte(length));
403 preamble.push_back(HighByte(length));
404 BT_HDR* p_buf = MakeLegacyBtHdrPacket(std::move(packet), preamble);
405 ASSERT_LOG(p_buf != nullptr,
406 "Unable to allocate BT_HDR legacy packet handle:%04x", handle_);
407 if (send_data_upwards_ == nullptr) {
408 LOG_WARN("Dropping ACL data with no callback");
409 osi_free(p_buf);
410 } else if (do_in_main_thread(FROM_HERE,
411 base::Bind(send_data_upwards_, p_buf)) !=
412 BT_STATUS_SUCCESS) {
413 osi_free(p_buf);
414 }
415 }
416
417 virtual void InitiateDisconnect(hci::DisconnectReason reason) = 0;
418 virtual bool IsLocallyInitiated() const = 0;
419
GetCreationTime() const420 CreationTime GetCreationTime() const { return creation_time_; }
Handle() const421 uint16_t Handle() const { return handle_; }
422
Shutdown()423 void Shutdown() {
424 Disconnect();
425 LOG_INFO("Shutdown and disconnect ACL connection handle:0x%04x", handle_);
426 }
427
428 protected:
429 const uint16_t handle_{kInvalidHciHandle};
430 os::Handler* handler_;
431
UnregisterEnqueue()432 void UnregisterEnqueue() {
433 if (!is_enqueue_registered_) return;
434 is_enqueue_registered_ = false;
435 queue_up_end_->UnregisterEnqueue();
436 }
437
Disconnect()438 void Disconnect() {
439 if (is_disconnected_) {
440 LOG_ERROR(
441 "Cannot disconnect ACL multiple times handle:%04x creation_time:%s",
442 handle_,
443 common::StringFormatTimeWithMilliseconds(
444 kConnectionDescriptorTimeFormat, creation_time_)
445 .c_str());
446 return;
447 }
448 is_disconnected_ = true;
449 UnregisterEnqueue();
450 queue_up_end_->UnregisterDequeue();
451 if (!queue_.empty())
452 LOG_WARN(
453 "ACL disconnect with non-empty queue handle:%04x stranded_pkts::%zu",
454 handle_, queue_.size());
455 }
456
457 virtual void ReadRemoteControllerInformation() = 0;
458
459 private:
460 SendDataUpwards send_data_upwards_;
461 hci::acl_manager::AclConnection::QueueUpEnd* queue_up_end_;
462
463 std::queue<std::unique_ptr<packet::RawBuilder>> queue_;
464 bool is_enqueue_registered_{false};
465 bool is_disconnected_{false};
466 CreationTime creation_time_;
467
RegisterEnqueue()468 void RegisterEnqueue() {
469 ASSERT_LOG(!is_disconnected_,
470 "Unable to send data over disconnected channel handle:%04x",
471 handle_);
472 if (is_enqueue_registered_) return;
473 is_enqueue_registered_ = true;
474 queue_up_end_->RegisterEnqueue(
475 handler_, common::Bind(&ShimAclConnection::handle_enqueue,
476 common::Unretained(this)));
477 }
478
479 virtual void RegisterCallbacks() = 0;
480 };
481
482 class ClassicShimAclConnection
483 : public ShimAclConnection,
484 public hci::acl_manager::ConnectionManagementCallbacks {
485 public:
ClassicShimAclConnection(SendDataUpwards send_data_upwards,OnDisconnect on_disconnect,const shim::legacy::acl_classic_link_interface_t & interface,os::Handler * handler,std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection,CreationTime creation_time)486 ClassicShimAclConnection(
487 SendDataUpwards send_data_upwards, OnDisconnect on_disconnect,
488 const shim::legacy::acl_classic_link_interface_t& interface,
489 os::Handler* handler,
490 std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection,
491 CreationTime creation_time)
492 : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler,
493 connection->GetAclQueueEnd(), creation_time),
494 on_disconnect_(on_disconnect),
495 interface_(interface),
496 connection_(std::move(connection)) {}
497
RegisterCallbacks()498 void RegisterCallbacks() override {
499 connection_->RegisterCallbacks(this, handler_);
500 }
501
ReadRemoteControllerInformation()502 void ReadRemoteControllerInformation() override {
503 connection_->ReadRemoteVersionInformation();
504 connection_->ReadRemoteSupportedFeatures();
505 }
506
OnConnectionPacketTypeChanged(uint16_t packet_type)507 void OnConnectionPacketTypeChanged(uint16_t packet_type) override {
508 TRY_POSTING_ON_MAIN(interface_.on_packet_type_changed, packet_type);
509 }
510
OnAuthenticationComplete(hci::ErrorCode hci_status)511 void OnAuthenticationComplete(hci::ErrorCode hci_status) override {
512 TRY_POSTING_ON_MAIN(interface_.on_authentication_complete, handle_,
513 ToLegacyHciErrorCode(hci_status));
514 }
515
OnEncryptionChange(hci::EncryptionEnabled enabled)516 void OnEncryptionChange(hci::EncryptionEnabled enabled) override {
517 bool is_enabled = (enabled == hci::EncryptionEnabled::ON ||
518 enabled == hci::EncryptionEnabled::BR_EDR_AES_CCM);
519 TRY_POSTING_ON_MAIN(interface_.on_encryption_change, is_enabled);
520 }
521
OnChangeConnectionLinkKeyComplete()522 void OnChangeConnectionLinkKeyComplete() override {
523 TRY_POSTING_ON_MAIN(interface_.on_change_connection_link_key_complete);
524 }
525
OnReadClockOffsetComplete(uint16_t clock_offset)526 void OnReadClockOffsetComplete(uint16_t clock_offset) override {
527 LOG_INFO("UNIMPLEMENTED");
528 }
529
OnModeChange(hci::ErrorCode status,hci::Mode current_mode,uint16_t interval)530 void OnModeChange(hci::ErrorCode status, hci::Mode current_mode,
531 uint16_t interval) override {
532 TRY_POSTING_ON_MAIN(interface_.on_mode_change, ToLegacyHciErrorCode(status),
533 handle_, ToLegacyHciMode(current_mode), interval);
534 }
535
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)536 void OnSniffSubrating(hci::ErrorCode hci_status,
537 uint16_t maximum_transmit_latency,
538 uint16_t maximum_receive_latency,
539 uint16_t minimum_remote_timeout,
540 uint16_t minimum_local_timeout) {
541 TRY_POSTING_ON_MAIN(interface_.on_sniff_subrating,
542 ToLegacyHciErrorCode(hci_status), handle_,
543 maximum_transmit_latency, maximum_receive_latency,
544 minimum_remote_timeout, minimum_local_timeout);
545 }
546
OnQosSetupComplete(hci::ServiceType service_type,uint32_t token_rate,uint32_t peak_bandwidth,uint32_t latency,uint32_t delay_variation)547 void OnQosSetupComplete(hci::ServiceType service_type, uint32_t token_rate,
548 uint32_t peak_bandwidth, uint32_t latency,
549 uint32_t delay_variation) override {
550 LOG_INFO("UNIMPLEMENTED");
551 }
552
OnFlowSpecificationComplete(hci::FlowDirection flow_direction,hci::ServiceType service_type,uint32_t token_rate,uint32_t token_bucket_size,uint32_t peak_bandwidth,uint32_t access_latency)553 void OnFlowSpecificationComplete(hci::FlowDirection flow_direction,
554 hci::ServiceType service_type,
555 uint32_t token_rate,
556 uint32_t token_bucket_size,
557 uint32_t peak_bandwidth,
558 uint32_t access_latency) override {
559 LOG_INFO("UNIMPLEMENTED");
560 }
561
OnFlushOccurred()562 void OnFlushOccurred() override { LOG_INFO("UNIMPLEMENTED"); }
563
OnRoleDiscoveryComplete(hci::Role current_role)564 void OnRoleDiscoveryComplete(hci::Role current_role) override {
565 LOG_INFO("UNIMPLEMENTED");
566 }
567
OnReadLinkPolicySettingsComplete(uint16_t link_policy_settings)568 void OnReadLinkPolicySettingsComplete(
569 uint16_t link_policy_settings) override {
570 LOG_INFO("UNIMPLEMENTED");
571 }
572
OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout)573 void OnReadAutomaticFlushTimeoutComplete(uint16_t flush_timeout) override {
574 LOG_INFO("UNIMPLEMENTED");
575 }
576
OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level)577 void OnReadTransmitPowerLevelComplete(uint8_t transmit_power_level) override {
578 LOG_INFO("UNIMPLEMENTED");
579 }
580
OnReadLinkSupervisionTimeoutComplete(uint16_t link_supervision_timeout)581 void OnReadLinkSupervisionTimeoutComplete(
582 uint16_t link_supervision_timeout) override {
583 LOG_INFO("UNIMPLEMENTED");
584 }
585
OnReadFailedContactCounterComplete(uint16_t failed_contact_counter)586 void OnReadFailedContactCounterComplete(
587 uint16_t failed_contact_counter) override {
588 LOG_INFO("UNIMPLEMENTED");
589 }
590
OnReadLinkQualityComplete(uint8_t link_quality)591 void OnReadLinkQualityComplete(uint8_t link_quality) override {
592 LOG_INFO("UNIMPLEMENTED");
593 }
594
OnReadAfhChannelMapComplete(hci::AfhMode afh_mode,std::array<uint8_t,10> afh_channel_map)595 void OnReadAfhChannelMapComplete(
596 hci::AfhMode afh_mode, std::array<uint8_t, 10> afh_channel_map) override {
597 LOG_INFO("UNIMPLEMENTED");
598 }
599
OnReadRssiComplete(uint8_t rssi)600 void OnReadRssiComplete(uint8_t rssi) override { LOG_INFO("UNIMPLEMENTED"); }
601
OnReadClockComplete(uint32_t clock,uint16_t accuracy)602 void OnReadClockComplete(uint32_t clock, uint16_t accuracy) override {
603 LOG_INFO("UNIMPLEMENTED");
604 }
605
OnCentralLinkKeyComplete(hci::KeyFlag key_flag)606 void OnCentralLinkKeyComplete(hci::KeyFlag key_flag) override {
607 LOG_INFO("%s UNIMPLEMENTED", __func__);
608 }
609
OnRoleChange(hci::ErrorCode hci_status,hci::Role new_role)610 void OnRoleChange(hci::ErrorCode hci_status, hci::Role new_role) override {
611 TRY_POSTING_ON_MAIN(
612 interface_.on_role_change, ToLegacyHciErrorCode(hci_status),
613 ToRawAddress(connection_->GetAddress()), ToLegacyRole(new_role));
614 BTM_LogHistory(kBtmLogTag, ToRawAddress(connection_->GetAddress()),
615 "Role change",
616 base::StringPrintf("classic New_role:%s status:%s",
617 hci::RoleText(new_role).c_str(),
618 hci::ErrorCodeText(hci_status).c_str()));
619 }
620
OnDisconnection(hci::ErrorCode reason)621 void OnDisconnection(hci::ErrorCode reason) override {
622 Disconnect();
623 on_disconnect_(handle_, reason);
624 }
625
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)626 void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,
627 uint8_t lmp_version,
628 uint16_t manufacturer_name,
629 uint16_t sub_version) override {
630 TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete,
631 ToLegacyHciErrorCode(hci_status), handle_, lmp_version,
632 manufacturer_name, sub_version);
633 }
634
OnReadRemoteSupportedFeaturesComplete(uint64_t features)635 void OnReadRemoteSupportedFeaturesComplete(uint64_t features) override {
636 TRY_POSTING_ON_MAIN(interface_.on_read_remote_supported_features_complete,
637 handle_, features);
638
639 if (features & ((uint64_t(1) << 63))) {
640 connection_->ReadRemoteExtendedFeatures(1);
641 return;
642 }
643 LOG_DEBUG("Device does not support extended features");
644 }
645
OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,uint8_t max_page_number,uint64_t features)646 void OnReadRemoteExtendedFeaturesComplete(uint8_t page_number,
647 uint8_t max_page_number,
648 uint64_t features) override {
649 TRY_POSTING_ON_MAIN(interface_.on_read_remote_extended_features_complete,
650 handle_, page_number, max_page_number, features);
651
652 // Supported features aliases to extended features page 0
653 if (page_number == 0 && !(features & ((uint64_t(1) << 63)))) {
654 LOG_DEBUG("Device does not support extended features");
655 return;
656 }
657
658 if (max_page_number != 0 && page_number != max_page_number)
659 connection_->ReadRemoteExtendedFeatures(page_number + 1);
660 }
661
GetRemoteAddress() const662 hci::Address GetRemoteAddress() const { return connection_->GetAddress(); }
663
InitiateDisconnect(hci::DisconnectReason reason)664 void InitiateDisconnect(hci::DisconnectReason reason) override {
665 connection_->Disconnect(reason);
666 }
667
HoldMode(uint16_t max_interval,uint16_t min_interval)668 void HoldMode(uint16_t max_interval, uint16_t min_interval) {
669 ASSERT(connection_->HoldMode(max_interval, min_interval));
670 }
671
SniffMode(uint16_t max_interval,uint16_t min_interval,uint16_t attempt,uint16_t timeout)672 void SniffMode(uint16_t max_interval, uint16_t min_interval, uint16_t attempt,
673 uint16_t timeout) {
674 ASSERT(
675 connection_->SniffMode(max_interval, min_interval, attempt, timeout));
676 }
677
ExitSniffMode()678 void ExitSniffMode() { ASSERT(connection_->ExitSniffMode()); }
679
SniffSubrating(uint16_t maximum_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)680 void SniffSubrating(uint16_t maximum_latency, uint16_t minimum_remote_timeout,
681 uint16_t minimum_local_timeout) {
682 ASSERT(connection_->SniffSubrating(maximum_latency, minimum_remote_timeout,
683 minimum_local_timeout));
684 }
685
SetConnectionEncryption(hci::Enable is_encryption_enabled)686 void SetConnectionEncryption(hci::Enable is_encryption_enabled) {
687 ASSERT(connection_->SetConnectionEncryption(is_encryption_enabled));
688 }
689
IsLocallyInitiated() const690 bool IsLocallyInitiated() const override {
691 return connection_->locally_initiated_;
692 }
693
694 private:
695 OnDisconnect on_disconnect_;
696 const shim::legacy::acl_classic_link_interface_t interface_;
697 std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection_;
698 };
699
700 class LeShimAclConnection
701 : public ShimAclConnection,
702 public hci::acl_manager::LeConnectionManagementCallbacks {
703 public:
LeShimAclConnection(SendDataUpwards send_data_upwards,OnDisconnect on_disconnect,const shim::legacy::acl_le_link_interface_t & interface,os::Handler * handler,std::unique_ptr<hci::acl_manager::LeAclConnection> connection,std::chrono::time_point<std::chrono::system_clock> creation_time)704 LeShimAclConnection(
705 SendDataUpwards send_data_upwards, OnDisconnect on_disconnect,
706 const shim::legacy::acl_le_link_interface_t& interface,
707 os::Handler* handler,
708 std::unique_ptr<hci::acl_manager::LeAclConnection> connection,
709 std::chrono::time_point<std::chrono::system_clock> creation_time)
710 : ShimAclConnection(connection->GetHandle(), send_data_upwards, handler,
711 connection->GetAclQueueEnd(), creation_time),
712 on_disconnect_(on_disconnect),
713 interface_(interface),
714 connection_(std::move(connection)) {}
715
RegisterCallbacks()716 void RegisterCallbacks() override {
717 connection_->RegisterCallbacks(this, handler_);
718 }
719
ReadRemoteControllerInformation()720 void ReadRemoteControllerInformation() override {
721 // TODO Issue LeReadRemoteFeatures Command
722 }
723
GetLocalAddressWithType()724 bluetooth::hci::AddressWithType GetLocalAddressWithType() {
725 return connection_->GetLocalAddress();
726 }
727
OnConnectionUpdate(hci::ErrorCode hci_status,uint16_t connection_interval,uint16_t connection_latency,uint16_t supervision_timeout)728 void OnConnectionUpdate(hci::ErrorCode hci_status,
729 uint16_t connection_interval,
730 uint16_t connection_latency,
731 uint16_t supervision_timeout) {
732 TRY_POSTING_ON_MAIN(
733 interface_.on_connection_update, ToLegacyHciErrorCode(hci_status),
734 handle_, connection_interval, connection_latency, supervision_timeout);
735 }
OnDataLengthChange(uint16_t max_tx_octets,uint16_t max_tx_time,uint16_t max_rx_octets,uint16_t max_rx_time)736 void OnDataLengthChange(uint16_t max_tx_octets, uint16_t max_tx_time,
737 uint16_t max_rx_octets, uint16_t max_rx_time) {
738 TRY_POSTING_ON_MAIN(interface_.on_data_length_change, handle_,
739 max_tx_octets, max_tx_time, max_rx_octets, max_rx_time);
740 }
741
OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,uint8_t lmp_version,uint16_t manufacturer_name,uint16_t sub_version)742 void OnReadRemoteVersionInformationComplete(hci::ErrorCode hci_status,
743 uint8_t lmp_version,
744 uint16_t manufacturer_name,
745 uint16_t sub_version) override {
746 TRY_POSTING_ON_MAIN(interface_.on_read_remote_version_information_complete,
747 ToLegacyHciErrorCode(hci_status), handle_, lmp_version,
748 manufacturer_name, sub_version);
749 }
750
OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status,uint64_t features)751 void OnLeReadRemoteFeaturesComplete(hci::ErrorCode hci_status,
752 uint64_t features) {
753 // TODO
754 }
755
OnPhyUpdate(hci::ErrorCode hci_status,uint8_t tx_phy,uint8_t rx_phy)756 void OnPhyUpdate(hci::ErrorCode hci_status, uint8_t tx_phy,
757 uint8_t rx_phy) override {
758 if (common::init_flags::pass_phy_update_callback_is_enabled()) {
759 TRY_POSTING_ON_MAIN(
760 interface_.on_phy_update,
761 static_cast<tGATT_STATUS>(ToLegacyHciErrorCode(hci_status)), handle_,
762 tx_phy, rx_phy);
763 } else {
764 LOG_WARN(
765 "Not posting OnPhyUpdate callback since it is disabled: (tx:%x, "
766 "rx:%x, status:%s)",
767 tx_phy, rx_phy, hci::ErrorCodeText(hci_status).c_str());
768 }
769 }
770
OnLocalAddressUpdate(hci::AddressWithType address_with_type)771 void OnLocalAddressUpdate(hci::AddressWithType address_with_type) override {
772 connection_->UpdateLocalAddress(address_with_type);
773 }
774
OnDisconnection(hci::ErrorCode reason)775 void OnDisconnection(hci::ErrorCode reason) {
776 Disconnect();
777 on_disconnect_(handle_, reason);
778 }
779
GetRemoteAddressWithType() const780 hci::AddressWithType GetRemoteAddressWithType() const {
781 return connection_->GetRemoteAddress();
782 }
783
InitiateDisconnect(hci::DisconnectReason reason)784 void InitiateDisconnect(hci::DisconnectReason reason) override {
785 connection_->Disconnect(reason);
786 }
787
IsLocallyInitiated() const788 bool IsLocallyInitiated() const override {
789 return connection_->locally_initiated_;
790 }
791
IsInFilterAcceptList() const792 bool IsInFilterAcceptList() const {
793 return connection_->IsInFilterAcceptList();
794 }
795
796 private:
797 OnDisconnect on_disconnect_;
798 const shim::legacy::acl_le_link_interface_t interface_;
799 std::unique_ptr<hci::acl_manager::LeAclConnection> connection_;
800 };
801
802 struct shim::legacy::Acl::impl {
implshim::legacy::Acl::impl803 impl(uint8_t max_acceptlist_size, uint8_t max_address_resolution_size)
804 : shadow_acceptlist_(ShadowAcceptlist(max_acceptlist_size)),
805 shadow_address_resolution_list_(
806 ShadowAddressResolutionList(max_address_resolution_size)) {}
807
808 std::map<HciHandle, std::unique_ptr<ClassicShimAclConnection>>
809 handle_to_classic_connection_map_;
810 std::map<HciHandle, std::unique_ptr<LeShimAclConnection>>
811 handle_to_le_connection_map_;
812
813 SyncMapCount<std::string> classic_acl_disconnect_reason_;
814 SyncMapCount<std::string> le_acl_disconnect_reason_;
815
816 FixedQueue<std::unique_ptr<ConnectionDescriptor>> connection_history_ =
817 FixedQueue<std::unique_ptr<ConnectionDescriptor>>(kConnectionHistorySize);
818
819 ShadowAcceptlist shadow_acceptlist_;
820 ShadowAddressResolutionList shadow_address_resolution_list_;
821
IsClassicAclshim::legacy::Acl::impl822 bool IsClassicAcl(HciHandle handle) {
823 return handle_to_classic_connection_map_.find(handle) !=
824 handle_to_classic_connection_map_.end();
825 }
826
EnqueueClassicPacketshim::legacy::Acl::impl827 void EnqueueClassicPacket(HciHandle handle,
828 std::unique_ptr<packet::RawBuilder> packet) {
829 ASSERT_LOG(IsClassicAcl(handle), "handle %d is not a classic connection",
830 handle);
831 handle_to_classic_connection_map_[handle]->EnqueuePacket(std::move(packet));
832 }
833
IsLeAclshim::legacy::Acl::impl834 bool IsLeAcl(HciHandle handle) {
835 return handle_to_le_connection_map_.find(handle) !=
836 handle_to_le_connection_map_.end();
837 }
838
EnqueueLePacketshim::legacy::Acl::impl839 void EnqueueLePacket(HciHandle handle,
840 std::unique_ptr<packet::RawBuilder> packet) {
841 ASSERT_LOG(IsLeAcl(handle), "handle %d is not a LE connection", handle);
842 handle_to_le_connection_map_[handle]->EnqueuePacket(std::move(packet));
843 }
844
ShutdownClassicConnectionsshim::legacy::Acl::impl845 void ShutdownClassicConnections(std::promise<void> promise) {
846 LOG_INFO("Shutdown gd acl shim classic connections");
847 for (auto& connection : handle_to_classic_connection_map_) {
848 connection.second->Shutdown();
849 }
850 handle_to_classic_connection_map_.clear();
851 promise.set_value();
852 }
853
ShutdownLeConnectionsshim::legacy::Acl::impl854 void ShutdownLeConnections(std::promise<void> promise) {
855 LOG_INFO("Shutdown gd acl shim le connections");
856 for (auto& connection : handle_to_le_connection_map_) {
857 connection.second->Shutdown();
858 }
859 handle_to_le_connection_map_.clear();
860 promise.set_value();
861 }
862
FinalShutdownshim::legacy::Acl::impl863 void FinalShutdown(std::promise<void> promise) {
864 if (!handle_to_classic_connection_map_.empty()) {
865 for (auto& connection : handle_to_classic_connection_map_) {
866 connection.second->Shutdown();
867 }
868 handle_to_classic_connection_map_.clear();
869 LOG_INFO("Cleared all classic connections count:%zu",
870 handle_to_classic_connection_map_.size());
871 }
872
873 if (!handle_to_le_connection_map_.empty()) {
874 for (auto& connection : handle_to_le_connection_map_) {
875 connection.second->Shutdown();
876 }
877 handle_to_le_connection_map_.clear();
878 LOG_INFO("Cleared all le connections count:%zu",
879 handle_to_le_connection_map_.size());
880 }
881 promise.set_value();
882 }
883
HoldModeshim::legacy::Acl::impl884 void HoldMode(HciHandle handle, uint16_t max_interval,
885 uint16_t min_interval) {
886 ASSERT_LOG(IsClassicAcl(handle), "handle %d is not a classic connection",
887 handle);
888 handle_to_classic_connection_map_[handle]->HoldMode(max_interval,
889 min_interval);
890 }
891
ExitSniffModeshim::legacy::Acl::impl892 void ExitSniffMode(HciHandle handle) {
893 ASSERT_LOG(IsClassicAcl(handle), "handle %d is not a classic connection",
894 handle);
895 handle_to_classic_connection_map_[handle]->ExitSniffMode();
896 }
897
SniffModeshim::legacy::Acl::impl898 void SniffMode(HciHandle handle, uint16_t max_interval, uint16_t min_interval,
899 uint16_t attempt, uint16_t timeout) {
900 ASSERT_LOG(IsClassicAcl(handle), "handle %d is not a classic connection",
901 handle);
902 handle_to_classic_connection_map_[handle]->SniffMode(
903 max_interval, min_interval, attempt, timeout);
904 }
905
SniffSubratingshim::legacy::Acl::impl906 void SniffSubrating(HciHandle handle, uint16_t maximum_latency,
907 uint16_t minimum_remote_timeout,
908 uint16_t minimum_local_timeout) {
909 ASSERT_LOG(IsClassicAcl(handle), "handle %d is not a classic connection",
910 handle);
911 handle_to_classic_connection_map_[handle]->SniffSubrating(
912 maximum_latency, minimum_remote_timeout, minimum_local_timeout);
913 }
914
SetConnectionEncryptionshim::legacy::Acl::impl915 void SetConnectionEncryption(HciHandle handle, hci::Enable enable) {
916 ASSERT_LOG(IsClassicAcl(handle), "handle %d is not a classic connection",
917 handle);
918 handle_to_classic_connection_map_[handle]->SetConnectionEncryption(enable);
919 }
920
disconnect_classicshim::legacy::Acl::impl921 void disconnect_classic(uint16_t handle, tHCI_STATUS reason,
922 std::string comment) {
923 auto connection = handle_to_classic_connection_map_.find(handle);
924 if (connection != handle_to_classic_connection_map_.end()) {
925 auto remote_address = connection->second->GetRemoteAddress();
926 connection->second->InitiateDisconnect(
927 ToDisconnectReasonFromLegacy(reason));
928 LOG_DEBUG("Disconnection initiated classic remote:%s handle:%hu",
929 PRIVATE_ADDRESS(remote_address), handle);
930 BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address),
931 "Disconnection initiated",
932 base::StringPrintf("classic reason:%s comment:%s",
933 hci_status_code_text(reason).c_str(),
934 comment.c_str()));
935 classic_acl_disconnect_reason_.Put(comment);
936 } else {
937 LOG_WARN("Unable to disconnect unknown classic connection handle:0x%04x",
938 handle);
939 }
940 }
941
disconnect_leshim::legacy::Acl::impl942 void disconnect_le(uint16_t handle, tHCI_STATUS reason, std::string comment) {
943 auto connection = handle_to_le_connection_map_.find(handle);
944 if (connection != handle_to_le_connection_map_.end()) {
945 auto remote_address_with_type =
946 connection->second->GetRemoteAddressWithType();
947 GetAclManager()->RemoveFromBackgroundList(remote_address_with_type);
948 connection->second->InitiateDisconnect(
949 ToDisconnectReasonFromLegacy(reason));
950 LOG_DEBUG("Disconnection initiated le remote:%s handle:%hu",
951 PRIVATE_ADDRESS(remote_address_with_type), handle);
952 BTM_LogHistory(kBtmLogTag,
953 ToLegacyAddressWithType(remote_address_with_type),
954 "Disconnection initiated",
955 base::StringPrintf("Le reason:%s comment:%s",
956 hci_status_code_text(reason).c_str(),
957 comment.c_str()));
958 le_acl_disconnect_reason_.Put(comment);
959 } else {
960 LOG_WARN("Unable to disconnect unknown le connection handle:0x%04x",
961 handle);
962 }
963 }
964
accept_le_connection_fromshim::legacy::Acl::impl965 void accept_le_connection_from(const hci::AddressWithType& address_with_type,
966 bool is_direct, std::promise<bool> promise) {
967 if (shadow_acceptlist_.IsFull()) {
968 LOG_ERROR("Acceptlist is full preventing new Le connection");
969 promise.set_value(false);
970 return;
971 }
972 shadow_acceptlist_.Add(address_with_type);
973 promise.set_value(true);
974 GetAclManager()->CreateLeConnection(address_with_type, is_direct);
975 LOG_DEBUG("Allow Le connection from remote:%s",
976 PRIVATE_ADDRESS(address_with_type));
977 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
978 "Allow connection from", "Le");
979 }
980
ignore_le_connection_fromshim::legacy::Acl::impl981 void ignore_le_connection_from(
982 const hci::AddressWithType& address_with_type) {
983 shadow_acceptlist_.Remove(address_with_type);
984 GetAclManager()->CancelLeConnectAndRemoveFromBackgroundList(
985 address_with_type);
986 LOG_DEBUG("Ignore Le connection from remote:%s",
987 PRIVATE_ADDRESS(address_with_type));
988 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
989 "Ignore connection from", "Le");
990 }
991
clear_acceptlistshim::legacy::Acl::impl992 void clear_acceptlist() {
993 auto shadow_acceptlist = shadow_acceptlist_.GetCopy();
994 size_t count = shadow_acceptlist.size();
995 GetAclManager()->ClearFilterAcceptList();
996 shadow_acceptlist_.Clear();
997 LOG_DEBUG("Cleared entire Le address acceptlist count:%zu", count);
998 }
999
AddToAddressResolutionshim::legacy::Acl::impl1000 void AddToAddressResolution(const hci::AddressWithType& address_with_type,
1001 const std::array<uint8_t, 16>& peer_irk,
1002 const std::array<uint8_t, 16>& local_irk) {
1003 if (shadow_address_resolution_list_.IsFull()) {
1004 LOG_WARN("Le Address Resolution list is full size:%zu",
1005 shadow_address_resolution_list_.Size());
1006 return;
1007 }
1008 // TODO This should really be added upon successful completion
1009 shadow_address_resolution_list_.Add(address_with_type);
1010 GetAclManager()->AddDeviceToResolvingList(address_with_type, peer_irk,
1011 local_irk);
1012 }
1013
RemoveFromAddressResolutionshim::legacy::Acl::impl1014 void RemoveFromAddressResolution(
1015 const hci::AddressWithType& address_with_type) {
1016 // TODO This should really be removed upon successful removal
1017 if (!shadow_address_resolution_list_.Remove(address_with_type)) {
1018 LOG_WARN("Unable to remove from Le Address Resolution list device:%s",
1019 PRIVATE_ADDRESS(address_with_type));
1020 }
1021 GetAclManager()->RemoveDeviceFromResolvingList(address_with_type);
1022 }
1023
ClearResolvingListshim::legacy::Acl::impl1024 void ClearResolvingList() {
1025 GetAclManager()->ClearResolvingList();
1026 // TODO This should really be cleared after successful clear status
1027 shadow_address_resolution_list_.Clear();
1028 }
1029
DumpConnectionHistoryshim::legacy::Acl::impl1030 void DumpConnectionHistory() const {
1031 std::vector<std::string> history =
1032 connection_history_.ReadElementsAsString();
1033 for (auto& entry : history) {
1034 LOG_DEBUG("%s", entry.c_str());
1035 }
1036 const auto acceptlist = shadow_acceptlist_.GetCopy();
1037 LOG_DEBUG("Shadow le accept list size:%-3zu controller_max_size:%hhu",
1038 acceptlist.size(),
1039 controller_get_interface()->get_ble_acceptlist_size());
1040 for (auto& entry : acceptlist) {
1041 LOG_DEBUG("acceptlist:%s", entry.ToString().c_str());
1042 }
1043 }
1044
1045 #define DUMPSYS_TAG "shim::acl"
DumpConnectionHistoryshim::legacy::Acl::impl1046 void DumpConnectionHistory(int fd) const {
1047 std::vector<std::string> history =
1048 connection_history_.ReadElementsAsString();
1049 for (auto& entry : history) {
1050 LOG_DUMPSYS(fd, "%s", entry.c_str());
1051 }
1052 if (classic_acl_disconnect_reason_.Size() > 0) {
1053 LOG_DUMPSYS(fd, "Classic sources of initiated disconnects");
1054 for (const auto& item :
1055 classic_acl_disconnect_reason_.GetSortedHighToLow()) {
1056 LOG_DUMPSYS(fd, " %s:%zu", item.item.c_str(), item.count);
1057 }
1058 }
1059 if (le_acl_disconnect_reason_.Size() > 0) {
1060 LOG_DUMPSYS(fd, "Le sources of initiated disconnects");
1061 for (const auto& item : le_acl_disconnect_reason_.GetSortedHighToLow()) {
1062 LOG_DUMPSYS(fd, " %s:%zu", item.item.c_str(), item.count);
1063 }
1064 }
1065
1066 auto acceptlist = shadow_acceptlist_.GetCopy();
1067 LOG_DUMPSYS(fd,
1068 "Shadow le accept list size:%-3zu "
1069 "controller_max_size:%hhu",
1070 acceptlist.size(),
1071 controller_get_interface()->get_ble_acceptlist_size());
1072 unsigned cnt = 0;
1073 for (auto& entry : acceptlist) {
1074 LOG_DUMPSYS(fd, " %03u %s", ++cnt, entry.ToString().c_str());
1075 }
1076 auto address_resolution_list = shadow_address_resolution_list_.GetCopy();
1077 LOG_DUMPSYS(fd,
1078 "Shadow le address resolution list size:%-3zu "
1079 "controller_max_size:%hhu",
1080 address_resolution_list.size(),
1081 controller_get_interface()->get_ble_resolving_list_max_size());
1082 cnt = 0;
1083 for (auto& entry : address_resolution_list) {
1084 LOG_DUMPSYS(fd, " %03u %s", ++cnt, entry.ToString().c_str());
1085 }
1086 }
1087 #undef DUMPSYS_TAG
1088 };
1089
1090 #define DUMPSYS_TAG "shim::legacy::l2cap"
1091 extern tL2C_CB l2cb;
DumpsysL2cap(int fd)1092 void DumpsysL2cap(int fd) {
1093 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1094 for (int i = 0; i < MAX_L2CAP_LINKS; i++) {
1095 const tL2C_LCB& lcb = l2cb.lcb_pool[i];
1096 if (!lcb.in_use) continue;
1097 LOG_DUMPSYS(fd, "link_state:%s", link_state_text(lcb.link_state).c_str());
1098 LOG_DUMPSYS(fd, "handle:0x%04x", lcb.Handle());
1099
1100 const tL2C_CCB* ccb = lcb.ccb_queue.p_first_ccb;
1101 while (ccb != nullptr) {
1102 LOG_DUMPSYS(
1103 fd, " active channel lcid:0x%04x rcid:0x%04x is_ecoc:%s in_use:%s",
1104 ccb->local_cid, ccb->remote_cid, common::ToString(ccb->ecoc).c_str(),
1105 common::ToString(ccb->in_use).c_str());
1106 ccb = ccb->p_next_ccb;
1107 }
1108 }
1109 }
1110
1111 #undef DUMPSYS_TAG
1112 #define DUMPSYS_TAG "shim::legacy::acl"
DumpsysAcl(int fd)1113 void DumpsysAcl(int fd) {
1114 const tACL_CB& acl_cb = btm_cb.acl_cb_;
1115
1116 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1117
1118 if (shim::Stack::GetInstance()->IsRunning()) {
1119 shim::Stack::GetInstance()->GetAcl()->DumpConnectionHistory(fd);
1120 }
1121
1122 for (int i = 0; i < MAX_L2CAP_LINKS; i++) {
1123 const tACL_CONN& link = acl_cb.acl_db[i];
1124 if (!link.in_use) continue;
1125
1126 LOG_DUMPSYS(fd, "remote_addr:%s handle:0x%04x transport:%s",
1127 link.remote_addr.ToString().c_str(), link.hci_handle,
1128 bt_transport_text(link.transport).c_str());
1129 LOG_DUMPSYS(fd, " link_up_issued:%5s",
1130 (link.link_up_issued) ? "true" : "false");
1131 LOG_DUMPSYS(fd, " flush_timeout:0x%04x", link.flush_timeout_in_ticks);
1132 LOG_DUMPSYS(fd, " link_supervision_timeout:%.3f sec",
1133 ticks_to_seconds(link.link_super_tout));
1134 LOG_DUMPSYS(fd, " disconnect_reason:0x%02x", link.disconnect_reason);
1135
1136 if (link.is_transport_br_edr()) {
1137 for (int j = 0; j < HCI_EXT_FEATURES_PAGE_MAX + 1; j++) {
1138 if (!link.peer_lmp_feature_valid[j]) continue;
1139 LOG_DUMPSYS(fd, " peer_lmp_features[%d] valid:%s data:%s", j,
1140 common::ToString(link.peer_lmp_feature_valid[j]).c_str(),
1141 bd_features_text(link.peer_lmp_feature_pages[j]).c_str());
1142 }
1143 LOG_DUMPSYS(fd, " [classic] link_policy:%s",
1144 link_policy_text(static_cast<tLINK_POLICY>(link.link_policy))
1145 .c_str());
1146 LOG_DUMPSYS(fd, " [classic] sniff_subrating:%s",
1147 common::ToString(HCI_SNIFF_SUB_RATE_SUPPORTED(
1148 link.peer_lmp_feature_pages[0]))
1149 .c_str());
1150
1151 LOG_DUMPSYS(fd, " pkt_types_mask:0x%04x", link.pkt_types_mask);
1152 LOG_DUMPSYS(fd, " role:%s", RoleText(link.link_role).c_str());
1153 } else if (link.is_transport_ble()) {
1154 LOG_DUMPSYS(fd, " [le] peer_features valid:%s data:%s",
1155 common::ToString(link.peer_le_features_valid).c_str(),
1156 bd_features_text(link.peer_le_features).c_str());
1157
1158 LOG_DUMPSYS(fd, " [le] active_remote_addr:%s[%s]",
1159 link.active_remote_addr.ToString().c_str(),
1160 AddressTypeText(link.active_remote_addr_type).c_str());
1161 LOG_DUMPSYS(fd, " [le] conn_addr:%s[%s]",
1162 link.conn_addr.ToString().c_str(),
1163 AddressTypeText(link.conn_addr_type).c_str());
1164 }
1165 }
1166 }
1167 #undef DUMPSYS_TAG
1168
1169 using Record = common::TimestampedEntry<std::string>;
1170 const std::string kTimeFormat("%Y-%m-%d %H:%M:%S");
1171
1172 #define DUMPSYS_TAG "shim::legacy::hid"
1173 extern btif_hh_cb_t btif_hh_cb;
1174
DumpsysHid(int fd)1175 void DumpsysHid(int fd) {
1176 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1177 LOG_DUMPSYS(fd, "status:%s num_devices:%u",
1178 btif_hh_status_text(btif_hh_cb.status).c_str(),
1179 btif_hh_cb.device_num);
1180 LOG_DUMPSYS(fd, "status:%s", btif_hh_status_text(btif_hh_cb.status).c_str());
1181 for (unsigned i = 0; i < BTIF_HH_MAX_HID; i++) {
1182 const btif_hh_device_t* p_dev = &btif_hh_cb.devices[i];
1183 if (p_dev->bd_addr != RawAddress::kEmpty) {
1184 LOG_DUMPSYS(fd, " %u: addr:%s fd:%d state:%s ready:%s thread_id:%d", i,
1185 PRIVATE_ADDRESS(p_dev->bd_addr), p_dev->fd,
1186 bthh_connection_state_text(p_dev->dev_status).c_str(),
1187 (p_dev->ready_for_data) ? ("T") : ("F"),
1188 static_cast<int>(p_dev->hh_poll_thread_id));
1189 }
1190 }
1191 for (unsigned i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) {
1192 const btif_hh_added_device_t* p_dev = &btif_hh_cb.added_devices[i];
1193 if (p_dev->bd_addr != RawAddress::kEmpty) {
1194 LOG_DUMPSYS(fd, " %u: addr:%s", i, PRIVATE_ADDRESS(p_dev->bd_addr));
1195 }
1196 }
1197 }
1198 #undef DUMPSYS_TAG
1199
1200 #define DUMPSYS_TAG "shim::legacy::btm"
DumpsysBtm(int fd)1201 void DumpsysBtm(int fd) {
1202 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1203 if (btm_cb.history_ != nullptr) {
1204 std::vector<Record> history = btm_cb.history_->Pull();
1205 for (auto& record : history) {
1206 time_t then = record.timestamp / 1000;
1207 struct tm tm;
1208 localtime_r(&then, &tm);
1209 auto s2 = common::StringFormatTime(kTimeFormat, tm);
1210 LOG_DUMPSYS(fd, " %s.%03u %s", s2.c_str(),
1211 static_cast<unsigned int>(record.timestamp % 1000),
1212 record.entry.c_str());
1213 }
1214 }
1215 }
1216 #undef DUMPSYS_TAG
1217
1218 #define DUMPSYS_TAG "shim::legacy::record"
DumpsysRecord(int fd)1219 void DumpsysRecord(int fd) {
1220 LOG_DUMPSYS_TITLE(fd, DUMPSYS_TAG);
1221
1222 if (btm_cb.sec_dev_rec == nullptr) {
1223 LOG_DUMPSYS(fd, "Record is empty - no devices");
1224 return;
1225 }
1226
1227 unsigned cnt = 0;
1228 list_node_t* end = list_end(btm_cb.sec_dev_rec);
1229 for (list_node_t* node = list_begin(btm_cb.sec_dev_rec); node != end;
1230 node = list_next(node)) {
1231 tBTM_SEC_DEV_REC* p_dev_rec =
1232 static_cast<tBTM_SEC_DEV_REC*>(list_node(node));
1233 LOG_DUMPSYS(fd, "%03u %s", ++cnt, p_dev_rec->ToString().c_str());
1234 }
1235 }
1236 #undef DUMPSYS_TAG
1237
Dump(int fd) const1238 void shim::legacy::Acl::Dump(int fd) const {
1239 PAN_Dumpsys(fd);
1240 DumpsysHid(fd);
1241 DumpsysRecord(fd);
1242 DumpsysAcl(fd);
1243 DumpsysL2cap(fd);
1244 DumpsysBtm(fd);
1245 }
1246
Acl(os::Handler * handler,const acl_interface_t & acl_interface,uint8_t max_acceptlist_size,uint8_t max_address_resolution_size)1247 shim::legacy::Acl::Acl(os::Handler* handler,
1248 const acl_interface_t& acl_interface,
1249 uint8_t max_acceptlist_size,
1250 uint8_t max_address_resolution_size)
1251 : handler_(handler), acl_interface_(acl_interface) {
1252 ASSERT(handler_ != nullptr);
1253 ValidateAclInterface(acl_interface_);
1254 pimpl_ = std::make_unique<Acl::impl>(max_acceptlist_size,
1255 max_address_resolution_size);
1256 GetAclManager()->RegisterCallbacks(this, handler_);
1257 GetAclManager()->RegisterLeCallbacks(this, handler_);
1258 GetController()->RegisterCompletedMonitorAclPacketsCallback(
1259 handler->BindOn(this, &Acl::on_incoming_acl_credits));
1260 shim::RegisterDumpsysFunction(static_cast<void*>(this),
1261 [this](int fd) { Dump(fd); });
1262
1263 GetAclManager()->HACK_SetNonAclDisconnectCallback(
1264 [this](uint16_t handle, uint8_t reason) {
1265 TRY_POSTING_ON_MAIN(acl_interface_.connection.sco.on_disconnected,
1266 handle, static_cast<tHCI_REASON>(reason));
1267
1268 // HACKCEPTION! LE ISO connections, just like SCO are not registered in
1269 // GD, so ISO can use same hack to get notified about disconnections
1270 TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_iso_disconnected,
1271 handle, static_cast<tHCI_REASON>(reason));
1272 });
1273 }
1274
~Acl()1275 shim::legacy::Acl::~Acl() {
1276 shim::UnregisterDumpsysFunction(static_cast<void*>(this));
1277 GetController()->UnregisterCompletedMonitorAclPacketsCallback();
1278
1279 if (CheckForOrphanedAclConnections()) {
1280 pimpl_->DumpConnectionHistory();
1281 }
1282 }
1283
CheckForOrphanedAclConnections() const1284 bool shim::legacy::Acl::CheckForOrphanedAclConnections() const {
1285 bool orphaned_acl_connections = false;
1286
1287 if (!pimpl_->handle_to_classic_connection_map_.empty()) {
1288 LOG_ERROR("About to destroy classic active ACL");
1289 for (const auto& connection : pimpl_->handle_to_classic_connection_map_) {
1290 LOG_ERROR(" Orphaned classic ACL handle:0x%04x bd_addr:%s created:%s",
1291 connection.second->Handle(),
1292 PRIVATE_ADDRESS(connection.second->GetRemoteAddress()),
1293 common::StringFormatTimeWithMilliseconds(
1294 kConnectionDescriptorTimeFormat,
1295 connection.second->GetCreationTime())
1296 .c_str());
1297 }
1298 orphaned_acl_connections = true;
1299 }
1300
1301 if (!pimpl_->handle_to_le_connection_map_.empty()) {
1302 LOG_ERROR("About to destroy le active ACL");
1303 for (const auto& connection : pimpl_->handle_to_le_connection_map_) {
1304 LOG_ERROR(" Orphaned le ACL handle:0x%04x bd_addr:%s created:%s",
1305 connection.second->Handle(),
1306 PRIVATE_ADDRESS(connection.second->GetRemoteAddressWithType()),
1307 common::StringFormatTimeWithMilliseconds(
1308 kConnectionDescriptorTimeFormat,
1309 connection.second->GetCreationTime())
1310 .c_str());
1311 }
1312 orphaned_acl_connections = true;
1313 }
1314 return orphaned_acl_connections;
1315 }
1316
on_incoming_acl_credits(uint16_t handle,uint16_t credits)1317 void shim::legacy::Acl::on_incoming_acl_credits(uint16_t handle,
1318 uint16_t credits) {
1319 TRY_POSTING_ON_MAIN(acl_interface_.on_packets_completed, handle, credits);
1320 }
1321
write_data_sync(HciHandle handle,std::unique_ptr<packet::RawBuilder> packet)1322 void shim::legacy::Acl::write_data_sync(
1323 HciHandle handle, std::unique_ptr<packet::RawBuilder> packet) {
1324 if (pimpl_->IsClassicAcl(handle)) {
1325 pimpl_->EnqueueClassicPacket(handle, std::move(packet));
1326 } else if (pimpl_->IsLeAcl(handle)) {
1327 pimpl_->EnqueueLePacket(handle, std::move(packet));
1328 } else {
1329 LOG_ERROR("Unable to find destination to write data\n");
1330 }
1331 }
1332
WriteData(HciHandle handle,std::unique_ptr<packet::RawBuilder> packet)1333 void shim::legacy::Acl::WriteData(HciHandle handle,
1334 std::unique_ptr<packet::RawBuilder> packet) {
1335 handler_->Post(common::BindOnce(&Acl::write_data_sync,
1336 common::Unretained(this), handle,
1337 std::move(packet)));
1338 }
1339
CreateClassicConnection(const hci::Address & address)1340 void shim::legacy::Acl::CreateClassicConnection(const hci::Address& address) {
1341 GetAclManager()->CreateConnection(address);
1342 LOG_DEBUG("Connection initiated for classic to remote:%s",
1343 PRIVATE_ADDRESS(address));
1344 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Initiated connection",
1345 "classic");
1346 }
1347
CancelClassicConnection(const hci::Address & address)1348 void shim::legacy::Acl::CancelClassicConnection(const hci::Address& address) {
1349 GetAclManager()->CancelConnect(address);
1350 LOG_DEBUG("Connection cancelled for classic to remote:%s",
1351 PRIVATE_ADDRESS(address));
1352 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Cancelled connection",
1353 "classic");
1354 }
1355
AcceptLeConnectionFrom(const hci::AddressWithType & address_with_type,bool is_direct,std::promise<bool> promise)1356 void shim::legacy::Acl::AcceptLeConnectionFrom(
1357 const hci::AddressWithType& address_with_type, bool is_direct,
1358 std::promise<bool> promise) {
1359 LOG_DEBUG("AcceptLeConnectionFrom %s",
1360 PRIVATE_ADDRESS(address_with_type.GetAddress()));
1361 handler_->CallOn(pimpl_.get(), &Acl::impl::accept_le_connection_from,
1362 address_with_type, is_direct, std::move(promise));
1363 }
1364
IgnoreLeConnectionFrom(const hci::AddressWithType & address_with_type)1365 void shim::legacy::Acl::IgnoreLeConnectionFrom(
1366 const hci::AddressWithType& address_with_type) {
1367 LOG_DEBUG("IgnoreLeConnectionFrom %s",
1368 PRIVATE_ADDRESS(address_with_type.GetAddress()));
1369 handler_->CallOn(pimpl_.get(), &Acl::impl::ignore_le_connection_from,
1370 address_with_type);
1371 }
1372
OnClassicLinkDisconnected(HciHandle handle,hci::ErrorCode reason)1373 void shim::legacy::Acl::OnClassicLinkDisconnected(HciHandle handle,
1374 hci::ErrorCode reason) {
1375 hci::Address remote_address =
1376 pimpl_->handle_to_classic_connection_map_[handle]->GetRemoteAddress();
1377 CreationTime creation_time =
1378 pimpl_->handle_to_classic_connection_map_[handle]->GetCreationTime();
1379 bool is_locally_initiated =
1380 pimpl_->handle_to_classic_connection_map_[handle]->IsLocallyInitiated();
1381
1382 TeardownTime teardown_time = std::chrono::system_clock::now();
1383
1384 pimpl_->handle_to_classic_connection_map_.erase(handle);
1385 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_disconnected,
1386 ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
1387 ToLegacyHciErrorCode(reason));
1388 LOG_DEBUG("Disconnected classic link remote:%s handle:%hu reason:%s",
1389 PRIVATE_ADDRESS(remote_address), handle,
1390 ErrorCodeText(reason).c_str());
1391 BTM_LogHistory(
1392 kBtmLogTag, ToRawAddress(remote_address), "Disconnected",
1393 base::StringPrintf("classic reason:%s", ErrorCodeText(reason).c_str()));
1394 pimpl_->connection_history_.Push(
1395 std::move(std::make_unique<ClassicConnectionDescriptor>(
1396 remote_address, creation_time, teardown_time, handle,
1397 is_locally_initiated, reason)));
1398 }
1399
GetConnectionLocalAddress(const RawAddress & remote_bda)1400 bluetooth::hci::AddressWithType shim::legacy::Acl::GetConnectionLocalAddress(
1401 const RawAddress& remote_bda) {
1402 bluetooth::hci::AddressWithType address_with_type;
1403 auto remote_address = ToGdAddress(remote_bda);
1404 for (auto& [handle, connection] : pimpl_->handle_to_le_connection_map_) {
1405 if (connection->GetRemoteAddressWithType().GetAddress() == remote_address) {
1406 return connection->GetLocalAddressWithType();
1407 }
1408 }
1409 LOG_WARN("address not found!");
1410 return address_with_type;
1411 }
1412
OnLeLinkDisconnected(HciHandle handle,hci::ErrorCode reason)1413 void shim::legacy::Acl::OnLeLinkDisconnected(HciHandle handle,
1414 hci::ErrorCode reason) {
1415 hci::AddressWithType remote_address_with_type =
1416 pimpl_->handle_to_le_connection_map_[handle]->GetRemoteAddressWithType();
1417 CreationTime creation_time =
1418 pimpl_->handle_to_le_connection_map_[handle]->GetCreationTime();
1419 bool is_locally_initiated =
1420 pimpl_->handle_to_le_connection_map_[handle]->IsLocallyInitiated();
1421
1422 TeardownTime teardown_time = std::chrono::system_clock::now();
1423
1424 pimpl_->handle_to_le_connection_map_.erase(handle);
1425 TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_disconnected,
1426 ToLegacyHciErrorCode(hci::ErrorCode::SUCCESS), handle,
1427 ToLegacyHciErrorCode(reason));
1428 LOG_DEBUG("Disconnected le link remote:%s handle:%hu reason:%s",
1429 PRIVATE_ADDRESS(remote_address_with_type), handle,
1430 ErrorCodeText(reason).c_str());
1431 BTM_LogHistory(
1432 kBtmLogTag, ToLegacyAddressWithType(remote_address_with_type),
1433 "Disconnected",
1434 base::StringPrintf("Le reason:%s", ErrorCodeText(reason).c_str()));
1435 pimpl_->connection_history_.Push(
1436 std::move(std::make_unique<LeConnectionDescriptor>(
1437 remote_address_with_type, creation_time, teardown_time, handle,
1438 is_locally_initiated, reason)));
1439 }
1440
OnConnectSuccess(std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection)1441 void shim::legacy::Acl::OnConnectSuccess(
1442 std::unique_ptr<hci::acl_manager::ClassicAclConnection> connection) {
1443 ASSERT(connection != nullptr);
1444 auto handle = connection->GetHandle();
1445 bool locally_initiated = connection->locally_initiated_;
1446 const hci::Address remote_address = connection->GetAddress();
1447 const RawAddress bd_addr = ToRawAddress(remote_address);
1448
1449 pimpl_->handle_to_classic_connection_map_.emplace(
1450 handle, std::make_unique<ClassicShimAclConnection>(
1451 acl_interface_.on_send_data_upwards,
1452 std::bind(&shim::legacy::Acl::OnClassicLinkDisconnected, this,
1453 std::placeholders::_1, std::placeholders::_2),
1454 acl_interface_.link.classic, handler_, std::move(connection),
1455 std::chrono::system_clock::now()));
1456 pimpl_->handle_to_classic_connection_map_[handle]->RegisterCallbacks();
1457 pimpl_->handle_to_classic_connection_map_[handle]
1458 ->ReadRemoteControllerInformation();
1459
1460 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_connected, bd_addr,
1461 handle, false);
1462 LOG_DEBUG("Connection successful classic remote:%s handle:%hu initiator:%s",
1463 PRIVATE_ADDRESS(remote_address), handle,
1464 (locally_initiated) ? "local" : "remote");
1465 BTM_LogHistory(kBtmLogTag, ToRawAddress(remote_address),
1466 "Connection successful",
1467 (locally_initiated) ? "classic Local initiated"
1468 : "classic Remote initiated");
1469 }
1470
OnConnectFail(hci::Address address,hci::ErrorCode reason)1471 void shim::legacy::Acl::OnConnectFail(hci::Address address,
1472 hci::ErrorCode reason) {
1473 const RawAddress bd_addr = ToRawAddress(address);
1474 TRY_POSTING_ON_MAIN(acl_interface_.connection.classic.on_failed, bd_addr,
1475 ToLegacyHciErrorCode(reason));
1476 LOG_WARN("Connection failed classic remote:%s reason:%s",
1477 PRIVATE_ADDRESS(address), hci::ErrorCodeText(reason).c_str());
1478 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "Connection failed",
1479 base::StringPrintf("classic reason:%s",
1480 hci::ErrorCodeText(reason).c_str()));
1481 }
1482
HACK_OnEscoConnectRequest(hci::Address address,hci::ClassOfDevice cod)1483 void shim::legacy::Acl::HACK_OnEscoConnectRequest(hci::Address address,
1484 hci::ClassOfDevice cod) {
1485 const RawAddress bd_addr = ToRawAddress(address);
1486 types::ClassOfDevice legacy_cod;
1487 types::ClassOfDevice::FromString(cod.ToLegacyConfigString(), legacy_cod);
1488
1489 TRY_POSTING_ON_MAIN(acl_interface_.connection.sco.on_esco_connect_request,
1490 bd_addr, legacy_cod);
1491 LOG_DEBUG("Received ESCO connect request remote:%s",
1492 PRIVATE_ADDRESS(address));
1493 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "ESCO Connection request");
1494 }
1495
HACK_OnScoConnectRequest(hci::Address address,hci::ClassOfDevice cod)1496 void shim::legacy::Acl::HACK_OnScoConnectRequest(hci::Address address,
1497 hci::ClassOfDevice cod) {
1498 const RawAddress bd_addr = ToRawAddress(address);
1499 types::ClassOfDevice legacy_cod;
1500 types::ClassOfDevice::FromString(cod.ToLegacyConfigString(), legacy_cod);
1501
1502 TRY_POSTING_ON_MAIN(acl_interface_.connection.sco.on_sco_connect_request,
1503 bd_addr, legacy_cod);
1504 LOG_DEBUG("Received SCO connect request remote:%s", PRIVATE_ADDRESS(address));
1505 BTM_LogHistory(kBtmLogTag, ToRawAddress(address), "SCO Connection request");
1506 }
1507
OnLeConnectSuccess(hci::AddressWithType address_with_type,std::unique_ptr<hci::acl_manager::LeAclConnection> connection)1508 void shim::legacy::Acl::OnLeConnectSuccess(
1509 hci::AddressWithType address_with_type,
1510 std::unique_ptr<hci::acl_manager::LeAclConnection> connection) {
1511 ASSERT(connection != nullptr);
1512 auto handle = connection->GetHandle();
1513
1514 // Save the peer address, if any
1515 hci::AddressWithType peer_address_with_type =
1516 connection->peer_address_with_type_;
1517
1518 hci::Role connection_role = connection->GetRole();
1519 bool locally_initiated = connection->locally_initiated_;
1520
1521 uint16_t conn_interval = connection->interval_;
1522 uint16_t conn_latency = connection->latency_;
1523 uint16_t conn_timeout = connection->supervision_timeout_;
1524
1525 RawAddress local_rpa =
1526 ToRawAddress(connection->local_resolvable_private_address_);
1527 RawAddress peer_rpa =
1528 ToRawAddress(connection->peer_resolvable_private_address_);
1529 tBLE_ADDR_TYPE peer_addr_type =
1530 (tBLE_ADDR_TYPE)connection->peer_address_with_type_.GetAddressType();
1531
1532 pimpl_->handle_to_le_connection_map_.emplace(
1533 handle, std::make_unique<LeShimAclConnection>(
1534 acl_interface_.on_send_data_upwards,
1535 std::bind(&shim::legacy::Acl::OnLeLinkDisconnected, this,
1536 std::placeholders::_1, std::placeholders::_2),
1537 acl_interface_.link.le, handler_, std::move(connection),
1538 std::chrono::system_clock::now()));
1539 pimpl_->handle_to_le_connection_map_[handle]->RegisterCallbacks();
1540
1541 // Once an le connection has successfully been established
1542 // the device address is removed from the controller accept list.
1543
1544 if (IsRpa(address_with_type)) {
1545 LOG_DEBUG("Connection address is rpa:%s identity_addr:%s",
1546 PRIVATE_ADDRESS(address_with_type),
1547 PRIVATE_ADDRESS(peer_address_with_type));
1548 pimpl_->shadow_acceptlist_.Remove(peer_address_with_type);
1549 } else {
1550 LOG_DEBUG("Connection address is not rpa addr:%s",
1551 PRIVATE_ADDRESS(address_with_type));
1552 pimpl_->shadow_acceptlist_.Remove(address_with_type);
1553 }
1554
1555 if (!pimpl_->handle_to_le_connection_map_[handle]->IsInFilterAcceptList() &&
1556 connection_role == hci::Role::CENTRAL) {
1557 pimpl_->handle_to_le_connection_map_[handle]->InitiateDisconnect(
1558 hci::DisconnectReason::REMOTE_USER_TERMINATED_CONNECTION);
1559 LOG_INFO("Disconnected ACL after connection canceled");
1560 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1561 "Connection canceled", "Le");
1562 return;
1563 }
1564
1565 pimpl_->handle_to_le_connection_map_[handle]
1566 ->ReadRemoteControllerInformation();
1567
1568 tBLE_BD_ADDR legacy_address_with_type =
1569 ToLegacyAddressWithType(address_with_type);
1570
1571 TRY_POSTING_ON_MAIN(
1572 acl_interface_.connection.le.on_connected, legacy_address_with_type,
1573 handle, ToLegacyRole(connection_role), conn_interval, conn_latency,
1574 conn_timeout, local_rpa, peer_rpa, peer_addr_type);
1575
1576 LOG_DEBUG("Connection successful le remote:%s handle:%hu initiator:%s",
1577 PRIVATE_ADDRESS(address_with_type), handle,
1578 (locally_initiated) ? "local" : "remote");
1579 BTM_LogHistory(kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1580 "Connection successful", "Le");
1581 }
1582
OnLeConnectFail(hci::AddressWithType address_with_type,hci::ErrorCode reason)1583 void shim::legacy::Acl::OnLeConnectFail(hci::AddressWithType address_with_type,
1584 hci::ErrorCode reason) {
1585 tBLE_BD_ADDR legacy_address_with_type =
1586 ToLegacyAddressWithType(address_with_type);
1587
1588 uint16_t handle = 0; /* TODO Unneeded */
1589 bool enhanced = true; /* TODO logging metrics only */
1590 tHCI_STATUS status = ToLegacyHciErrorCode(reason);
1591
1592 pimpl_->shadow_acceptlist_.Remove(address_with_type);
1593
1594 TRY_POSTING_ON_MAIN(acl_interface_.connection.le.on_failed,
1595 legacy_address_with_type, handle, enhanced, status);
1596 LOG_WARN("Connection failed le remote:%s",
1597 PRIVATE_ADDRESS(address_with_type));
1598 BTM_LogHistory(
1599 kBtmLogTag, ToLegacyAddressWithType(address_with_type),
1600 "Connection failed",
1601 base::StringPrintf("le reason:%s", hci::ErrorCodeText(reason).c_str()));
1602 }
1603
DisconnectClassic(uint16_t handle,tHCI_STATUS reason,std::string comment)1604 void shim::legacy::Acl::DisconnectClassic(uint16_t handle, tHCI_STATUS reason,
1605 std::string comment) {
1606 handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_classic, handle, reason,
1607 comment);
1608 }
1609
DisconnectLe(uint16_t handle,tHCI_STATUS reason,std::string comment)1610 void shim::legacy::Acl::DisconnectLe(uint16_t handle, tHCI_STATUS reason,
1611 std::string comment) {
1612 handler_->CallOn(pimpl_.get(), &Acl::impl::disconnect_le, handle, reason,
1613 comment);
1614 }
1615
HoldMode(uint16_t hci_handle,uint16_t max_interval,uint16_t min_interval)1616 bool shim::legacy::Acl::HoldMode(uint16_t hci_handle, uint16_t max_interval,
1617 uint16_t min_interval) {
1618 handler_->CallOn(pimpl_.get(), &Acl::impl::HoldMode, hci_handle, max_interval,
1619 min_interval);
1620 return false; // TODO void
1621 }
1622
SniffMode(uint16_t hci_handle,uint16_t max_interval,uint16_t min_interval,uint16_t attempt,uint16_t timeout)1623 bool shim::legacy::Acl::SniffMode(uint16_t hci_handle, uint16_t max_interval,
1624 uint16_t min_interval, uint16_t attempt,
1625 uint16_t timeout) {
1626 handler_->CallOn(pimpl_.get(), &Acl::impl::SniffMode, hci_handle,
1627 max_interval, min_interval, attempt, timeout);
1628 return false;
1629 }
1630
ExitSniffMode(uint16_t hci_handle)1631 bool shim::legacy::Acl::ExitSniffMode(uint16_t hci_handle) {
1632 handler_->CallOn(pimpl_.get(), &Acl::impl::ExitSniffMode, hci_handle);
1633 return false;
1634 }
1635
SniffSubrating(uint16_t hci_handle,uint16_t maximum_latency,uint16_t minimum_remote_timeout,uint16_t minimum_local_timeout)1636 bool shim::legacy::Acl::SniffSubrating(uint16_t hci_handle,
1637 uint16_t maximum_latency,
1638 uint16_t minimum_remote_timeout,
1639 uint16_t minimum_local_timeout) {
1640 handler_->CallOn(pimpl_.get(), &Acl::impl::SniffSubrating, hci_handle,
1641 maximum_latency, minimum_remote_timeout,
1642 minimum_local_timeout);
1643 return false;
1644 }
1645
DumpConnectionHistory(int fd) const1646 void shim::legacy::Acl::DumpConnectionHistory(int fd) const {
1647 pimpl_->DumpConnectionHistory(fd);
1648 }
1649
Shutdown()1650 void shim::legacy::Acl::Shutdown() {
1651 if (CheckForOrphanedAclConnections()) {
1652 std::promise<void> shutdown_promise;
1653 auto shutdown_future = shutdown_promise.get_future();
1654 handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownClassicConnections,
1655 std::move(shutdown_promise));
1656 shutdown_future.wait();
1657
1658 shutdown_promise = std::promise<void>();
1659
1660 shutdown_future = shutdown_promise.get_future();
1661 handler_->CallOn(pimpl_.get(), &Acl::impl::ShutdownLeConnections,
1662 std::move(shutdown_promise));
1663 shutdown_future.wait();
1664 LOG_WARN("Flushed open ACL connections");
1665 } else {
1666 LOG_INFO("All ACL connections have been previously closed");
1667 }
1668 }
1669
FinalShutdown()1670 void shim::legacy::Acl::FinalShutdown() {
1671 std::promise<void> promise;
1672 auto future = promise.get_future();
1673 GetAclManager()->UnregisterCallbacks(this, std::move(promise));
1674 future.wait();
1675 LOG_DEBUG("Unregistered classic callbacks from gd acl manager");
1676
1677 promise = std::promise<void>();
1678 future = promise.get_future();
1679 GetAclManager()->UnregisterLeCallbacks(this, std::move(promise));
1680 future.wait();
1681 LOG_DEBUG("Unregistered le callbacks from gd acl manager");
1682
1683 promise = std::promise<void>();
1684 future = promise.get_future();
1685 handler_->CallOn(pimpl_.get(), &Acl::impl::FinalShutdown, std::move(promise));
1686 future.wait();
1687 LOG_INFO("Unregistered and cleared any orphaned ACL connections");
1688 }
1689
ClearAcceptList()1690 void shim::legacy::Acl::ClearAcceptList() {
1691 handler_->CallOn(pimpl_.get(), &Acl::impl::clear_acceptlist);
1692 }
1693
AddToAddressResolution(const hci::AddressWithType & address_with_type,const std::array<uint8_t,16> & peer_irk,const std::array<uint8_t,16> & local_irk)1694 void shim::legacy::Acl::AddToAddressResolution(
1695 const hci::AddressWithType& address_with_type,
1696 const std::array<uint8_t, 16>& peer_irk,
1697 const std::array<uint8_t, 16>& local_irk) {
1698 handler_->CallOn(pimpl_.get(), &Acl::impl::AddToAddressResolution,
1699 address_with_type, peer_irk, local_irk);
1700 }
1701
RemoveFromAddressResolution(const hci::AddressWithType & address_with_type)1702 void shim::legacy::Acl::RemoveFromAddressResolution(
1703 const hci::AddressWithType& address_with_type) {
1704 handler_->CallOn(pimpl_.get(), &Acl::impl::RemoveFromAddressResolution,
1705 address_with_type);
1706 }
1707
ClearAddressResolution()1708 void shim::legacy::Acl::ClearAddressResolution() {
1709 handler_->CallOn(pimpl_.get(), &Acl::impl::ClearResolvingList);
1710 }
1711