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