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