• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 "hci/acl_manager/le_impl.h"
18 
19 #include <bluetooth/log.h>
20 #include <com_android_bluetooth_flags.h>
21 #include <gmock/gmock.h>
22 #include <gtest/gtest.h>
23 #include <log/log.h>
24 
25 #include <chrono>
26 #include <future>
27 
28 #include "common/bidi_queue.h"
29 #include "common/le_conn_params.h"
30 #include "hci/acl_manager/le_connection_callbacks.h"
31 #include "hci/acl_manager/le_connection_management_callbacks_mock.h"
32 #include "hci/address_with_type.h"
33 #include "hci/controller.h"
34 #include "hci/hci_layer_fake.h"
35 #include "hci/hci_packets.h"
36 #include "hci/octets.h"
37 #include "os/handler.h"
38 #include "packet/bit_inserter.h"
39 #include "packet/raw_builder.h"
40 #include "stack/l2cap/l2c_api.h"
41 
42 using namespace bluetooth;
43 using namespace std::chrono_literals;
44 
45 using ::bluetooth::common::BidiQueue;
46 using ::bluetooth::common::Callback;
47 using ::bluetooth::os::Handler;
48 using ::bluetooth::os::Thread;
49 using ::bluetooth::packet::BitInserter;
50 using ::bluetooth::packet::RawBuilder;
51 
52 using ::testing::_;
53 using ::testing::DoAll;
54 using ::testing::Eq;
55 using ::testing::Field;
56 using ::testing::Mock;
57 using ::testing::MockFunction;
58 using ::testing::SaveArg;
59 using ::testing::VariantWith;
60 using ::testing::WithArg;
61 
62 namespace {
63 constexpr bool kCrashOnUnknownHandle = true;
64 constexpr char kFixedAddress[] = "c0:aa:bb:cc:dd:ee";
65 constexpr char kLocalRandomAddress[] = "04:c0:aa:bb:cc:dd:ee";
66 constexpr char kRemoteRandomAddress[] = "04:11:22:33:44:55";
67 constexpr char kRemoteAddress[] = "00:11:22:33:44:55";
68 constexpr uint16_t kHciHandle = 123;
69 [[maybe_unused]] constexpr bool kAddToFilterAcceptList = true;
70 [[maybe_unused]] constexpr bool kSkipFilterAcceptList = !kAddToFilterAcceptList;
71 [[maybe_unused]] constexpr bool kIsDirectConnection = true;
72 [[maybe_unused]] constexpr bool kIsBackgroundConnection = !kIsDirectConnection;
73 constexpr hci::Octet16 kRotationIrk = {};
74 constexpr std::chrono::milliseconds kMinimumRotationTime(14 * 1000);
75 constexpr std::chrono::milliseconds kMaximumRotationTime(16 * 1000);
76 constexpr uint16_t kIntervalMax = 0x40;
77 constexpr uint16_t kIntervalMin = 0x20;
78 constexpr uint16_t kLatency = 0x60;
79 constexpr uint16_t kLength = 0x5678;
80 constexpr uint16_t kTime = 0x1234;
81 constexpr uint16_t kTimeout = 0x80;
82 constexpr uint16_t kContinuationNumber = 0x32;
83 constexpr std::array<uint8_t, 16> kPeerIdentityResolvingKey({
84         0x00,
85         0x01,
86         0x02,
87         0x03,
88         0x04,
89         0x05,
90         0x06,
91         0x07,
92         0x08,
93         0x09,
94         0x0a,
95         0x0b,
96         0x0c,
97         0x0d,
98         0x0e,
99         0x0f,
100 });
101 constexpr std::array<uint8_t, 16> kLocalIdentityResolvingKey({
102         0x80,
103         0x81,
104         0x82,
105         0x83,
106         0x84,
107         0x85,
108         0x86,
109         0x87,
110         0x88,
111         0x89,
112         0x8a,
113         0x8b,
114         0x8c,
115         0x8d,
116         0x8e,
117         0x8f,
118 });
119 
120 template <typename B>
Serialize(std::unique_ptr<B> build)121 std::shared_ptr<std::vector<uint8_t>> Serialize(std::unique_ptr<B> build) {
122   auto bytes = std::make_shared<std::vector<uint8_t>>();
123   BitInserter bi(*bytes);
124   build->Serialize(bi);
125   return bytes;
126 }
127 
128 template <typename T>
CreateAclCommandView(hci::CommandView command)129 T CreateAclCommandView(hci::CommandView command) {
130   return T::Create(hci::AclCommandView::Create(command));
131 }
132 
133 template <typename T>
CreateLeConnectionManagementCommandView(hci::CommandView command)134 T CreateLeConnectionManagementCommandView(hci::CommandView command) {
135   return T::Create(CreateAclCommandView<hci::LeConnectionManagementCommandView>(command));
136 }
137 
138 template <typename T>
CreateLeSecurityCommandView(hci::CommandView command)139 T CreateLeSecurityCommandView(hci::CommandView command) {
140   return T::Create(hci::LeSecurityCommandView::Create(command));
141 }
142 
143 template <typename T>
CreateLeEventView(std::shared_ptr<std::vector<uint8_t>> bytes)144 T CreateLeEventView(std::shared_ptr<std::vector<uint8_t>> bytes) {
145   return T::Create(hci::LeMetaEventView::Create(
146           hci::EventView::Create(hci::PacketView<hci::kLittleEndian>(bytes))));
147 }
148 
ReturnCommandComplete(hci::OpCode op_code,hci::ErrorCode error_code)149 hci::CommandCompleteView ReturnCommandComplete(hci::OpCode op_code, hci::ErrorCode error_code) {
150   std::vector<uint8_t> success_vector{static_cast<uint8_t>(error_code)};
151   auto builder = hci::CommandCompleteBuilder::Create(uint8_t{1}, op_code,
152                                                      std::make_unique<RawBuilder>(success_vector));
153   auto bytes = Serialize<hci::CommandCompleteBuilder>(std::move(builder));
154   return hci::CommandCompleteView::Create(
155           hci::EventView::Create(hci::PacketView<hci::kLittleEndian>(bytes)));
156 }
157 
ReturnCommandStatus(hci::OpCode op_code,hci::ErrorCode error_code)158 hci::CommandStatusView ReturnCommandStatus(hci::OpCode op_code, hci::ErrorCode error_code) {
159   std::vector<uint8_t> success_vector{static_cast<uint8_t>(error_code)};
160   auto builder = hci::CommandStatusBuilder::Create(hci::ErrorCode::SUCCESS, uint8_t{1}, op_code,
161                                                    std::make_unique<RawBuilder>(success_vector));
162   auto bytes = Serialize<hci::CommandStatusBuilder>(std::move(builder));
163   return hci::CommandStatusView::Create(
164           hci::EventView::Create(hci::PacketView<hci::kLittleEndian>(bytes)));
165 }
166 
167 }  // namespace
168 
169 namespace bluetooth {
170 namespace hci {
171 namespace acl_manager {
172 
173 namespace {
174 
175 class TestController : public Controller {
176 public:
IsSupported(OpCode op_code) const177   bool IsSupported(OpCode op_code) const override {
178     log::info("IsSupported");
179     return supported_opcodes_.count(op_code) == 1;
180   }
181 
AddSupported(OpCode op_code)182   void AddSupported(OpCode op_code) {
183     log::info("AddSupported");
184     supported_opcodes_.insert(op_code);
185   }
186 
GetNumAclPacketBuffers() const187   uint16_t GetNumAclPacketBuffers() const { return max_acl_packet_credits_; }
188 
GetAclPacketLength() const189   uint16_t GetAclPacketLength() const { return hci_mtu_; }
190 
GetLeBufferSize() const191   LeBufferSize GetLeBufferSize() const {
192     LeBufferSize le_buffer_size;
193     le_buffer_size.le_data_packet_length_ = le_hci_mtu_;
194     le_buffer_size.total_num_le_packets_ = le_max_acl_packet_credits_;
195     return le_buffer_size;
196   }
197 
RegisterCompletedAclPacketsCallback(CompletedAclPacketsCallback cb)198   void RegisterCompletedAclPacketsCallback(CompletedAclPacketsCallback cb) {
199     acl_credits_callback_ = cb;
200   }
201 
SendCompletedAclPacketsCallback(uint16_t handle,uint16_t credits)202   void SendCompletedAclPacketsCallback(uint16_t handle, uint16_t credits) {
203     acl_credits_callback_(handle, credits);
204   }
205 
UnregisterCompletedAclPacketsCallback()206   void UnregisterCompletedAclPacketsCallback() { acl_credits_callback_ = {}; }
207 
SupportsBlePrivacy() const208   bool SupportsBlePrivacy() const override { return supports_ble_privacy_; }
209   bool supports_ble_privacy_{false};
210 
211 public:
212   const uint16_t max_acl_packet_credits_ = 10;
213   const uint16_t hci_mtu_ = 1024;
214   const uint16_t le_max_acl_packet_credits_ = 15;
215   const uint16_t le_hci_mtu_ = 27;
216 
217 private:
218   CompletedAclPacketsCallback acl_credits_callback_;
219   std::set<OpCode> supported_opcodes_{};
220 };
221 
222 }  // namespace
223 
224 class MockLeConnectionCallbacks : public LeConnectionCallbacks {
225 public:
226   MOCK_METHOD(void, OnLeConnectSuccess,
227               (AddressWithType address_with_type, std::unique_ptr<LeAclConnection> connection),
228               (override));
229   MOCK_METHOD(void, OnLeConnectFail, (AddressWithType address_with_type, ErrorCode reason),
230               (override));
231 };
232 
233 class MockLeAcceptlistCallbacks : public LeAcceptlistCallbacks {
234 public:
235   MOCK_METHOD(void, OnLeConnectSuccess, (AddressWithType address), (override));
236   MOCK_METHOD(void, OnLeConnectFail, (AddressWithType address, ErrorCode reason), (override));
237   MOCK_METHOD(void, OnLeDisconnection, (AddressWithType address), (override));
238   MOCK_METHOD(void, OnResolvingListChange, (), (override));
239 };
240 
241 class LeImplTest : public ::testing::Test {
242 protected:
SetUp()243   void SetUp() override {
244     __android_log_set_minimum_priority(ANDROID_LOG_VERBOSE);
245     thread_ = new Thread("thread", Thread::Priority::NORMAL);
246     handler_ = new Handler(thread_);
247     controller_ = new TestController();
248     hci_layer_ = new HciLayerFake();
249 
250     round_robin_scheduler_ = new RoundRobinScheduler(handler_, controller_, hci_queue_.GetUpEnd());
251     hci_queue_.GetDownEnd()->RegisterDequeue(
252             handler_, common::Bind(&LeImplTest::HciDownEndDequeue, common::Unretained(this)));
253 
254     classic_impl_ = new classic_impl(hci_layer_, controller_, handler_, round_robin_scheduler_,
255                                      false, nullptr, nullptr);
256     le_impl_ = new le_impl(hci_layer_, controller_, handler_, round_robin_scheduler_,
257                            kCrashOnUnknownHandle, classic_impl_);
258     le_impl_->handle_register_le_callbacks(&mock_le_connection_callbacks_, handler_);
259 
260     Address address;
261     Address::FromString(kFixedAddress, address);
262     fixed_address_ = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS);
263 
264     Address::FromString(kRemoteAddress, remote_address_);
265     remote_public_address_with_type_ =
266             AddressWithType(remote_address_, AddressType::PUBLIC_DEVICE_ADDRESS);
267 
268     Address::FromString(kLocalRandomAddress, local_rpa_);
269     Address::FromString(kRemoteRandomAddress, remote_rpa_);
270   }
271 
set_random_device_address_policy()272   void set_random_device_address_policy() {
273     // Set address policy
274     hci::Address address;
275     Address::FromString("D0:05:04:03:02:01", address);
276     hci::AddressWithType address_with_type(address, hci::AddressType::RANDOM_DEVICE_ADDRESS);
277     Octet16 rotation_irk{};
278     auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000);
279     auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000);
280     le_impl_->set_privacy_policy_for_initiator_address(
281             LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS, address_with_type, rotation_irk,
282             minimum_rotation_time, maximum_rotation_time);
283     hci_layer_->GetCommand(OpCode::LE_SET_RANDOM_ADDRESS);
284     hci_layer_->IncomingEvent(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
285   }
286 
287   // Need to store the LeAclConnection so it is not immediately dropped => disconnected
create_enhanced_connection(std::string remote_address_string,int handle)288   std::unique_ptr<LeAclConnection> create_enhanced_connection(std::string remote_address_string,
289                                                               int handle) {
290     std::unique_ptr<LeAclConnection> connection;
291 
292     hci::Address remote_address;
293     Address::FromString(remote_address_string, remote_address);
294     hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
295     le_impl_->create_le_connection(address_with_type, true, false);
296     sync_handler();
297 
298     hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
299     hci_layer_->IncomingEvent(
300             LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
301     hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
302     hci_layer_->IncomingEvent(
303             LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
304     sync_handler();
305 
306     // Check state is ARMED
307     EXPECT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
308 
309     // we need to capture the LeAclConnection so it is not immediately dropped => disconnected
310     EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _))
311             .WillOnce([&](AddressWithType, std::unique_ptr<LeAclConnection> conn) {
312               connection = std::move(conn);
313               connection->RegisterCallbacks(&connection_management_callbacks_, handler_);
314             });
315 
316     hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
317             ErrorCode::SUCCESS, handle, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS,
318             remote_address, Address::kEmpty, Address::kEmpty, 0x0024, 0x0000, 0x0011,
319             ClockAccuracy::PPM_30));
320     sync_handler();
321 
322     hci_layer_->GetCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
323     hci_layer_->IncomingEvent(
324             LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
325     hci_layer_->AssertNoQueuedCommand();
326     sync_handler();
327     EXPECT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
328 
329     return connection;
330   }
331 
get_view_from_creating_connection(std::string remote_address_string)332   LeExtendedCreateConnectionView get_view_from_creating_connection(
333           std::string remote_address_string) {
334     hci::Address remote_address;
335     Address::FromString(remote_address_string, remote_address);
336     hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
337 
338     // Create connection
339     le_impl_->create_le_connection(address_with_type, true, false);
340 
341     hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
342     hci_layer_->IncomingEvent(
343             LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
344     sync_handler();
345 
346     return CreateLeConnectionManagementCommandView<LeExtendedCreateConnectionView>(
347             hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION));
348   }
349 
TearDown()350   void TearDown() override {
351     com::android::bluetooth::flags::provider_->reset_flags();
352 
353     // We cannot teardown our structure without unregistering
354     // from our own structure we created.
355     if (le_impl_->address_manager_registered) {
356       le_impl_->ready_to_unregister = true;
357       le_impl_->check_for_unregister();
358       sync_handler();
359     }
360 
361     sync_handler();
362     delete le_impl_;
363     delete classic_impl_;
364 
365     hci_queue_.GetDownEnd()->UnregisterDequeue();
366 
367     delete hci_layer_;
368     delete round_robin_scheduler_;
369     delete controller_;
370 
371     handler_->Clear();
372     delete handler_;
373     delete thread_;
374   }
375 
sync_handler()376   void sync_handler() {
377     log::assert_that(thread_ != nullptr, "assert failed: thread_ != nullptr");
378     log::assert_that(thread_->GetReactor()->WaitForIdle(2s),
379                      "assert failed: thread_->GetReactor()->WaitForIdle(2s)");
380   }
381 
HciDownEndDequeue()382   void HciDownEndDequeue() {
383     auto packet = hci_queue_.GetDownEnd()->TryDequeue();
384     // Convert from a Builder to a View
385     auto bytes = std::make_shared<std::vector<uint8_t>>();
386     bluetooth::packet::BitInserter i(*bytes);
387     bytes->reserve(packet->size());
388     packet->Serialize(i);
389     auto packet_view = bluetooth::packet::PacketView<bluetooth::packet::kLittleEndian>(bytes);
390     AclView acl_packet_view = AclView::Create(packet_view);
391     ASSERT_TRUE(acl_packet_view.IsValid());
392     PacketView<true> count_view = acl_packet_view.GetPayload();
393     sent_acl_packets_.push(acl_packet_view);
394 
395     packet_count_--;
396     if (packet_count_ == 0) {
397       packet_promise_->set_value();
398       packet_promise_ = nullptr;
399     }
400   }
401 
402 protected:
set_privacy_policy_for_initiator_address(const AddressWithType & address,const LeAddressManager::AddressPolicy & policy)403   void set_privacy_policy_for_initiator_address(const AddressWithType& address,
404                                                 const LeAddressManager::AddressPolicy& policy) {
405     le_impl_->set_privacy_policy_for_initiator_address(policy, address, kRotationIrk,
406                                                        kMinimumRotationTime, kMaximumRotationTime);
407   }
408 
409   Address remote_address_;
410   AddressWithType fixed_address_;
411   Address local_rpa_;
412   Address remote_rpa_;
413   AddressWithType remote_public_address_with_type_;
414 
415   uint16_t packet_count_;
416   std::unique_ptr<std::promise<void>> packet_promise_;
417   std::unique_ptr<std::future<void>> packet_future_;
418   std::queue<AclView> sent_acl_packets_;
419 
420   BidiQueue<AclView, AclBuilder> hci_queue_{3};
421 
422   Thread* thread_;
423   Handler* handler_;
424   HciLayerFake* hci_layer_{nullptr};
425   classic_impl* classic_impl_;
426   TestController* controller_;
427   RoundRobinScheduler* round_robin_scheduler_{nullptr};
428 
429   MockLeConnectionCallbacks mock_le_connection_callbacks_;
430   MockLeConnectionManagementCallbacks connection_management_callbacks_;
431 
432   struct le_impl* le_impl_;
433 };
434 
435 class LeImplRegisteredWithAddressManagerTest : public LeImplTest {
436 protected:
SetUp()437   void SetUp() override {
438     LeImplTest::SetUp();
439     set_privacy_policy_for_initiator_address(fixed_address_,
440                                              LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
441 
442     le_impl_->register_with_address_manager();
443     sync_handler();  // Let |LeAddressManager::register_client| execute on handler
444     ASSERT_TRUE(le_impl_->address_manager_registered);
445     ASSERT_TRUE(le_impl_->pause_connection);
446   }
447 
TearDown()448   void TearDown() override { LeImplTest::TearDown(); }
449 };
450 
451 class LeImplWithConnectionTest : public LeImplTest {
452 protected:
SetUp()453   void SetUp() override {
454     LeImplTest::SetUp();
455     set_random_device_address_policy();
456 
457     EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _))
458             .WillOnce([&](AddressWithType addr, std::unique_ptr<LeAclConnection> conn) {
459               remote_address_with_type_ = addr;
460               connection_ = std::move(conn);
461               connection_->RegisterCallbacks(&connection_management_callbacks_, handler_);
462             });
463 
464     auto command = LeEnhancedConnectionCompleteBuilder::Create(
465             ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
466             remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011,
467             ClockAccuracy::PPM_30);
468     auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
469     auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
470     ASSERT_TRUE(view.IsValid());
471     le_impl_->on_le_event(view);
472 
473     sync_handler();
474     ASSERT_EQ(remote_public_address_with_type_, remote_address_with_type_);
475   }
476 
TearDown()477   void TearDown() override {
478     connection_.reset();
479     LeImplTest::TearDown();
480   }
481 
482   AddressWithType remote_address_with_type_;
483   std::unique_ptr<LeAclConnection> connection_;
484 };
485 
TEST_F(LeImplTest,add_device_to_accept_list)486 TEST_F(LeImplTest, add_device_to_accept_list) {
487   le_impl_->add_device_to_accept_list(
488           {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
489   ASSERT_EQ(1UL, le_impl_->accept_list.size());
490 
491   le_impl_->add_device_to_accept_list(
492           {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
493   ASSERT_EQ(2UL, le_impl_->accept_list.size());
494 
495   le_impl_->add_device_to_accept_list(
496           {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
497   ASSERT_EQ(2UL, le_impl_->accept_list.size());
498 
499   le_impl_->add_device_to_accept_list(
500           {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
501   ASSERT_EQ(2UL, le_impl_->accept_list.size());
502 }
503 
TEST_F(LeImplTest,remove_device_from_accept_list)504 TEST_F(LeImplTest, remove_device_from_accept_list) {
505   le_impl_->add_device_to_accept_list(
506           {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
507   le_impl_->add_device_to_accept_list(
508           {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
509   le_impl_->add_device_to_accept_list(
510           {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
511   le_impl_->add_device_to_accept_list(
512           {{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
513   ASSERT_EQ(4UL, le_impl_->accept_list.size());
514 
515   le_impl_->remove_device_from_accept_list(
516           {{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
517   ASSERT_EQ(3UL, le_impl_->accept_list.size());
518 
519   le_impl_->remove_device_from_accept_list(
520           {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
521   ASSERT_EQ(2UL, le_impl_->accept_list.size());
522 
523   le_impl_->remove_device_from_accept_list(
524           {{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
525   ASSERT_EQ(2UL, le_impl_->accept_list.size());
526 
527   le_impl_->remove_device_from_accept_list({Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS});
528   ASSERT_EQ(2UL, le_impl_->accept_list.size());
529 
530   le_impl_->remove_device_from_accept_list(
531           {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
532   le_impl_->remove_device_from_accept_list(
533           {{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
534   ASSERT_EQ(0UL, le_impl_->accept_list.size());
535 }
536 
TEST_F(LeImplTest,connection_complete_with_periperal_role)537 TEST_F(LeImplTest, connection_complete_with_periperal_role) {
538   set_random_device_address_policy();
539 
540   // Create connection
541   le_impl_->create_le_connection(
542           {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false);
543   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
544   hci_layer_->IncomingEvent(
545           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
546   hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
547   hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
548   sync_handler();
549 
550   // Check state is ARMED
551   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
552 
553   // Receive connection complete of incoming connection (Role::PERIPHERAL)
554   hci::Address remote_address;
555   Address::FromString("D0:05:04:03:02:01", remote_address);
556   hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
557   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
558   hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
559           ErrorCode::SUCCESS, 0x0041, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
560           remote_address, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30));
561   sync_handler();
562 
563   // Check state is still ARMED
564   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
565 }
566 
TEST_F(LeImplTest,enhanced_connection_complete_with_periperal_role)567 TEST_F(LeImplTest, enhanced_connection_complete_with_periperal_role) {
568   set_random_device_address_policy();
569 
570   controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
571   // Create connection
572   le_impl_->create_le_connection(
573           {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false);
574   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
575   hci_layer_->IncomingEvent(
576           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
577   hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
578   hci_layer_->IncomingEvent(
579           LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
580   sync_handler();
581 
582   // Check state is ARMED
583   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
584 
585   // Receive connection complete of incoming connection (Role::PERIPHERAL)
586   hci::Address remote_address;
587   Address::FromString("D0:05:04:03:02:01", remote_address);
588   hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
589   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
590   hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
591           ErrorCode::SUCCESS, 0x0041, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
592           remote_address, Address::kEmpty, Address::kEmpty, 0x0024, 0x0000, 0x0011,
593           ClockAccuracy::PPM_30));
594   sync_handler();
595 
596   // Check state is still ARMED
597   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
598 }
599 
TEST_F(LeImplTest,connection_complete_with_central_role)600 TEST_F(LeImplTest, connection_complete_with_central_role) {
601   set_random_device_address_policy();
602 
603   hci::Address remote_address;
604   Address::FromString("D0:05:04:03:02:01", remote_address);
605   hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
606   // Create connection
607   le_impl_->create_le_connection(address_with_type, true, false);
608   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
609   hci_layer_->IncomingEvent(
610           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
611   hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
612   hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
613   sync_handler();
614 
615   // Check state is ARMED
616   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
617 
618   // Receive connection complete of outgoing connection (Role::CENTRAL)
619   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
620   hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
621           ErrorCode::SUCCESS, 0x0041, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS,
622           remote_address, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30));
623   sync_handler();
624 
625   // Check state is DISARMED
626   ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
627 }
628 
TEST_F(LeImplTest,enhanced_connection_complete_with_central_role)629 TEST_F(LeImplTest, enhanced_connection_complete_with_central_role) {
630   set_random_device_address_policy();
631 
632   controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
633   hci::Address remote_address;
634   Address::FromString("D0:05:04:03:02:01", remote_address);
635   hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
636   // Create connection
637   le_impl_->create_le_connection(address_with_type, true, false);
638   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
639   hci_layer_->IncomingEvent(
640           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
641   hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
642   hci_layer_->IncomingEvent(
643           LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
644   sync_handler();
645 
646   // Check state is ARMED
647   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
648 
649   // Receive connection complete of outgoing connection (Role::CENTRAL)
650   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
651   hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
652           ErrorCode::SUCCESS, 0x0041, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS,
653           remote_address, Address::kEmpty, Address::kEmpty, 0x0024, 0x0000, 0x0011,
654           ClockAccuracy::PPM_30));
655   sync_handler();
656 
657   // Check state is DISARMED
658   ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
659 }
660 
TEST_F(LeImplTest,aggressive_connection_mode_selected_when_no_ongoing_le_connections_exist)661 TEST_F(LeImplTest, aggressive_connection_mode_selected_when_no_ongoing_le_connections_exist) {
662   if (LeConnectionParameters::GetAggressiveConnThreshold() == 0) {
663     GTEST_SKIP() << "Skipping test because the threshold is zero";
664   }
665 
666   com::android::bluetooth::flags::provider_->initial_conn_params_p1(true);
667   set_random_device_address_policy();
668   controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
669 
670   LeExtendedCreateConnectionView view = get_view_from_creating_connection("FF:EE:DD:CC:BB:AA");
671 
672   ASSERT_TRUE(view.IsValid());
673   ASSERT_EQ(view.GetPhyScanParameters()[0].conn_interval_min_,
674             LeConnectionParameters::GetMinConnIntervalAggressive());
675   ASSERT_EQ(view.GetPhyScanParameters()[0].conn_interval_max_,
676             LeConnectionParameters::GetMaxConnIntervalAggressive());
677 }
678 
TEST_F(LeImplTest,aggressive_connection_mode_selected_when_few_le_connections_exist)679 TEST_F(LeImplTest, aggressive_connection_mode_selected_when_few_le_connections_exist) {
680   if (LeConnectionParameters::GetAggressiveConnThreshold() == 0) {
681     GTEST_SKIP() << "Skipping test because the threshold is zero";
682   }
683 
684   com::android::bluetooth::flags::provider_->initial_conn_params_p1(true);
685   set_random_device_address_policy();
686   controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
687 
688   std::vector<std::unique_ptr<LeAclConnection>> connections;
689   for (uint32_t i = 0; i < LeConnectionParameters::GetAggressiveConnThreshold() - 1; i++) {
690     std::stringstream addr_string_stream;
691     addr_string_stream << "A0:05:04:03:02:" << std::hex << std::setw(2) << std::setfill('0') << i;
692 
693     connections.push_back(create_enhanced_connection(addr_string_stream.str(), i /* handle */));
694   }
695 
696   LeExtendedCreateConnectionView view = get_view_from_creating_connection("FF:EE:DD:CC:BB:AA");
697 
698   ASSERT_TRUE(view.IsValid());
699   ASSERT_EQ(view.GetPhyScanParameters()[0].conn_interval_min_,
700             LeConnectionParameters::GetMinConnIntervalAggressive());
701   ASSERT_EQ(view.GetPhyScanParameters()[0].conn_interval_max_,
702             LeConnectionParameters::GetMaxConnIntervalAggressive());
703 }
704 
TEST_F(LeImplTest,relaxed_connection_mode_selected_when_enough_le_connections_exist)705 TEST_F(LeImplTest, relaxed_connection_mode_selected_when_enough_le_connections_exist) {
706   com::android::bluetooth::flags::provider_->initial_conn_params_p1(true);
707   set_random_device_address_policy();
708   controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
709 
710   std::vector<std::unique_ptr<LeAclConnection>> connections;
711   for (uint32_t i = 0; i < LeConnectionParameters::GetAggressiveConnThreshold(); i++) {
712     std::stringstream addr_string_stream;
713     addr_string_stream << "A0:05:04:03:02:" << std::hex << std::setw(2) << std::setfill('0') << i;
714 
715     connections.push_back(create_enhanced_connection(addr_string_stream.str(), i /* handle */));
716   }
717 
718   LeExtendedCreateConnectionView view = get_view_from_creating_connection("FF:EE:DD:CC:BB:AA");
719 
720   ASSERT_TRUE(view.IsValid());
721   ASSERT_EQ(view.GetPhyScanParameters()[0].conn_interval_min_,
722             LeConnectionParameters::GetMinConnIntervalRelaxed());
723   ASSERT_EQ(view.GetPhyScanParameters()[0].conn_interval_max_,
724             LeConnectionParameters::GetMaxConnIntervalRelaxed());
725 }
726 
727 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyNotSet)728 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNotSet) {
729   std::promise<void> promise;
730   auto future = promise.get_future();
731   handler_->Post(common::BindOnce(
732           [](struct le_impl* le_impl, os::Handler* handler, std::promise<void> promise) {
733             le_impl->register_with_address_manager();
734             handler->Post(common::BindOnce([](std::promise<void> promise) { promise.set_value(); },
735                                            std::move(promise)));
736           },
737           le_impl_, handler_, std::move(promise)));
738 
739   // Let |LeAddressManager::register_client| execute on handler
740   auto status = future.wait_for(2s);
741   ASSERT_EQ(status, std::future_status::ready);
742 
743   handler_->Post(common::BindOnce(
744           [](struct le_impl* le_impl) {
745             ASSERT_TRUE(le_impl->address_manager_registered);
746             ASSERT_TRUE(le_impl->pause_connection);
747           },
748           le_impl_));
749 
750   std::promise<void> promise2;
751   auto future2 = promise2.get_future();
752   handler_->Post(common::BindOnce(
753           [](struct le_impl* le_impl, os::Handler* handler, std::promise<void> promise) {
754             le_impl->ready_to_unregister = true;
755             le_impl->check_for_unregister();
756             ASSERT_FALSE(le_impl->address_manager_registered);
757             ASSERT_FALSE(le_impl->pause_connection);
758             handler->Post(common::BindOnce([](std::promise<void> promise) { promise.set_value(); },
759                                            std::move(promise)));
760           },
761           le_impl_, handler_, std::move(promise2)));
762 
763   // Let |LeAddressManager::unregister_client| execute on handler
764   auto status2 = future2.wait_for(2s);
765   ASSERT_EQ(status2, std::future_status::ready);
766 }
767 
768 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMED)769 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED) {
770   le_impl_->connectability_state_ = ConnectabilityState::DISARMED;
771   le_impl_->disarm_connectability();
772   ASSERT_FALSE(le_impl_->disarmed_while_arming_);
773 
774   le_impl_->on_create_connection(
775           ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
776 }
777 
778 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMED_extended)779 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED_extended) {
780   le_impl_->connectability_state_ = ConnectabilityState::DISARMED;
781   le_impl_->disarm_connectability();
782   ASSERT_FALSE(le_impl_->disarmed_while_arming_);
783 
784   le_impl_->on_extended_create_connection(
785           ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
786 }
787 
788 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMING)789 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING) {
790   le_impl_->connectability_state_ = ConnectabilityState::ARMING;
791   le_impl_->disarm_connectability();
792   ASSERT_TRUE(le_impl_->disarmed_while_arming_);
793   le_impl_->on_create_connection(
794           ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
795 }
796 
797 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMING_extended)798 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING_extended) {
799   le_impl_->connectability_state_ = ConnectabilityState::ARMING;
800   le_impl_->disarm_connectability();
801   ASSERT_TRUE(le_impl_->disarmed_while_arming_);
802 
803   le_impl_->on_extended_create_connection(
804           ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
805 }
806 
807 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMED)808 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED) {
809   le_impl_->connectability_state_ = ConnectabilityState::ARMED;
810   le_impl_->disarm_connectability();
811   ASSERT_FALSE(le_impl_->disarmed_while_arming_);
812 
813   le_impl_->on_create_connection(
814           ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
815 }
816 
817 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMED_extended)818 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED_extended) {
819   le_impl_->connectability_state_ = ConnectabilityState::ARMED;
820   le_impl_->disarm_connectability();
821   ASSERT_FALSE(le_impl_->disarmed_while_arming_);
822 
823   le_impl_->on_extended_create_connection(
824           ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
825 }
826 
827 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMING)828 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING) {
829   le_impl_->connectability_state_ = ConnectabilityState::DISARMING;
830   le_impl_->disarm_connectability();
831   ASSERT_FALSE(le_impl_->disarmed_while_arming_);
832 
833   le_impl_->on_create_connection(
834           ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
835 }
836 
837 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMING_extended)838 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING_extended) {
839   le_impl_->connectability_state_ = ConnectabilityState::DISARMING;
840   le_impl_->disarm_connectability();
841   ASSERT_FALSE(le_impl_->disarmed_while_arming_);
842 
843   le_impl_->on_extended_create_connection(
844           ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
845 }
846 
847 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyPublicAddress)848 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyPublicAddress) {
849   set_privacy_policy_for_initiator_address(fixed_address_,
850                                            LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
851 
852   le_impl_->register_with_address_manager();
853   sync_handler();  // Let |eAddressManager::register_client| execute on handler
854   ASSERT_TRUE(le_impl_->address_manager_registered);
855   ASSERT_TRUE(le_impl_->pause_connection);
856 
857   le_impl_->ready_to_unregister = true;
858 
859   le_impl_->check_for_unregister();
860   sync_handler();  // Let |LeAddressManager::unregister_client| execute on handler
861   ASSERT_FALSE(le_impl_->address_manager_registered);
862   ASSERT_FALSE(le_impl_->pause_connection);
863 }
864 
865 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyStaticAddress)866 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyStaticAddress) {
867   set_privacy_policy_for_initiator_address(fixed_address_,
868                                            LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS);
869 
870   le_impl_->register_with_address_manager();
871   sync_handler();  // Let |LeAddressManager::register_client| execute on handler
872   ASSERT_TRUE(le_impl_->address_manager_registered);
873   ASSERT_TRUE(le_impl_->pause_connection);
874 
875   le_impl_->ready_to_unregister = true;
876 
877   le_impl_->check_for_unregister();
878   sync_handler();  // Let |LeAddressManager::unregister_client| execute on handler
879   ASSERT_FALSE(le_impl_->address_manager_registered);
880   ASSERT_FALSE(le_impl_->pause_connection);
881 }
882 
883 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyNonResolvableAddress)884 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNonResolvableAddress) {
885   set_privacy_policy_for_initiator_address(
886           fixed_address_, LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS);
887 
888   le_impl_->register_with_address_manager();
889   sync_handler();  // Let |LeAddressManager::register_client| execute on handler
890   ASSERT_TRUE(le_impl_->address_manager_registered);
891   ASSERT_TRUE(le_impl_->pause_connection);
892 
893   le_impl_->ready_to_unregister = true;
894 
895   le_impl_->check_for_unregister();
896   sync_handler();  // Let |LeAddressManager::unregister_client| execute on handler
897   ASSERT_FALSE(le_impl_->address_manager_registered);
898   ASSERT_FALSE(le_impl_->pause_connection);
899 }
900 
901 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyResolvableAddress)902 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyResolvableAddress) {
903   set_privacy_policy_for_initiator_address(fixed_address_,
904                                            LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS);
905 
906   le_impl_->register_with_address_manager();
907   sync_handler();  // Let |LeAddressManager::register_client| execute on handler
908   ASSERT_TRUE(le_impl_->address_manager_registered);
909   ASSERT_TRUE(le_impl_->pause_connection);
910 
911   le_impl_->ready_to_unregister = true;
912 
913   le_impl_->check_for_unregister();
914   sync_handler();  // Let |LeAddressManager::unregister_client| execute on handler
915   ASSERT_FALSE(le_impl_->address_manager_registered);
916   ASSERT_FALSE(le_impl_->pause_connection);
917 }
918 
919 // b/260920739
TEST_F(LeImplTest,DISABLED_add_device_to_resolving_list)920 TEST_F(LeImplTest, DISABLED_add_device_to_resolving_list) {
921   // Some kind of privacy policy must be set for LeAddressManager to operate properly
922   set_privacy_policy_for_initiator_address(fixed_address_,
923                                            LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
924   // Let LeAddressManager::resume_registered_clients execute
925   sync_handler();
926 
927   hci_layer_->AssertNoQueuedCommand();
928 
929   // le_impl should not be registered with address manager
930   ASSERT_FALSE(le_impl_->address_manager_registered);
931   ASSERT_FALSE(le_impl_->pause_connection);
932 
933   ASSERT_EQ(0UL, le_impl_->le_address_manager_->NumberCachedCommands());
934   // Acknowledge that the le_impl has quiesced all relevant controller state
935   le_impl_->add_device_to_resolving_list(remote_public_address_with_type_,
936                                          kPeerIdentityResolvingKey, kLocalIdentityResolvingKey);
937   ASSERT_EQ(3UL, le_impl_->le_address_manager_->NumberCachedCommands());
938 
939   sync_handler();  // Let |LeAddressManager::register_client| execute on handler
940   ASSERT_TRUE(le_impl_->address_manager_registered);
941   ASSERT_TRUE(le_impl_->pause_connection);
942 
943   le_impl_->le_address_manager_->AckPause(le_impl_);
944   sync_handler();  // Allow |LeAddressManager::ack_pause| to complete
945 
946   {
947     // Inform controller to disable address resolution
948     auto command =
949             CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->GetCommand());
950     ASSERT_TRUE(command.IsValid());
951     ASSERT_EQ(Enable::DISABLED, command.GetAddressResolutionEnable());
952     le_impl_->le_address_manager_->OnCommandComplete(
953             ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
954   }
955   sync_handler();  // |LeAddressManager::check_cached_commands|
956 
957   {
958     auto command =
959             CreateLeSecurityCommandView<LeAddDeviceToResolvingListView>(hci_layer_->GetCommand());
960     ASSERT_TRUE(command.IsValid());
961     ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS,
962               command.GetPeerIdentityAddressType());
963     ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress());
964     ASSERT_EQ(kPeerIdentityResolvingKey, command.GetPeerIrk());
965     ASSERT_EQ(kLocalIdentityResolvingKey, command.GetLocalIrk());
966     le_impl_->le_address_manager_->OnCommandComplete(
967             ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS));
968   }
969   sync_handler();  // |LeAddressManager::check_cached_commands|
970 
971   {
972     auto command =
973             CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->GetCommand());
974     ASSERT_TRUE(command.IsValid());
975     ASSERT_EQ(Enable::ENABLED, command.GetAddressResolutionEnable());
976     le_impl_->le_address_manager_->OnCommandComplete(
977             ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
978   }
979   sync_handler();  // |LeAddressManager::check_cached_commands|
980 
981   hci_layer_->AssertNoQueuedCommand();
982   ASSERT_TRUE(le_impl_->address_manager_registered);
983 
984   le_impl_->ready_to_unregister = true;
985 
986   le_impl_->check_for_unregister();
987   sync_handler();
988   ASSERT_FALSE(le_impl_->address_manager_registered);
989   ASSERT_FALSE(le_impl_->pause_connection);
990 }
991 
TEST_F(LeImplTest,add_device_to_resolving_list__SupportsBlePrivacy)992 TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) {
993   controller_->supports_ble_privacy_ = true;
994 
995   // Some kind of privacy policy must be set for LeAddressManager to operate properly
996   set_privacy_policy_for_initiator_address(fixed_address_,
997                                            LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
998   // Let LeAddressManager::resume_registered_clients execute
999   sync_handler();
1000 
1001   hci_layer_->AssertNoQueuedCommand();
1002 
1003   // le_impl should not be registered with address manager
1004   ASSERT_FALSE(le_impl_->address_manager_registered);
1005   ASSERT_FALSE(le_impl_->pause_connection);
1006 
1007   ASSERT_EQ(0UL, le_impl_->le_address_manager_->NumberCachedCommands());
1008   // Acknowledge that the le_impl has quiesced all relevant controller state
1009   le_impl_->add_device_to_resolving_list(remote_public_address_with_type_,
1010                                          kPeerIdentityResolvingKey, kLocalIdentityResolvingKey);
1011   ASSERT_EQ(4UL, le_impl_->le_address_manager_->NumberCachedCommands());
1012 
1013   sync_handler();  // Let |LeAddressManager::register_client| execute on handler
1014   ASSERT_TRUE(le_impl_->address_manager_registered);
1015   ASSERT_TRUE(le_impl_->pause_connection);
1016 
1017   le_impl_->le_address_manager_->AckPause(le_impl_);
1018   sync_handler();  // Allow |LeAddressManager::ack_pause| to complete
1019 
1020   {
1021     // Inform controller to disable address resolution
1022     auto command =
1023             CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->GetCommand());
1024     ASSERT_TRUE(command.IsValid());
1025     ASSERT_EQ(Enable::DISABLED, command.GetAddressResolutionEnable());
1026     le_impl_->le_address_manager_->OnCommandComplete(
1027             ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1028   }
1029   sync_handler();  // |LeAddressManager::check_cached_commands|
1030 
1031   {
1032     auto command =
1033             CreateLeSecurityCommandView<LeAddDeviceToResolvingListView>(hci_layer_->GetCommand());
1034     ASSERT_TRUE(command.IsValid());
1035     ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS,
1036               command.GetPeerIdentityAddressType());
1037     ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress());
1038     ASSERT_EQ(kPeerIdentityResolvingKey, command.GetPeerIrk());
1039     ASSERT_EQ(kLocalIdentityResolvingKey, command.GetLocalIrk());
1040     le_impl_->le_address_manager_->OnCommandComplete(
1041             ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS));
1042   }
1043   sync_handler();  // |LeAddressManager::check_cached_commands|
1044 
1045   {
1046     auto command = CreateLeSecurityCommandView<LeSetPrivacyModeView>(hci_layer_->GetCommand());
1047     ASSERT_TRUE(command.IsValid());
1048     ASSERT_EQ(PrivacyMode::DEVICE, command.GetPrivacyMode());
1049     ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress());
1050     ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS,
1051               command.GetPeerIdentityAddressType());
1052     le_impl_->le_address_manager_->OnCommandComplete(
1053             ReturnCommandComplete(OpCode::LE_SET_PRIVACY_MODE, ErrorCode::SUCCESS));
1054   }
1055   sync_handler();  // |LeAddressManager::check_cached_commands|
1056 
1057   {
1058     auto command =
1059             CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->GetCommand());
1060     ASSERT_TRUE(command.IsValid());
1061     ASSERT_EQ(Enable::ENABLED, command.GetAddressResolutionEnable());
1062     le_impl_->le_address_manager_->OnCommandComplete(
1063             ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1064   }
1065   sync_handler();  // |LeAddressManager::check_cached_commands|
1066 
1067   ASSERT_TRUE(le_impl_->address_manager_registered);
1068 
1069   le_impl_->ready_to_unregister = true;
1070 
1071   le_impl_->check_for_unregister();
1072   sync_handler();
1073   ASSERT_FALSE(le_impl_->address_manager_registered);
1074   ASSERT_FALSE(le_impl_->pause_connection);
1075 }
1076 
TEST_F(LeImplTest,connectability_state_machine_text)1077 TEST_F(LeImplTest, connectability_state_machine_text) {
1078   ASSERT_STREQ("ConnectabilityState::DISARMED",
1079                connectability_state_machine_text(ConnectabilityState::DISARMED).c_str());
1080   ASSERT_STREQ("ConnectabilityState::ARMING",
1081                connectability_state_machine_text(ConnectabilityState::ARMING).c_str());
1082   ASSERT_STREQ("ConnectabilityState::ARMED",
1083                connectability_state_machine_text(ConnectabilityState::ARMED).c_str());
1084   ASSERT_STREQ("ConnectabilityState::DISARMING",
1085                connectability_state_machine_text(ConnectabilityState::DISARMING).c_str());
1086 }
1087 
TEST_F(LeImplTest,on_le_event__CONNECTION_COMPLETE_CENTRAL)1088 TEST_F(LeImplTest, on_le_event__CONNECTION_COMPLETE_CENTRAL) {
1089   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1090   set_random_device_address_policy();
1091   auto command = LeConnectionCompleteBuilder::Create(
1092           ErrorCode::SUCCESS, kHciHandle, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1093           remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30);
1094   auto bytes = Serialize<LeConnectionCompleteBuilder>(std::move(command));
1095   auto view = CreateLeEventView<hci::LeConnectionCompleteView>(bytes);
1096   ASSERT_TRUE(view.IsValid());
1097   le_impl_->on_le_event(view);
1098 }
1099 
TEST_F(LeImplTest,on_le_event__CONNECTION_COMPLETE_PERIPHERAL)1100 TEST_F(LeImplTest, on_le_event__CONNECTION_COMPLETE_PERIPHERAL) {
1101   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1102   set_random_device_address_policy();
1103   auto command = LeConnectionCompleteBuilder::Create(
1104           ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1105           remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30);
1106   auto bytes = Serialize<LeConnectionCompleteBuilder>(std::move(command));
1107   auto view = CreateLeEventView<hci::LeConnectionCompleteView>(bytes);
1108   ASSERT_TRUE(view.IsValid());
1109   le_impl_->on_le_event(view);
1110 }
1111 
TEST_F(LeImplTest,on_le_event__ENHANCED_CONNECTION_COMPLETE_CENTRAL)1112 TEST_F(LeImplTest, on_le_event__ENHANCED_CONNECTION_COMPLETE_CENTRAL) {
1113   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1114   set_random_device_address_policy();
1115   auto command = LeEnhancedConnectionCompleteBuilder::Create(
1116           ErrorCode::SUCCESS, kHciHandle, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1117           remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30);
1118   auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
1119   auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
1120   ASSERT_TRUE(view.IsValid());
1121   le_impl_->on_le_event(view);
1122 }
1123 
TEST_F(LeImplTest,on_le_event__ENHANCED_CONNECTION_COMPLETE_PERIPHERAL)1124 TEST_F(LeImplTest, on_le_event__ENHANCED_CONNECTION_COMPLETE_PERIPHERAL) {
1125   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1126   set_random_device_address_policy();
1127   auto command = LeEnhancedConnectionCompleteBuilder::Create(
1128           ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1129           remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30);
1130   auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
1131   auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
1132   ASSERT_TRUE(view.IsValid());
1133   le_impl_->on_le_event(view);
1134 }
1135 
TEST_F(LeImplWithConnectionTest,on_le_event__PHY_UPDATE_COMPLETE)1136 TEST_F(LeImplWithConnectionTest, on_le_event__PHY_UPDATE_COMPLETE) {
1137   hci::ErrorCode hci_status{ErrorCode::STATUS_UNKNOWN};
1138   hci::PhyType tx_phy{0};
1139   hci::PhyType rx_phy{0};
1140 
1141   // Send a phy update
1142   {
1143     EXPECT_CALL(connection_management_callbacks_, OnPhyUpdate(_, _, _))
1144             .WillOnce([&](hci::ErrorCode _hci_status, uint8_t _tx_phy, uint8_t _rx_phy) {
1145               hci_status = _hci_status;
1146               tx_phy = static_cast<PhyType>(_tx_phy);
1147               rx_phy = static_cast<PhyType>(_rx_phy);
1148             });
1149     auto command = LePhyUpdateCompleteBuilder::Create(ErrorCode::SUCCESS, kHciHandle, 0x01, 0x02);
1150     auto bytes = Serialize<LePhyUpdateCompleteBuilder>(std::move(command));
1151     auto view = CreateLeEventView<hci::LePhyUpdateCompleteView>(bytes);
1152     ASSERT_TRUE(view.IsValid());
1153     le_impl_->on_le_event(view);
1154   }
1155 
1156   sync_handler();
1157   ASSERT_EQ(ErrorCode::SUCCESS, hci_status);
1158   ASSERT_EQ(PhyType::LE_1M, tx_phy);
1159   ASSERT_EQ(PhyType::LE_2M, rx_phy);
1160 }
1161 
TEST_F(LeImplWithConnectionTest,on_le_event__SUBRATE_CHANGE_EVENT)1162 TEST_F(LeImplWithConnectionTest, on_le_event__SUBRATE_CHANGE_EVENT) {
1163   // Send a subrate event
1164   EXPECT_CALL(connection_management_callbacks_,
1165               OnLeSubrateChange(ErrorCode::SUCCESS, 0x01, 0x02, 0x03, 0x04));
1166   auto command =
1167           LeSubrateChangeBuilder::Create(ErrorCode::SUCCESS, kHciHandle, 0x01, 0x02, 0x03, 0x04);
1168   auto bytes = Serialize<LeSubrateChangeBuilder>(std::move(command));
1169   auto view = CreateLeEventView<hci::LeSubrateChangeView>(bytes);
1170   ASSERT_TRUE(view.IsValid());
1171   le_impl_->on_le_event(view);
1172 
1173   sync_handler();
1174 }
1175 
TEST_F(LeImplWithConnectionTest,on_le_event__DATA_LENGTH_CHANGE)1176 TEST_F(LeImplWithConnectionTest, on_le_event__DATA_LENGTH_CHANGE) {
1177   uint16_t tx_octets{0};
1178   uint16_t tx_time{0};
1179   uint16_t rx_octets{0};
1180   uint16_t rx_time{0};
1181 
1182   // Send a data length event
1183   {
1184     EXPECT_CALL(connection_management_callbacks_, OnDataLengthChange(_, _, _, _))
1185             .WillOnce([&](uint16_t _tx_octets, uint16_t _tx_time, uint16_t _rx_octets,
1186                           uint16_t _rx_time) {
1187               tx_octets = _tx_octets;
1188               tx_time = _tx_time;
1189               rx_octets = _rx_octets;
1190               rx_time = _rx_time;
1191             });
1192     auto command = LeDataLengthChangeBuilder::Create(kHciHandle, 0x1234, 0x5678, 0x9abc, 0xdef0);
1193     auto bytes = Serialize<LeDataLengthChangeBuilder>(std::move(command));
1194     auto view = CreateLeEventView<hci::LeDataLengthChangeView>(bytes);
1195     ASSERT_TRUE(view.IsValid());
1196     le_impl_->on_le_event(view);
1197   }
1198 
1199   sync_handler();
1200   ASSERT_EQ(0x1234, tx_octets);
1201   ASSERT_EQ(0x5678, tx_time);
1202   ASSERT_EQ(0x9abc, rx_octets);
1203   ASSERT_EQ(0xdef0, rx_time);
1204 }
1205 
TEST_F(LeImplWithConnectionTest,on_le_event__REMOTE_CONNECTION_PARAMETER_REQUEST)1206 TEST_F(LeImplWithConnectionTest, on_le_event__REMOTE_CONNECTION_PARAMETER_REQUEST) {
1207   std::promise<void> request_promise;
1208   auto request = request_promise.get_future();
1209   EXPECT_CALL(connection_management_callbacks_,
1210               OnParameterUpdateRequest(kIntervalMin, kIntervalMax, kLatency, kTimeout))
1211           .WillOnce([&request_promise]() { request_promise.set_value(); });
1212 
1213   // Send a remote connection parameter request
1214   auto command = hci::LeRemoteConnectionParameterRequestBuilder::Create(
1215           kHciHandle, kIntervalMin, kIntervalMax, kLatency, kTimeout);
1216   auto bytes = Serialize<LeRemoteConnectionParameterRequestBuilder>(std::move(command));
1217   {
1218     auto view = CreateLeEventView<hci::LeRemoteConnectionParameterRequestView>(bytes);
1219     ASSERT_TRUE(view.IsValid());
1220     le_impl_->on_le_event(view);
1221   }
1222 
1223   ASSERT_EQ(std::future_status::ready, request.wait_for(std::chrono::seconds(1)));
1224 }
1225 
1226 // b/260920739
TEST_F(LeImplRegisteredWithAddressManagerTest,DISABLED_clear_resolving_list)1227 TEST_F(LeImplRegisteredWithAddressManagerTest, DISABLED_clear_resolving_list) {
1228   le_impl_->clear_resolving_list();
1229   ASSERT_EQ(3UL, le_impl_->le_address_manager_->NumberCachedCommands());
1230 
1231   sync_handler();  // Allow |LeAddressManager::pause_registered_clients| to complete
1232   sync_handler();  // Allow |LeAddressManager::handle_next_command| to complete
1233 
1234   {
1235     auto view =
1236             CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->GetCommand());
1237     ASSERT_TRUE(view.IsValid());
1238     ASSERT_EQ(Enable::DISABLED, view.GetAddressResolutionEnable());
1239     le_impl_->le_address_manager_->OnCommandComplete(
1240             ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1241   }
1242 
1243   sync_handler();  // Allow |LeAddressManager::check_cached_commands| to complete
1244   {
1245     auto view = CreateLeSecurityCommandView<LeClearResolvingListView>(hci_layer_->GetCommand());
1246     ASSERT_TRUE(view.IsValid());
1247     le_impl_->le_address_manager_->OnCommandComplete(
1248             ReturnCommandComplete(OpCode::LE_CLEAR_RESOLVING_LIST, ErrorCode::SUCCESS));
1249   }
1250 
1251   sync_handler();  // Allow |LeAddressManager::handle_next_command| to complete
1252   {
1253     auto view =
1254             CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->GetCommand());
1255     ASSERT_TRUE(view.IsValid());
1256     ASSERT_EQ(Enable::ENABLED, view.GetAddressResolutionEnable());
1257     le_impl_->le_address_manager_->OnCommandComplete(
1258             ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1259   }
1260   hci_layer_->AssertNoQueuedCommand();
1261 }
1262 
TEST_F(LeImplRegisteredWithAddressManagerTest,ignore_on_pause_on_resume_after_unregistered)1263 TEST_F(LeImplRegisteredWithAddressManagerTest, ignore_on_pause_on_resume_after_unregistered) {
1264   le_impl_->ready_to_unregister = true;
1265   le_impl_->check_for_unregister();
1266   // OnPause should be ignored
1267   le_impl_->OnPause();
1268   ASSERT_FALSE(le_impl_->pause_connection);
1269   // OnResume should be ignored
1270   le_impl_->pause_connection = true;
1271   le_impl_->OnResume();
1272   ASSERT_TRUE(le_impl_->pause_connection);
1273 }
1274 
TEST_F(LeImplWithConnectionTest,HACK_get_handle)1275 TEST_F(LeImplWithConnectionTest, HACK_get_handle) {
1276   sync_handler();
1277 
1278   ASSERT_EQ(kHciHandle, le_impl_->HACK_get_handle(remote_address_));
1279 }
1280 
TEST_F(LeImplTest,on_le_connection_canceled_on_pause)1281 TEST_F(LeImplTest, on_le_connection_canceled_on_pause) {
1282   set_random_device_address_policy();
1283   le_impl_->pause_connection = true;
1284   le_impl_->on_le_connection_canceled_on_pause();
1285   ASSERT_TRUE(le_impl_->arm_on_resume_);
1286   ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
1287 }
1288 
TEST_F(LeImplTest,on_create_connection_timeout)1289 TEST_F(LeImplTest, on_create_connection_timeout) {
1290   EXPECT_CALL(mock_le_connection_callbacks_,
1291               OnLeConnectFail(_, ErrorCode::CONNECTION_ACCEPT_TIMEOUT))
1292           .Times(1);
1293   le_impl_->create_connection_timeout_alarms_.emplace(
1294           std::piecewise_construct,
1295           std::forward_as_tuple(remote_public_address_with_type_.GetAddress(),
1296                                 remote_public_address_with_type_.GetAddressType()),
1297           std::forward_as_tuple(handler_));
1298   le_impl_->on_create_connection_timeout(remote_public_address_with_type_);
1299   sync_handler();
1300   ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty());
1301 }
1302 
1303 // b/260917913
TEST_F(LeImplTest,DISABLED_on_common_le_connection_complete__NoPriorConnection)1304 TEST_F(LeImplTest, DISABLED_on_common_le_connection_complete__NoPriorConnection) {
1305   le_impl_->on_common_le_connection_complete(remote_public_address_with_type_);
1306   ASSERT_TRUE(le_impl_->connecting_le_.empty());
1307 }
1308 
TEST_F(LeImplTest,cancel_connect)1309 TEST_F(LeImplTest, cancel_connect) {
1310   le_impl_->create_connection_timeout_alarms_.emplace(
1311           std::piecewise_construct,
1312           std::forward_as_tuple(remote_public_address_with_type_.GetAddress(),
1313                                 remote_public_address_with_type_.GetAddressType()),
1314           std::forward_as_tuple(handler_));
1315   le_impl_->cancel_connect(remote_public_address_with_type_);
1316   sync_handler();
1317   ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty());
1318 }
1319 
1320 enum class ConnectionCompleteType { CONNECTION_COMPLETE, ENHANCED_CONNECTION_COMPLETE };
1321 
1322 class LeImplTestParameterizedByConnectionCompleteEventType
1323     : public LeImplTest,
1324       public ::testing::WithParamInterface<ConnectionCompleteType> {};
1325 
TEST_P(LeImplTestParameterizedByConnectionCompleteEventType,ConnectionCompleteAsPeripheralWithAdvertisingSet)1326 TEST_P(LeImplTestParameterizedByConnectionCompleteEventType,
1327        ConnectionCompleteAsPeripheralWithAdvertisingSet) {
1328   // arrange
1329   controller_->AddSupported(hci::OpCode::LE_MULTI_ADVT);
1330   set_random_device_address_policy();
1331 
1332   auto advertising_set_id = 13;
1333 
1334   hci::Address advertiser_address;
1335   Address::FromString("A0:A1:A2:A3:A4:A5", advertiser_address);
1336   hci::AddressWithType advertiser_address_with_type(advertiser_address,
1337                                                     hci::AddressType::PUBLIC_DEVICE_ADDRESS);
1338 
1339   // expect
1340   ::testing::InSequence s;
1341   MockFunction<void(std::string check_point_name)> check;
1342   std::unique_ptr<LeAclConnection> connection{};
1343   EXPECT_CALL(check, Call("terminating_advertising_set"));
1344   EXPECT_CALL(mock_le_connection_callbacks_,
1345               OnLeConnectSuccess(remote_public_address_with_type_, _))
1346           .WillOnce(WithArg<1>(::testing::Invoke(
1347                   [&](std::unique_ptr<LeAclConnection> conn) { connection = std::move(conn); })));
1348 
1349   // act
1350   switch (GetParam()) {
1351     case ConnectionCompleteType::CONNECTION_COMPLETE: {
1352       hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1353               ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1354               remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30));
1355     } break;
1356     case ConnectionCompleteType::ENHANCED_CONNECTION_COMPLETE: {
1357       hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
1358               ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1359               remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011,
1360               ClockAccuracy::PPM_30));
1361     } break;
1362     default: {
1363       log::fatal("unexpected case");
1364     }
1365   }
1366   sync_handler();
1367 
1368   check.Call("terminating_advertising_set");
1369   le_impl_->OnAdvertisingSetTerminated(kHciHandle, advertising_set_id, advertiser_address_with_type,
1370                                        false /* is_discoverable */);
1371   sync_handler();
1372 
1373   // assert
1374   Mock::VerifyAndClearExpectations(&mock_le_connection_callbacks_);
1375   ASSERT_NE(connection, nullptr);
1376   EXPECT_THAT(connection->GetRoleSpecificData(),
1377               VariantWith<DataAsPeripheral>(Field("local_address", &DataAsPeripheral::local_address,
1378                                                   Eq(advertiser_address_with_type))));
1379 }
1380 
1381 INSTANTIATE_TEST_SUITE_P(ConnectionCompleteAsPeripheralWithAdvertisingSet,
1382                          LeImplTestParameterizedByConnectionCompleteEventType,
1383                          ::testing::Values(ConnectionCompleteType::CONNECTION_COMPLETE,
1384                                            ConnectionCompleteType::ENHANCED_CONNECTION_COMPLETE));
1385 
1386 class LeImplTestParameterizedByDiscoverability : public LeImplTest,
1387                                                  public ::testing::WithParamInterface<bool> {};
1388 
TEST_P(LeImplTestParameterizedByDiscoverability,ConnectionCompleteAsDiscoverable)1389 TEST_P(LeImplTestParameterizedByDiscoverability, ConnectionCompleteAsDiscoverable) {
1390   // arrange
1391   controller_->AddSupported(hci::OpCode::LE_MULTI_ADVT);
1392   set_random_device_address_policy();
1393   auto is_discoverable = GetParam();
1394 
1395   // expect
1396   std::unique_ptr<LeAclConnection> connection{};
1397   EXPECT_CALL(mock_le_connection_callbacks_,
1398               OnLeConnectSuccess(remote_public_address_with_type_, _))
1399           .WillOnce(WithArg<1>(::testing::Invoke(
1400                   [&](std::unique_ptr<LeAclConnection> conn) { connection = std::move(conn); })));
1401 
1402   // act
1403   hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1404           ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1405           remote_address_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30));
1406   // the sync is needed since otherwise the OnAdvertisingSetTerminated() event arrives first, due to
1407   // handler indirection (2 hops vs 1 hop) this isn't a bug in production since there we'd have:
1408   // 1. Connection Complete: HCI -> LE_IMPL (2 hops)
1409   // 2. Advertising Set Terminated: HCI -> ADV -> LE_IMPL (3 hops)
1410   // so this sync is only needed in test
1411   sync_handler();
1412   le_impl_->OnAdvertisingSetTerminated(kHciHandle, 1 /* advertiser_set_id */, fixed_address_,
1413                                        is_discoverable);
1414   sync_handler();
1415 
1416   // assert
1417   ASSERT_NE(connection, nullptr);
1418   EXPECT_THAT(connection->GetRoleSpecificData(),
1419               VariantWith<DataAsPeripheral>(Field("connected_to_discoverable",
1420                                                   &DataAsPeripheral::connected_to_discoverable,
1421                                                   Eq(is_discoverable))));
1422 }
1423 
1424 INSTANTIATE_TEST_SUITE_P(LeImplTestParameterizedByDiscoverability,
1425                          LeImplTestParameterizedByDiscoverability, ::testing::Values(false, true));
1426 
TEST_F(LeImplTest,ConnectionCompleteAcceptlistCallback)1427 TEST_F(LeImplTest, ConnectionCompleteAcceptlistCallback) {
1428   // arrange
1429   MockLeAcceptlistCallbacks callbacks;
1430   le_impl_->handle_register_le_acceptlist_callbacks(&callbacks);
1431   set_random_device_address_policy();
1432 
1433   // expect
1434   AddressWithType remote_address;
1435   EXPECT_CALL(callbacks, OnLeConnectSuccess(_)).WillOnce([&](AddressWithType addr) {
1436     remote_address = addr;
1437   });
1438 
1439   // act
1440   auto command = LeEnhancedConnectionCompleteBuilder::Create(
1441           ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1442           remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30);
1443   auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
1444   auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
1445   ASSERT_TRUE(view.IsValid());
1446   le_impl_->on_le_event(view);
1447   sync_handler();
1448 
1449   // assert
1450   ASSERT_EQ(remote_public_address_with_type_, remote_address);
1451 }
1452 
TEST_F(LeImplTest,ResolvingListCallback)1453 TEST_F(LeImplTest, ResolvingListCallback) {
1454   // arrange
1455   MockLeAcceptlistCallbacks callbacks;
1456   le_impl_->handle_register_le_acceptlist_callbacks(&callbacks);
1457 
1458   // expect
1459   AddressWithType remote_address;
1460   EXPECT_CALL(callbacks, OnResolvingListChange()).Times(1);
1461 
1462   // act
1463   le_impl_->add_device_to_resolving_list(remote_public_address_with_type_,
1464                                          kPeerIdentityResolvingKey, kLocalIdentityResolvingKey);
1465 
1466   // assert
1467   Mock::VerifyAndClearExpectations(&callbacks);
1468 }
1469 
TEST_F(LeImplTest,ConnectionFailedAcceptlistCallback)1470 TEST_F(LeImplTest, ConnectionFailedAcceptlistCallback) {
1471   // arrange
1472   MockLeAcceptlistCallbacks callbacks;
1473   le_impl_->handle_register_le_acceptlist_callbacks(&callbacks);
1474   set_random_device_address_policy();
1475 
1476   // expect
1477   AddressWithType remote_address;
1478   ErrorCode reason;
1479   EXPECT_CALL(callbacks, OnLeConnectFail(_, _))
1480           .WillOnce([&](AddressWithType addr, ErrorCode error) {
1481             remote_address = addr;
1482             reason = error;
1483           });
1484 
1485   // act
1486   auto command = LeEnhancedConnectionCompleteBuilder::Create(
1487           ErrorCode::CONTROLLER_BUSY, kHciHandle, Role::PERIPHERAL,
1488           AddressType::PUBLIC_DEVICE_ADDRESS, remote_address_, local_rpa_, remote_rpa_, 0x0024,
1489           0x0000, 0x0011, ClockAccuracy::PPM_30);
1490   auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
1491   auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
1492   ASSERT_TRUE(view.IsValid());
1493   le_impl_->on_le_event(view);
1494   sync_handler();
1495 
1496   // assert
1497   EXPECT_EQ(remote_address, remote_public_address_with_type_);
1498   EXPECT_EQ(reason, ErrorCode::CONTROLLER_BUSY);
1499 }
1500 
TEST_F(LeImplTest,DisconnectionAcceptlistCallback)1501 TEST_F(LeImplTest, DisconnectionAcceptlistCallback) {
1502   // expect
1503   MockLeAcceptlistCallbacks callbacks;
1504   AddressWithType remote_address;
1505   EXPECT_CALL(callbacks, OnLeDisconnection(_)).WillOnce([&](AddressWithType addr) {
1506     remote_address = addr;
1507   });
1508   // we need to capture the LeAclConnection so it is not immediately dropped => disconnected
1509   std::unique_ptr<LeAclConnection> connection;
1510   EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _))
1511           .WillOnce([&](AddressWithType, std::unique_ptr<LeAclConnection> conn) {
1512             connection = std::move(conn);
1513             connection->RegisterCallbacks(&connection_management_callbacks_, handler_);
1514           });
1515 
1516   // arrange: an active connection to a peer
1517   le_impl_->handle_register_le_acceptlist_callbacks(&callbacks);
1518   set_random_device_address_policy();
1519   auto command = LeEnhancedConnectionCompleteBuilder::Create(
1520           ErrorCode::SUCCESS, kHciHandle, Role::PERIPHERAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1521           remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30);
1522   auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
1523   auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
1524   ASSERT_TRUE(view.IsValid());
1525   le_impl_->on_le_event(view);
1526   sync_handler();
1527 
1528   // act
1529   le_impl_->on_le_disconnect(kHciHandle, ErrorCode::REMOTE_USER_TERMINATED_CONNECTION);
1530   sync_handler();
1531 
1532   // assert
1533   EXPECT_EQ(remote_public_address_with_type_, remote_address);
1534   Mock::VerifyAndClearExpectations(&callbacks);
1535 }
1536 
TEST_F(LeImplTest,direct_connection_after_background_connection)1537 TEST_F(LeImplTest, direct_connection_after_background_connection) {
1538   set_random_device_address_policy();
1539 
1540   hci::AddressWithType address({0x21, 0x22, 0x23, 0x24, 0x25, 0x26},
1541                                AddressType::PUBLIC_DEVICE_ADDRESS);
1542 
1543   // arrange: Create background connection. Remember that acl_manager adds device background list
1544   le_impl_->add_device_to_background_connection_list(address);
1545   le_impl_->create_le_connection(address, true, /* is_direct */ false);
1546   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1547   hci_layer_->IncomingEvent(
1548           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1549   auto raw_bg_create_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
1550   hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1551   sync_handler();
1552 
1553   // act: Create direct connection
1554   le_impl_->create_le_connection(address, true, /* is_direct */ true);
1555   auto cancel_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION_CANCEL);
1556   if (cancel_connection.IsValid()) {
1557     hci_layer_->IncomingEvent(
1558             LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1559     hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1560             ErrorCode::UNKNOWN_CONNECTION, kHciHandle, Role::CENTRAL,
1561             AddressType::PUBLIC_DEVICE_ADDRESS, Address::kEmpty, 0x0000, 0x0000, 0x0000,
1562             ClockAccuracy::PPM_30));
1563   }
1564   auto raw_direct_create_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
1565 
1566   // assert
1567   auto bg_create_connection =
1568           LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(
1569                   AclCommandView::Create(raw_bg_create_connection)));
1570   EXPECT_TRUE(bg_create_connection.IsValid());
1571   auto direct_create_connection =
1572           LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(
1573                   AclCommandView::Create(raw_direct_create_connection)));
1574   EXPECT_TRUE(direct_create_connection.IsValid());
1575   log::info("Scan Interval {}", direct_create_connection.GetLeScanInterval());
1576   ASSERT_NE(direct_create_connection.GetLeScanInterval(), bg_create_connection.GetLeScanInterval());
1577 
1578   hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1579   sync_handler();
1580 
1581   // Check state is ARMED
1582   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
1583 
1584   // Simulate timeout on direct connect. Verify background connect is still in place
1585   EXPECT_CALL(mock_le_connection_callbacks_,
1586               OnLeConnectFail(_, ErrorCode::CONNECTION_ACCEPT_TIMEOUT))
1587           .Times(1);
1588   le_impl_->on_create_connection_timeout(address);
1589   sync_handler();
1590   cancel_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION_CANCEL);
1591   hci_layer_->IncomingEvent(
1592           LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1593   hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1594           ErrorCode::UNKNOWN_CONNECTION, kHciHandle, Role::CENTRAL,
1595           AddressType::PUBLIC_DEVICE_ADDRESS, Address::kEmpty, 0x0000, 0x0000, 0x0000,
1596           ClockAccuracy::PPM_30));
1597   EXPECT_TRUE(cancel_connection.IsValid());
1598   raw_bg_create_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
1599   bg_create_connection = LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(
1600           AclCommandView::Create(raw_bg_create_connection)));
1601   EXPECT_TRUE(bg_create_connection.IsValid());
1602   sync_handler();
1603   ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty());
1604 
1605   hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1606   sync_handler();
1607 
1608   // Check state is ARMED
1609   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
1610 }
1611 
TEST_F(LeImplTest,direct_connection_after_direct_connection)1612 TEST_F(LeImplTest, direct_connection_after_direct_connection) {
1613   set_random_device_address_policy();
1614 
1615   hci::AddressWithType address({0x21, 0x22, 0x23, 0x24, 0x25, 0x26},
1616                                AddressType::PUBLIC_DEVICE_ADDRESS);
1617 
1618   // Create first direct connection
1619   le_impl_->create_le_connection(address, true, /* is_direct */ true);
1620   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1621   hci_layer_->IncomingEvent(
1622           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1623   auto raw_direct_1_create_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
1624   hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1625   sync_handler();
1626 
1627   // Check state is ARMED
1628   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
1629 
1630   // assert
1631   auto direct_1_create_connection =
1632           LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(
1633                   AclCommandView::Create(raw_direct_1_create_connection)));
1634   EXPECT_TRUE(direct_1_create_connection.IsValid());
1635 
1636   log::info("Second direct connect to the same device");
1637 
1638   // Create second direct connection
1639   le_impl_->create_le_connection(address, true, /* is_direct */ true);
1640   sync_handler();
1641 
1642   CommandView cancel_connection = CommandView::Create(
1643           PacketView<packet::kLittleEndian>(std::make_shared<std::vector<uint8_t>>()));
1644 
1645   hci_layer_->AssertNoQueuedCommand();
1646 
1647   log::info("Simulate timeout");
1648 
1649   EXPECT_CALL(mock_le_connection_callbacks_,
1650               OnLeConnectFail(_, ErrorCode::CONNECTION_ACCEPT_TIMEOUT))
1651           .Times(1);
1652   le_impl_->on_create_connection_timeout(address);
1653   sync_handler();
1654   cancel_connection = hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION_CANCEL);
1655   EXPECT_TRUE(cancel_connection.IsValid());
1656   hci_layer_->IncomingEvent(
1657           LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1658   hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1659           ErrorCode::UNKNOWN_CONNECTION, kHciHandle, Role::CENTRAL,
1660           AddressType::PUBLIC_DEVICE_ADDRESS, Address::kEmpty, 0x0000, 0x0000, 0x0000,
1661           ClockAccuracy::PPM_30));
1662   sync_handler();
1663   ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty());
1664 
1665   hci_layer_->GetCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
1666   hci_layer_->IncomingEvent(
1667           LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1668   hci_layer_->AssertNoQueuedCommand();
1669   ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
1670 }
1671 
TEST_F(LeImplTest,direct_connection_cancel_but_connected)1672 TEST_F(LeImplTest, direct_connection_cancel_but_connected) {
1673   com::android::bluetooth::flags::provider_->le_impl_ack_pause_disarmed(true);
1674 
1675   set_random_device_address_policy();
1676   controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
1677 
1678   hci::AddressWithType address({0x21, 0x22, 0x23, 0x24, 0x25, 0x26},
1679                                AddressType::PUBLIC_DEVICE_ADDRESS);
1680 
1681   // Create first direct connection
1682   le_impl_->create_le_connection(address, true, /* is_direct */ true);
1683   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1684   hci_layer_->IncomingEvent(
1685           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1686   hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
1687   hci_layer_->IncomingEvent(
1688           LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1689   sync_handler();
1690   ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
1691 
1692   // Cancel the connection
1693   le_impl_->cancel_connect(address);
1694   hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION_CANCEL);
1695   hci_layer_->IncomingEvent(
1696           LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1697 
1698   // According to the spec, UNKNOWN_CONNECTION should be reported but some controller could
1699   // report SUCCESS when there is a race between cancel and connect.
1700   hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
1701           ErrorCode::SUCCESS, kHciHandle, Role::CENTRAL, AddressType::PUBLIC_DEVICE_ADDRESS,
1702           remote_address_, local_rpa_, remote_rpa_, 0x0024, 0x0000, 0x0011, ClockAccuracy::PPM_30));
1703   sync_handler();
1704   ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
1705   ASSERT_TRUE(le_impl_->accept_list.empty());
1706 
1707   // Disconnect and reconnect
1708   le_impl_->on_le_disconnect(kHciHandle, ErrorCode::REMOTE_USER_TERMINATED_CONNECTION);
1709   sync_handler();
1710 
1711   le_impl_->create_le_connection(address, true, /* is_direct */ true);
1712   ASSERT_TRUE(le_impl_->accept_list.contains(address));
1713   sync_handler();
1714 
1715   le_impl_->OnPause();
1716   hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1717   hci_layer_->IncomingEvent(
1718           LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1719   hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
1720   hci_layer_->IncomingEvent(
1721           LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1722   sync_handler();
1723 }
1724 
1725 }  // namespace acl_manager
1726 }  // namespace hci
1727 }  // namespace bluetooth
1728