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