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::SaveArg;
53
54 namespace {
55 constexpr char kFixedAddress[] = "c0:aa:bb:cc:dd:ee";
56 constexpr char kRemoteAddress[] = "00:11:22:33:44:55";
57 constexpr bool kCrashOnUnknownHandle = true;
58 constexpr char kLocalRandomAddress[] = "04:c0:aa:bb:cc:dd:ee";
59 constexpr char kRemoteRandomAddress[] = "04:11:22:33:44:55";
60 constexpr uint16_t kHciHandle = 123;
61 [[maybe_unused]] constexpr bool kAddToFilterAcceptList = true;
62 [[maybe_unused]] constexpr bool kSkipFilterAcceptList = !kAddToFilterAcceptList;
63 [[maybe_unused]] constexpr bool kIsDirectConnection = true;
64 [[maybe_unused]] constexpr bool kIsBackgroundConnection = !kIsDirectConnection;
65 constexpr crypto_toolbox::Octet16 kRotationIrk = {};
66 constexpr std::chrono::milliseconds kMinimumRotationTime(14 * 1000);
67 constexpr std::chrono::milliseconds kMaximumRotationTime(16 * 1000);
68 constexpr uint16_t kIntervalMax = 0x40;
69 constexpr uint16_t kIntervalMin = 0x20;
70 constexpr uint16_t kLatency = 0x60;
71 constexpr uint16_t kLength = 0x5678;
72 constexpr uint16_t kTime = 0x1234;
73 constexpr uint16_t kTimeout = 0x80;
74 constexpr std::array<uint8_t, 16> kPeerIdentityResolvingKey({
75 0x00,
76 0x01,
77 0x02,
78 0x03,
79 0x04,
80 0x05,
81 0x06,
82 0x07,
83 0x08,
84 0x09,
85 0x0a,
86 0x0b,
87 0x0c,
88 0x0d,
89 0x0e,
90 0x0f,
91 });
92 constexpr std::array<uint8_t, 16> kLocalIdentityResolvingKey({
93 0x80,
94 0x81,
95 0x82,
96 0x83,
97 0x84,
98 0x85,
99 0x86,
100 0x87,
101 0x88,
102 0x89,
103 0x8a,
104 0x8b,
105 0x8c,
106 0x8d,
107 0x8e,
108 0x8f,
109 });
110
111 template <typename B>
Serialize(std::unique_ptr<B> build)112 std::shared_ptr<std::vector<uint8_t>> Serialize(std::unique_ptr<B> build) {
113 auto bytes = std::make_shared<std::vector<uint8_t>>();
114 BitInserter bi(*bytes);
115 build->Serialize(bi);
116 return bytes;
117 }
118
119 template <typename T>
CreateCommandView(std::shared_ptr<std::vector<uint8_t>> bytes)120 T CreateCommandView(std::shared_ptr<std::vector<uint8_t>> bytes) {
121 return T::Create(hci::CommandView::Create(hci::PacketView<hci::kLittleEndian>(bytes)));
122 }
123
124 template <typename T>
CreateAclCommandView(std::shared_ptr<std::vector<uint8_t>> bytes)125 T CreateAclCommandView(std::shared_ptr<std::vector<uint8_t>> bytes) {
126 return T::Create(CreateCommandView<hci::AclCommandView>(bytes));
127 }
128
129 template <typename T>
CreateLeConnectionManagementCommandView(std::shared_ptr<std::vector<uint8_t>> bytes)130 T CreateLeConnectionManagementCommandView(std::shared_ptr<std::vector<uint8_t>> bytes) {
131 return T::Create(CreateAclCommandView<hci::LeConnectionManagementCommandView>(bytes));
132 }
133
134 template <typename T>
CreateLeSecurityCommandView(std::shared_ptr<std::vector<uint8_t>> bytes)135 T CreateLeSecurityCommandView(std::shared_ptr<std::vector<uint8_t>> bytes) {
136 return T::Create(CreateCommandView<hci::LeSecurityCommandView>(bytes));
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 [[maybe_unused]] 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 [[maybe_unused]] 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
GetPacketView(std::unique_ptr<packet::BasePacketBuilder> packet)167 PacketView<kLittleEndian> GetPacketView(std::unique_ptr<packet::BasePacketBuilder> packet) {
168 auto bytes = std::make_shared<std::vector<uint8_t>>();
169 BitInserter i(*bytes);
170 bytes->reserve(packet->size());
171 packet->Serialize(i);
172 return packet::PacketView<packet::kLittleEndian>(bytes);
173 }
174
175 class TestController : public Controller {
176 public:
IsSupported(OpCode op_code) const177 bool IsSupported(OpCode op_code) const override {
178 LOG_INFO("IsSupported");
179 return supported_opcodes_.count(op_code) == 1;
180 }
181
AddSupported(OpCode op_code)182 void AddSupported(OpCode op_code) {
183 LOG_INFO("AddSupported");
184 supported_opcodes_.insert(op_code);
185 }
186
GetNumAclPacketBuffers() const187 uint16_t GetNumAclPacketBuffers() const {
188 return max_acl_packet_credits_;
189 }
190
GetAclPacketLength() const191 uint16_t GetAclPacketLength() const {
192 return hci_mtu_;
193 }
194
GetLeBufferSize() const195 LeBufferSize GetLeBufferSize() const {
196 LeBufferSize le_buffer_size;
197 le_buffer_size.le_data_packet_length_ = le_hci_mtu_;
198 le_buffer_size.total_num_le_packets_ = le_max_acl_packet_credits_;
199 return le_buffer_size;
200 }
201
RegisterCompletedAclPacketsCallback(CompletedAclPacketsCallback cb)202 void RegisterCompletedAclPacketsCallback(CompletedAclPacketsCallback cb) {
203 acl_credits_callback_ = cb;
204 }
205
SendCompletedAclPacketsCallback(uint16_t handle,uint16_t credits)206 void SendCompletedAclPacketsCallback(uint16_t handle, uint16_t credits) {
207 acl_credits_callback_.Invoke(handle, credits);
208 }
209
UnregisterCompletedAclPacketsCallback()210 void UnregisterCompletedAclPacketsCallback() {
211 acl_credits_callback_ = {};
212 }
213
SupportsBlePrivacy() const214 bool SupportsBlePrivacy() const override {
215 return supports_ble_privacy_;
216 }
217 bool supports_ble_privacy_{false};
218
219 public:
220 const uint16_t max_acl_packet_credits_ = 10;
221 const uint16_t hci_mtu_ = 1024;
222 const uint16_t le_max_acl_packet_credits_ = 15;
223 const uint16_t le_hci_mtu_ = 27;
224
225 private:
226 CompletedAclPacketsCallback acl_credits_callback_;
227 std::set<OpCode> supported_opcodes_{};
228 };
229
230 class TestHciLayer : public HciLayer {
231 // This is a springboard class that converts from `AclCommandBuilder`
232 // to `ComandBuilder` for use in the hci layer.
233 template <typename T>
234 class CommandInterfaceImpl : public CommandInterface<T> {
235 public:
CommandInterfaceImpl(HciLayer & hci)236 explicit CommandInterfaceImpl(HciLayer& hci) : hci_(hci) {}
237 ~CommandInterfaceImpl() = default;
238
EnqueueCommand(std::unique_ptr<T> command,common::ContextualOnceCallback<void (CommandCompleteView)> on_complete)239 void EnqueueCommand(
240 std::unique_ptr<T> command, common::ContextualOnceCallback<void(CommandCompleteView)> on_complete) override {
241 hci_.EnqueueCommand(move(command), std::move(on_complete));
242 }
243
EnqueueCommand(std::unique_ptr<T> command,common::ContextualOnceCallback<void (CommandStatusView)> on_status)244 void EnqueueCommand(
245 std::unique_ptr<T> command, common::ContextualOnceCallback<void(CommandStatusView)> on_status) override {
246 hci_.EnqueueCommand(move(command), std::move(on_status));
247 }
248 HciLayer& hci_;
249 };
250
EnqueueCommand(std::unique_ptr<CommandBuilder> command,common::ContextualOnceCallback<void (CommandStatusView)> on_status)251 void EnqueueCommand(
252 std::unique_ptr<CommandBuilder> command,
253 common::ContextualOnceCallback<void(CommandStatusView)> on_status) override {
254 const std::lock_guard<std::mutex> lock(command_queue_mutex_);
255 command_queue_.push(std::move(command));
256 command_status_callbacks.push_back(std::move(on_status));
257 if (command_promise_ != nullptr) {
258 std::promise<void>* prom = command_promise_.release();
259 prom->set_value();
260 delete prom;
261 }
262 }
263
EnqueueCommand(std::unique_ptr<CommandBuilder> command,common::ContextualOnceCallback<void (CommandCompleteView)> on_complete)264 void EnqueueCommand(
265 std::unique_ptr<CommandBuilder> command,
266 common::ContextualOnceCallback<void(CommandCompleteView)> on_complete) override {
267 const std::lock_guard<std::mutex> lock(command_queue_mutex_);
268 command_queue_.push(std::move(command));
269 command_complete_callbacks.push_back(std::move(on_complete));
270 if (command_promise_ != nullptr) {
271 std::promise<void>* prom = command_promise_.release();
272 prom->set_value();
273 delete prom;
274 }
275 }
276
277 public:
DequeueCommand()278 std::unique_ptr<CommandBuilder> DequeueCommand() {
279 const std::lock_guard<std::mutex> lock(command_queue_mutex_);
280 auto packet = std::move(command_queue_.front());
281 command_queue_.pop();
282 return std::move(packet);
283 }
284
DequeueCommandBytes()285 std::shared_ptr<std::vector<uint8_t>> DequeueCommandBytes() {
286 auto command = DequeueCommand();
287 auto bytes = std::make_shared<std::vector<uint8_t>>();
288 packet::BitInserter bi(*bytes);
289 command->Serialize(bi);
290 return bytes;
291 }
292
IsPacketQueueEmpty() const293 bool IsPacketQueueEmpty() const {
294 const std::lock_guard<std::mutex> lock(command_queue_mutex_);
295 return command_queue_.empty();
296 }
297
NumberOfQueuedCommands() const298 size_t NumberOfQueuedCommands() const {
299 const std::lock_guard<std::mutex> lock(command_queue_mutex_);
300 return command_queue_.size();
301 }
302
SetCommandFuture()303 void SetCommandFuture() {
304 ASSERT_EQ(command_promise_, nullptr) << "Promises, Promises, ... Only one at a time.";
305 command_promise_ = std::make_unique<std::promise<void>>();
306 command_future_ = std::make_unique<std::future<void>>(command_promise_->get_future());
307 }
308
GetLastCommand()309 CommandView GetLastCommand() {
310 if (command_queue_.empty()) {
311 return CommandView::Create(PacketView<kLittleEndian>(std::make_shared<std::vector<uint8_t>>()));
312 }
313 auto last = std::move(command_queue_.front());
314 command_queue_.pop();
315 return CommandView::Create(GetPacketView(std::move(last)));
316 }
317
GetCommand(OpCode op_code)318 CommandView GetCommand(OpCode op_code) {
319 if (!command_queue_.empty()) {
320 std::lock_guard<std::mutex> lock(command_queue_mutex_);
321 if (command_future_ != nullptr) {
322 command_future_.reset();
323 command_promise_.reset();
324 }
325 } else if (command_future_ != nullptr) {
326 auto result = command_future_->wait_for(std::chrono::milliseconds(1000));
327 EXPECT_NE(std::future_status::timeout, result);
328 }
329 std::lock_guard<std::mutex> lock(command_queue_mutex_);
330 ASSERT_LOG(
331 !command_queue_.empty(), "Expecting command %s but command queue was empty", OpCodeText(op_code).c_str());
332 CommandView command_packet_view = GetLastCommand();
333 EXPECT_TRUE(command_packet_view.IsValid());
334 EXPECT_EQ(command_packet_view.GetOpCode(), op_code);
335 return command_packet_view;
336 }
337
CommandCompleteCallback(std::unique_ptr<EventBuilder> event_builder)338 void CommandCompleteCallback(std::unique_ptr<EventBuilder> event_builder) {
339 auto event = EventView::Create(GetPacketView(std::move(event_builder)));
340 CommandCompleteView complete_view = CommandCompleteView::Create(event);
341 ASSERT_TRUE(complete_view.IsValid());
342 ASSERT_NE((uint16_t)command_complete_callbacks.size(), 0);
343 std::move(command_complete_callbacks.front()).Invoke(complete_view);
344 command_complete_callbacks.pop_front();
345 }
346
CommandStatusCallback(std::unique_ptr<EventBuilder> event_builder)347 void CommandStatusCallback(std::unique_ptr<EventBuilder> event_builder) {
348 auto event = EventView::Create(GetPacketView(std::move(event_builder)));
349 CommandStatusView status_view = CommandStatusView::Create(event);
350 ASSERT_TRUE(status_view.IsValid());
351 ASSERT_NE((uint16_t)command_status_callbacks.size(), 0);
352 std::move(command_status_callbacks.front()).Invoke(status_view);
353 command_status_callbacks.pop_front();
354 }
355
IncomingLeMetaEvent(std::unique_ptr<LeMetaEventBuilder> event_builder)356 void IncomingLeMetaEvent(std::unique_ptr<LeMetaEventBuilder> event_builder) {
357 auto packet = GetPacketView(std::move(event_builder));
358 EventView event = EventView::Create(packet);
359 LeMetaEventView meta_event_view = LeMetaEventView::Create(event);
360 EXPECT_TRUE(meta_event_view.IsValid());
361 le_event_handler_.Invoke(meta_event_view);
362 }
363
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)364 LeAclConnectionInterface* GetLeAclConnectionInterface(
365 common::ContextualCallback<void(LeMetaEventView)> event_handler,
366 common::ContextualCallback<void(uint16_t, ErrorCode)> on_disconnect,
367 common::ContextualCallback<
368 void(hci::ErrorCode hci_status, uint16_t, uint8_t version, uint16_t manufacturer_name, uint16_t sub_version)>
369 on_read_remote_version) override {
370 disconnect_handlers_.push_back(on_disconnect);
371 read_remote_version_handlers_.push_back(on_read_remote_version);
372 le_event_handler_ = event_handler;
373 return &le_acl_connection_manager_interface_;
374 }
375
PutLeAclConnectionInterface()376 void PutLeAclConnectionInterface() override {}
377
378 private:
379 std::list<common::ContextualOnceCallback<void(CommandCompleteView)>> command_complete_callbacks;
380 std::list<common::ContextualOnceCallback<void(CommandStatusView)>> command_status_callbacks;
381 common::ContextualCallback<void(LeMetaEventView)> le_event_handler_;
382 std::queue<std::unique_ptr<CommandBuilder>> command_queue_;
383 mutable std::mutex command_queue_mutex_;
384 std::unique_ptr<std::promise<void>> command_promise_;
385 std::unique_ptr<std::future<void>> command_future_;
386 CommandInterfaceImpl<AclCommandBuilder> le_acl_connection_manager_interface_{*this};
387 };
388 } // namespace
389
390 class MockLeConnectionCallbacks : public LeConnectionCallbacks {
391 public:
392 MOCK_METHOD(
393 void,
394 OnLeConnectSuccess,
395 (AddressWithType address_with_type, std::unique_ptr<LeAclConnection> connection),
396 (override));
397 MOCK_METHOD(void, OnLeConnectFail, (AddressWithType address_with_type, ErrorCode reason), (override));
398 };
399
400 class MockLeConnectionManagementCallbacks : public LeConnectionManagementCallbacks {
401 public:
402 MOCK_METHOD(
403 void,
404 OnConnectionUpdate,
405 (hci::ErrorCode hci_status,
406 uint16_t connection_interval,
407 uint16_t connection_latency,
408 uint16_t supervision_timeout),
409 (override));
410 MOCK_METHOD(
411 void,
412 OnDataLengthChange,
413 (uint16_t tx_octets, uint16_t tx_time, uint16_t rx_octets, uint16_t rx_time),
414 (override));
415 MOCK_METHOD(void, OnDisconnection, (ErrorCode reason), (override));
416 MOCK_METHOD(
417 void,
418 OnReadRemoteVersionInformationComplete,
419 (hci::ErrorCode hci_status, uint8_t lmp_version, uint16_t manufacturer_name, uint16_t sub_version),
420 (override));
421 MOCK_METHOD(void, OnLeReadRemoteFeaturesComplete, (hci::ErrorCode hci_status, uint64_t features), (override));
422 MOCK_METHOD(void, OnPhyUpdate, (hci::ErrorCode hci_status, uint8_t tx_phy, uint8_t rx_phy), (override));
423 MOCK_METHOD(void, OnLocalAddressUpdate, (AddressWithType address_with_type), (override));
424 };
425
426 class LeImplTest : public ::testing::Test {
427 protected:
SetUp()428 void SetUp() override {
429 bluetooth::common::InitFlags::SetAllForTesting();
430 thread_ = new Thread("thread", Thread::Priority::NORMAL);
431 handler_ = new Handler(thread_);
432 controller_ = new TestController();
433 hci_layer_ = new TestHciLayer();
434
435 round_robin_scheduler_ = new RoundRobinScheduler(handler_, controller_, hci_queue_.GetUpEnd());
436 hci_queue_.GetDownEnd()->RegisterDequeue(
437 handler_, common::Bind(&LeImplTest::HciDownEndDequeue, common::Unretained(this)));
438 le_impl_ = new le_impl(hci_layer_, controller_, handler_, round_robin_scheduler_, kCrashOnUnknownHandle);
439 le_impl_->handle_register_le_callbacks(&mock_le_connection_callbacks_, handler_);
440
441 Address address;
442 Address::FromString(kFixedAddress, address);
443 fixed_address_ = AddressWithType(address, AddressType::PUBLIC_DEVICE_ADDRESS);
444
445 Address::FromString(kRemoteAddress, remote_address_);
446 remote_public_address_with_type_ = AddressWithType(remote_address_, AddressType::PUBLIC_DEVICE_ADDRESS);
447
448 Address::FromString(kLocalRandomAddress, local_rpa_);
449 Address::FromString(kRemoteRandomAddress, remote_rpa_);
450 }
451
set_random_device_address_policy()452 void set_random_device_address_policy() {
453 // Set address policy
454 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
455 hci::Address address;
456 Address::FromString("D0:05:04:03:02:01", address);
457 hci::AddressWithType address_with_type(address, hci::AddressType::RANDOM_DEVICE_ADDRESS);
458 crypto_toolbox::Octet16 rotation_irk{};
459 auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000);
460 auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000);
461 le_impl_->set_privacy_policy_for_initiator_address(
462 LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS,
463 address_with_type,
464 rotation_irk,
465 minimum_rotation_time,
466 maximum_rotation_time);
467 hci_layer_->GetCommand(OpCode::LE_SET_RANDOM_ADDRESS);
468 hci_layer_->CommandCompleteCallback(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
469 }
470
TearDown()471 void TearDown() override {
472 // We cannot teardown our structure without unregistering
473 // from our own structure we created.
474 if (le_impl_->address_manager_registered) {
475 le_impl_->ready_to_unregister = true;
476 le_impl_->check_for_unregister();
477 sync_handler();
478 }
479
480 sync_handler();
481 delete le_impl_;
482
483 hci_queue_.GetDownEnd()->UnregisterDequeue();
484
485 delete hci_layer_;
486 delete round_robin_scheduler_;
487 delete controller_;
488
489 handler_->Clear();
490 delete handler_;
491 delete thread_;
492 }
493
sync_handler()494 void sync_handler() {
495 std::promise<void> promise;
496 auto future = promise.get_future();
497 handler_->BindOnceOn(&promise, &std::promise<void>::set_value).Invoke();
498 auto status = future.wait_for(2s);
499 ASSERT_EQ(status, std::future_status::ready);
500 }
501
HciDownEndDequeue()502 void HciDownEndDequeue() {
503 auto packet = hci_queue_.GetDownEnd()->TryDequeue();
504 // Convert from a Builder to a View
505 auto bytes = std::make_shared<std::vector<uint8_t>>();
506 bluetooth::packet::BitInserter i(*bytes);
507 bytes->reserve(packet->size());
508 packet->Serialize(i);
509 auto packet_view = bluetooth::packet::PacketView<bluetooth::packet::kLittleEndian>(bytes);
510 AclView acl_packet_view = AclView::Create(packet_view);
511 ASSERT_TRUE(acl_packet_view.IsValid());
512 PacketView<true> count_view = acl_packet_view.GetPayload();
513 sent_acl_packets_.push(acl_packet_view);
514
515 packet_count_--;
516 if (packet_count_ == 0) {
517 packet_promise_->set_value();
518 packet_promise_ = nullptr;
519 }
520 }
521
522 protected:
set_privacy_policy_for_initiator_address(const AddressWithType & address,const LeAddressManager::AddressPolicy & policy)523 void set_privacy_policy_for_initiator_address(
524 const AddressWithType& address, const LeAddressManager::AddressPolicy& policy) {
525 le_impl_->set_privacy_policy_for_initiator_address(
526 policy, address, kRotationIrk, kMinimumRotationTime, kMaximumRotationTime);
527 }
528
529 Address local_rpa_;
530 Address remote_address_;
531 Address remote_rpa_;
532 AddressWithType fixed_address_;
533 AddressWithType remote_public_address_;
534 AddressWithType remote_public_address_with_type_;
535
536 uint16_t packet_count_;
537 std::unique_ptr<std::promise<void>> packet_promise_;
538 std::unique_ptr<std::future<void>> packet_future_;
539 std::queue<AclView> sent_acl_packets_;
540
541 BidiQueue<AclView, AclBuilder> hci_queue_{3};
542
543 Thread* thread_;
544 Handler* handler_;
545 TestHciLayer* hci_layer_{nullptr};
546 TestController* controller_;
547 RoundRobinScheduler* round_robin_scheduler_{nullptr};
548
549 MockLeConnectionCallbacks mock_le_connection_callbacks_;
550 MockLeConnectionManagementCallbacks connection_management_callbacks_;
551
552 struct le_impl* le_impl_;
553 };
554
555 class LeImplRegisteredWithAddressManagerTest : public LeImplTest {
556 protected:
SetUp()557 void SetUp() override {
558 LeImplTest::SetUp();
559 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
560
561 le_impl_->register_with_address_manager();
562 sync_handler(); // Let |LeAddressManager::register_client| execute on handler
563 ASSERT_TRUE(le_impl_->address_manager_registered);
564 ASSERT_TRUE(le_impl_->pause_connection);
565 }
566
TearDown()567 void TearDown() override {
568 LeImplTest::TearDown();
569 }
570 };
571
572 class LeImplWithConnectionTest : public LeImplTest {
573 protected:
SetUp()574 void SetUp() override {
575 LeImplTest::SetUp();
576 set_random_device_address_policy();
577
578 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _))
579 .WillOnce([&](AddressWithType addr, std::unique_ptr<LeAclConnection> conn) {
580 remote_address_with_type_ = addr;
581 connection_ = std::move(conn);
582 connection_->RegisterCallbacks(&connection_management_callbacks_, handler_);
583 });
584
585 auto command = LeEnhancedConnectionCompleteBuilder::Create(
586 ErrorCode::SUCCESS,
587 kHciHandle,
588 Role::PERIPHERAL,
589 AddressType::PUBLIC_DEVICE_ADDRESS,
590 remote_address_,
591 local_rpa_,
592 remote_rpa_,
593 0x0024,
594 0x0000,
595 0x0011,
596 ClockAccuracy::PPM_30);
597 auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
598 auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
599 ASSERT_TRUE(view.IsValid());
600 le_impl_->on_le_event(view);
601
602 sync_handler();
603 ASSERT_EQ(remote_public_address_with_type_, remote_address_with_type_);
604 }
605
TearDown()606 void TearDown() override {
607 connection_.reset();
608 LeImplTest::TearDown();
609 }
610
611 AddressWithType remote_address_with_type_;
612 std::unique_ptr<LeAclConnection> connection_;
613 };
614
TEST_F(LeImplTest,add_device_to_connect_list)615 TEST_F(LeImplTest, add_device_to_connect_list) {
616 le_impl_->add_device_to_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
617 ASSERT_EQ(1UL, le_impl_->connect_list.size());
618
619 le_impl_->add_device_to_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
620 ASSERT_EQ(2UL, le_impl_->connect_list.size());
621
622 le_impl_->add_device_to_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
623 ASSERT_EQ(2UL, le_impl_->connect_list.size());
624
625 le_impl_->add_device_to_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
626 ASSERT_EQ(2UL, le_impl_->connect_list.size());
627 }
628
TEST_F(LeImplTest,remove_device_from_connect_list)629 TEST_F(LeImplTest, remove_device_from_connect_list) {
630 le_impl_->add_device_to_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
631 le_impl_->add_device_to_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
632 le_impl_->add_device_to_connect_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
633 le_impl_->add_device_to_connect_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
634 ASSERT_EQ(4UL, le_impl_->connect_list.size());
635
636 le_impl_->remove_device_from_connect_list({{0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, AddressType::PUBLIC_DEVICE_ADDRESS});
637 ASSERT_EQ(3UL, le_impl_->connect_list.size());
638
639 le_impl_->remove_device_from_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
640 ASSERT_EQ(2UL, le_impl_->connect_list.size());
641
642 le_impl_->remove_device_from_connect_list({{0x11, 0x12, 0x13, 0x14, 0x15, 0x16}, AddressType::PUBLIC_DEVICE_ADDRESS});
643 ASSERT_EQ(2UL, le_impl_->connect_list.size());
644
645 le_impl_->remove_device_from_connect_list({Address::kEmpty, AddressType::PUBLIC_DEVICE_ADDRESS});
646 ASSERT_EQ(2UL, le_impl_->connect_list.size());
647
648 le_impl_->remove_device_from_connect_list({{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS});
649 le_impl_->remove_device_from_connect_list({{0x31, 0x32, 0x33, 0x34, 0x35, 0x36}, AddressType::PUBLIC_DEVICE_ADDRESS});
650 ASSERT_EQ(0UL, le_impl_->connect_list.size());
651 }
652
TEST_F(LeImplTest,connection_complete_with_periperal_role)653 TEST_F(LeImplTest, connection_complete_with_periperal_role) {
654 set_random_device_address_policy();
655
656 // Create connection
657 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
658 le_impl_->create_le_connection(
659 {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false);
660 hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
661 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
662 hci_layer_->CommandCompleteCallback(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
663 hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
664 hci_layer_->CommandStatusCallback(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
665 sync_handler();
666
667 // Check state is ARMED
668 ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
669
670 // Receive connection complete of incoming connection (Role::PERIPHERAL)
671 hci::Address remote_address;
672 Address::FromString("D0:05:04:03:02:01", remote_address);
673 hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
674 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
675 hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
676 ErrorCode::SUCCESS,
677 0x0041,
678 Role::PERIPHERAL,
679 AddressType::PUBLIC_DEVICE_ADDRESS,
680 remote_address,
681 0x0024,
682 0x0000,
683 0x0011,
684 ClockAccuracy::PPM_30));
685 sync_handler();
686
687 // Check state is still ARMED
688 ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
689 }
690
TEST_F(LeImplTest,enhanced_connection_complete_with_periperal_role)691 TEST_F(LeImplTest, enhanced_connection_complete_with_periperal_role) {
692 set_random_device_address_policy();
693
694 controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
695 // Create connection
696 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
697 le_impl_->create_le_connection(
698 {{0x21, 0x22, 0x23, 0x24, 0x25, 0x26}, AddressType::PUBLIC_DEVICE_ADDRESS}, true, false);
699 hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
700 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
701 hci_layer_->CommandCompleteCallback(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
702 hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
703 hci_layer_->CommandStatusCallback(LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
704 sync_handler();
705
706 // Check state is ARMED
707 ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
708
709 // Receive connection complete of incoming connection (Role::PERIPHERAL)
710 hci::Address remote_address;
711 Address::FromString("D0:05:04:03:02:01", remote_address);
712 hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
713 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
714 hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
715 ErrorCode::SUCCESS,
716 0x0041,
717 Role::PERIPHERAL,
718 AddressType::PUBLIC_DEVICE_ADDRESS,
719 remote_address,
720 Address::kEmpty,
721 Address::kEmpty,
722 0x0024,
723 0x0000,
724 0x0011,
725 ClockAccuracy::PPM_30));
726 sync_handler();
727
728 // Check state is still ARMED
729 ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
730 }
731
TEST_F(LeImplTest,connection_complete_with_central_role)732 TEST_F(LeImplTest, connection_complete_with_central_role) {
733 set_random_device_address_policy();
734
735 hci::Address remote_address;
736 Address::FromString("D0:05:04:03:02:01", remote_address);
737 hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
738 // Create connection
739 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
740 le_impl_->create_le_connection(address_with_type, true, false);
741 hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
742 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
743 hci_layer_->CommandCompleteCallback(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
744 hci_layer_->GetCommand(OpCode::LE_CREATE_CONNECTION);
745 hci_layer_->CommandStatusCallback(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
746 sync_handler();
747
748 // Check state is ARMED
749 ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
750
751 // Receive connection complete of outgoing connection (Role::CENTRAL)
752 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
753 hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
754 ErrorCode::SUCCESS,
755 0x0041,
756 Role::CENTRAL,
757 AddressType::PUBLIC_DEVICE_ADDRESS,
758 remote_address,
759 0x0024,
760 0x0000,
761 0x0011,
762 ClockAccuracy::PPM_30));
763 sync_handler();
764
765 // Check state is DISARMED
766 ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
767 }
768
TEST_F(LeImplTest,enhanced_connection_complete_with_central_role)769 TEST_F(LeImplTest, enhanced_connection_complete_with_central_role) {
770 set_random_device_address_policy();
771
772 controller_->AddSupported(OpCode::LE_EXTENDED_CREATE_CONNECTION);
773 hci::Address remote_address;
774 Address::FromString("D0:05:04:03:02:01", remote_address);
775 hci::AddressWithType address_with_type(remote_address, hci::AddressType::PUBLIC_DEVICE_ADDRESS);
776 // Create connection
777 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
778 le_impl_->create_le_connection(address_with_type, true, false);
779 hci_layer_->GetCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
780 ASSERT_NO_FATAL_FAILURE(hci_layer_->SetCommandFuture());
781 hci_layer_->CommandCompleteCallback(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
782 hci_layer_->GetCommand(OpCode::LE_EXTENDED_CREATE_CONNECTION);
783 hci_layer_->CommandStatusCallback(LeExtendedCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
784 sync_handler();
785
786 // Check state is ARMED
787 ASSERT_EQ(ConnectabilityState::ARMED, le_impl_->connectability_state_);
788
789 // Receive connection complete of outgoing connection (Role::CENTRAL)
790 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(address_with_type, _));
791 hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
792 ErrorCode::SUCCESS,
793 0x0041,
794 Role::CENTRAL,
795 AddressType::PUBLIC_DEVICE_ADDRESS,
796 remote_address,
797 Address::kEmpty,
798 Address::kEmpty,
799 0x0024,
800 0x0000,
801 0x0011,
802 ClockAccuracy::PPM_30));
803 sync_handler();
804
805 // Check state is DISARMED
806 ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
807 }
808
809 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyNotSet)810 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNotSet) {
811 auto log_capture = std::make_unique<LogCapture>();
812
813 std::promise<void> promise;
814 auto future = promise.get_future();
815 handler_->Post(common::BindOnce(
816 [](struct le_impl* le_impl, os::Handler* handler, std::promise<void> promise) {
817 le_impl->register_with_address_manager();
818 handler->Post(common::BindOnce([](std::promise<void> promise) { promise.set_value(); }, std::move(promise)));
819 },
820 le_impl_,
821 handler_,
822 std::move(promise)));
823
824 // Let |LeAddressManager::register_client| execute on handler
825 auto status = future.wait_for(2s);
826 ASSERT_EQ(status, std::future_status::ready);
827
828 handler_->Post(common::BindOnce(
829 [](struct le_impl* le_impl) {
830 ASSERT_TRUE(le_impl->address_manager_registered);
831 ASSERT_TRUE(le_impl->pause_connection);
832 },
833 le_impl_));
834
835 std::promise<void> promise2;
836 auto future2 = promise2.get_future();
837 handler_->Post(common::BindOnce(
838 [](struct le_impl* le_impl, os::Handler* handler, std::promise<void> promise) {
839 le_impl->ready_to_unregister = true;
840 le_impl->check_for_unregister();
841 ASSERT_FALSE(le_impl->address_manager_registered);
842 ASSERT_FALSE(le_impl->pause_connection);
843 handler->Post(common::BindOnce([](std::promise<void> promise) { promise.set_value(); }, std::move(promise)));
844 },
845 le_impl_,
846 handler_,
847 std::move(promise2)));
848
849 // Let |LeAddressManager::unregister_client| execute on handler
850 auto status2 = future2.wait_for(2s);
851 ASSERT_EQ(status2, std::future_status::ready);
852
853 handler_->Post(common::BindOnce(
854 [](std::unique_ptr<LogCapture> log_capture) {
855 log_capture->Sync();
856 ASSERT_TRUE(log_capture->Rewind()->Find("address policy isn't set yet"));
857 ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
858 },
859 std::move(log_capture)));
860 }
861
862 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMED)863 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED) {
864 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
865
866 le_impl_->connectability_state_ = ConnectabilityState::DISARMED;
867 le_impl_->disarm_connectability();
868 ASSERT_FALSE(le_impl_->disarmed_while_arming_);
869
870 le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
871
872 ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
873 ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMED"));
874 }
875
876 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMED_extended)877 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMED_extended) {
878 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
879
880 le_impl_->connectability_state_ = ConnectabilityState::DISARMED;
881 le_impl_->disarm_connectability();
882 ASSERT_FALSE(le_impl_->disarmed_while_arming_);
883
884 le_impl_->on_extended_create_connection(
885 ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
886
887 ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
888 ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMED"));
889 }
890
891 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMING)892 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING) {
893 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
894
895 le_impl_->connectability_state_ = ConnectabilityState::ARMING;
896 le_impl_->disarm_connectability();
897 ASSERT_TRUE(le_impl_->disarmed_while_arming_);
898 le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
899
900 ASSERT_TRUE(log_capture->Rewind()->Find("Queueing cancel connect until"));
901 ASSERT_TRUE(log_capture->Rewind()->Find("Le connection state machine armed state"));
902 }
903
904 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMING_extended)905 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMING_extended) {
906 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
907
908 le_impl_->connectability_state_ = ConnectabilityState::ARMING;
909 le_impl_->disarm_connectability();
910 ASSERT_TRUE(le_impl_->disarmed_while_arming_);
911
912 le_impl_->on_extended_create_connection(
913 ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
914
915 ASSERT_TRUE(log_capture->Rewind()->Find("Queueing cancel connect until"));
916 ASSERT_TRUE(log_capture->Rewind()->Find("Le connection state machine armed state"));
917 }
918
919 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMED)920 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED) {
921 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
922
923 le_impl_->connectability_state_ = ConnectabilityState::ARMED;
924 le_impl_->disarm_connectability();
925 ASSERT_FALSE(le_impl_->disarmed_while_arming_);
926
927 le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
928
929 ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine"));
930 ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine with create connection"));
931 }
932
933 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_ARMED_extended)934 TEST_F(LeImplTest, DISABLED_disarm_connectability_ARMED_extended) {
935 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
936
937 le_impl_->connectability_state_ = ConnectabilityState::ARMED;
938 le_impl_->disarm_connectability();
939 ASSERT_FALSE(le_impl_->disarmed_while_arming_);
940
941 le_impl_->on_extended_create_connection(
942 ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
943
944 ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine"));
945 ASSERT_TRUE(log_capture->Rewind()->Find("Disarming LE connection state machine with create connection"));
946 }
947
948 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMING)949 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING) {
950 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
951
952 le_impl_->connectability_state_ = ConnectabilityState::DISARMING;
953 le_impl_->disarm_connectability();
954 ASSERT_FALSE(le_impl_->disarmed_while_arming_);
955
956 le_impl_->on_create_connection(ReturnCommandStatus(OpCode::LE_CREATE_CONNECTION, ErrorCode::SUCCESS));
957
958 ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
959 ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMING"));
960 }
961
962 // b/260917913
TEST_F(LeImplTest,DISABLED_disarm_connectability_DISARMING_extended)963 TEST_F(LeImplTest, DISABLED_disarm_connectability_DISARMING_extended) {
964 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
965
966 le_impl_->connectability_state_ = ConnectabilityState::DISARMING;
967 le_impl_->disarm_connectability();
968 ASSERT_FALSE(le_impl_->disarmed_while_arming_);
969
970 le_impl_->on_extended_create_connection(
971 ReturnCommandStatus(OpCode::LE_EXTENDED_CREATE_CONNECTION, ErrorCode::SUCCESS));
972
973 ASSERT_TRUE(log_capture->Rewind()->Find("Attempting to disarm le connection"));
974 ASSERT_TRUE(log_capture->Rewind()->Find("in unexpected state:ConnectabilityState::DISARMING"));
975 }
976
977 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyPublicAddress)978 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyPublicAddress) {
979 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
980
981 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
982
983 le_impl_->register_with_address_manager();
984 sync_handler(); // Let |eAddressManager::register_client| execute on handler
985 ASSERT_TRUE(le_impl_->address_manager_registered);
986 ASSERT_TRUE(le_impl_->pause_connection);
987
988 le_impl_->ready_to_unregister = true;
989
990 le_impl_->check_for_unregister();
991 sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
992 ASSERT_FALSE(le_impl_->address_manager_registered);
993 ASSERT_FALSE(le_impl_->pause_connection);
994
995 ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 1"));
996 ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
997 }
998
999 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyStaticAddress)1000 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyStaticAddress) {
1001 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
1002
1003 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS);
1004
1005 le_impl_->register_with_address_manager();
1006 sync_handler(); // Let |LeAddressManager::register_client| execute on handler
1007 ASSERT_TRUE(le_impl_->address_manager_registered);
1008 ASSERT_TRUE(le_impl_->pause_connection);
1009
1010 le_impl_->ready_to_unregister = true;
1011
1012 le_impl_->check_for_unregister();
1013 sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
1014 ASSERT_FALSE(le_impl_->address_manager_registered);
1015 ASSERT_FALSE(le_impl_->pause_connection);
1016
1017 ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 2"));
1018 ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
1019 }
1020
1021 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyNonResolvableAddress)1022 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyNonResolvableAddress) {
1023 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
1024
1025 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_NON_RESOLVABLE_ADDRESS);
1026
1027 le_impl_->register_with_address_manager();
1028 sync_handler(); // Let |LeAddressManager::register_client| execute on handler
1029 ASSERT_TRUE(le_impl_->address_manager_registered);
1030 ASSERT_TRUE(le_impl_->pause_connection);
1031
1032 le_impl_->ready_to_unregister = true;
1033
1034 le_impl_->check_for_unregister();
1035 sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
1036 ASSERT_FALSE(le_impl_->address_manager_registered);
1037 ASSERT_FALSE(le_impl_->pause_connection);
1038
1039 ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 3"));
1040 ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
1041 }
1042
1043 // b/260917913
TEST_F(LeImplTest,DISABLED_register_with_address_manager__AddressPolicyResolvableAddress)1044 TEST_F(LeImplTest, DISABLED_register_with_address_manager__AddressPolicyResolvableAddress) {
1045 std::unique_ptr<LogCapture> log_capture = std::make_unique<LogCapture>();
1046
1047 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS);
1048
1049 le_impl_->register_with_address_manager();
1050 sync_handler(); // Let |LeAddressManager::register_client| execute on handler
1051 ASSERT_TRUE(le_impl_->address_manager_registered);
1052 ASSERT_TRUE(le_impl_->pause_connection);
1053
1054 le_impl_->ready_to_unregister = true;
1055
1056 le_impl_->check_for_unregister();
1057 sync_handler(); // Let |LeAddressManager::unregister_client| execute on handler
1058 ASSERT_FALSE(le_impl_->address_manager_registered);
1059 ASSERT_FALSE(le_impl_->pause_connection);
1060
1061 ASSERT_TRUE(log_capture->Rewind()->Find("SetPrivacyPolicyForInitiatorAddress with policy 4"));
1062 ASSERT_TRUE(log_capture->Rewind()->Find("Client unregistered"));
1063 }
1064
1065 // b/260920739
TEST_F(LeImplTest,DISABLED_add_device_to_resolving_list)1066 TEST_F(LeImplTest, DISABLED_add_device_to_resolving_list) {
1067 // Some kind of privacy policy must be set for LeAddressManager to operate properly
1068 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
1069 // Let LeAddressManager::resume_registered_clients execute
1070 sync_handler();
1071
1072 ASSERT_EQ(0UL, hci_layer_->NumberOfQueuedCommands());
1073
1074 // le_impl should not be registered with address manager
1075 ASSERT_FALSE(le_impl_->address_manager_registered);
1076 ASSERT_FALSE(le_impl_->pause_connection);
1077
1078 ASSERT_EQ(0UL, le_impl_->le_address_manager_->NumberCachedCommands());
1079 // Acknowledge that the le_impl has quiesced all relevant controller state
1080 le_impl_->add_device_to_resolving_list(
1081 remote_public_address_with_type_, kPeerIdentityResolvingKey, kLocalIdentityResolvingKey);
1082 ASSERT_EQ(3UL, le_impl_->le_address_manager_->NumberCachedCommands());
1083
1084 sync_handler(); // Let |LeAddressManager::register_client| execute on handler
1085 ASSERT_TRUE(le_impl_->address_manager_registered);
1086 ASSERT_TRUE(le_impl_->pause_connection);
1087
1088 le_impl_->le_address_manager_->AckPause(le_impl_);
1089 sync_handler(); // Allow |LeAddressManager::ack_pause| to complete
1090
1091 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1092 {
1093 // Inform controller to disable address resolution
1094 auto command = CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->DequeueCommandBytes());
1095 ASSERT_TRUE(command.IsValid());
1096 ASSERT_EQ(Enable::DISABLED, command.GetAddressResolutionEnable());
1097 le_impl_->le_address_manager_->OnCommandComplete(
1098 ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1099 }
1100 sync_handler(); // |LeAddressManager::check_cached_commands|
1101
1102 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1103 {
1104 auto command = CreateLeSecurityCommandView<LeAddDeviceToResolvingListView>(hci_layer_->DequeueCommandBytes());
1105 ASSERT_TRUE(command.IsValid());
1106 ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, command.GetPeerIdentityAddressType());
1107 ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress());
1108 ASSERT_EQ(kPeerIdentityResolvingKey, command.GetPeerIrk());
1109 ASSERT_EQ(kLocalIdentityResolvingKey, command.GetLocalIrk());
1110 le_impl_->le_address_manager_->OnCommandComplete(
1111 ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS));
1112 }
1113 sync_handler(); // |LeAddressManager::check_cached_commands|
1114
1115 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1116 {
1117 auto command = CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->DequeueCommandBytes());
1118 ASSERT_TRUE(command.IsValid());
1119 ASSERT_EQ(Enable::ENABLED, command.GetAddressResolutionEnable());
1120 le_impl_->le_address_manager_->OnCommandComplete(
1121 ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1122 }
1123 sync_handler(); // |LeAddressManager::check_cached_commands|
1124
1125 ASSERT_TRUE(hci_layer_->IsPacketQueueEmpty());
1126 ASSERT_TRUE(le_impl_->address_manager_registered);
1127
1128 le_impl_->ready_to_unregister = true;
1129
1130 le_impl_->check_for_unregister();
1131 sync_handler();
1132 ASSERT_FALSE(le_impl_->address_manager_registered);
1133 ASSERT_FALSE(le_impl_->pause_connection);
1134 }
1135
TEST_F(LeImplTest,add_device_to_resolving_list__SupportsBlePrivacy)1136 TEST_F(LeImplTest, add_device_to_resolving_list__SupportsBlePrivacy) {
1137 controller_->supports_ble_privacy_ = true;
1138
1139 // Some kind of privacy policy must be set for LeAddressManager to operate properly
1140 set_privacy_policy_for_initiator_address(fixed_address_, LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS);
1141 // Let LeAddressManager::resume_registered_clients execute
1142 sync_handler();
1143
1144 ASSERT_EQ(0UL, hci_layer_->NumberOfQueuedCommands());
1145
1146 // le_impl should not be registered with address manager
1147 ASSERT_FALSE(le_impl_->address_manager_registered);
1148 ASSERT_FALSE(le_impl_->pause_connection);
1149
1150 ASSERT_EQ(0UL, le_impl_->le_address_manager_->NumberCachedCommands());
1151 // Acknowledge that the le_impl has quiesced all relevant controller state
1152 le_impl_->add_device_to_resolving_list(
1153 remote_public_address_with_type_, kPeerIdentityResolvingKey, kLocalIdentityResolvingKey);
1154 ASSERT_EQ(4UL, le_impl_->le_address_manager_->NumberCachedCommands());
1155
1156 sync_handler(); // Let |LeAddressManager::register_client| execute on handler
1157 ASSERT_TRUE(le_impl_->address_manager_registered);
1158 ASSERT_TRUE(le_impl_->pause_connection);
1159
1160 le_impl_->le_address_manager_->AckPause(le_impl_);
1161 sync_handler(); // Allow |LeAddressManager::ack_pause| to complete
1162
1163 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1164 {
1165 // Inform controller to disable address resolution
1166 auto command = CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->DequeueCommandBytes());
1167 ASSERT_TRUE(command.IsValid());
1168 ASSERT_EQ(Enable::DISABLED, command.GetAddressResolutionEnable());
1169 le_impl_->le_address_manager_->OnCommandComplete(
1170 ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1171 }
1172 sync_handler(); // |LeAddressManager::check_cached_commands|
1173
1174 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1175 {
1176 auto command = CreateLeSecurityCommandView<LeAddDeviceToResolvingListView>(hci_layer_->DequeueCommandBytes());
1177 ASSERT_TRUE(command.IsValid());
1178 ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, command.GetPeerIdentityAddressType());
1179 ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress());
1180 ASSERT_EQ(kPeerIdentityResolvingKey, command.GetPeerIrk());
1181 ASSERT_EQ(kLocalIdentityResolvingKey, command.GetLocalIrk());
1182 le_impl_->le_address_manager_->OnCommandComplete(
1183 ReturnCommandComplete(OpCode::LE_ADD_DEVICE_TO_RESOLVING_LIST, ErrorCode::SUCCESS));
1184 }
1185 sync_handler(); // |LeAddressManager::check_cached_commands|
1186
1187 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1188 {
1189 auto command = CreateLeSecurityCommandView<LeSetPrivacyModeView>(hci_layer_->DequeueCommandBytes());
1190 ASSERT_TRUE(command.IsValid());
1191 ASSERT_EQ(PrivacyMode::DEVICE, command.GetPrivacyMode());
1192 ASSERT_EQ(remote_public_address_with_type_.GetAddress(), command.GetPeerIdentityAddress());
1193 ASSERT_EQ(PeerAddressType::PUBLIC_DEVICE_OR_IDENTITY_ADDRESS, command.GetPeerIdentityAddressType());
1194 le_impl_->le_address_manager_->OnCommandComplete(
1195 ReturnCommandComplete(OpCode::LE_SET_PRIVACY_MODE, ErrorCode::SUCCESS));
1196 }
1197 sync_handler(); // |LeAddressManager::check_cached_commands|
1198
1199 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1200 {
1201 auto command = CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->DequeueCommandBytes());
1202 ASSERT_TRUE(command.IsValid());
1203 ASSERT_EQ(Enable::ENABLED, command.GetAddressResolutionEnable());
1204 le_impl_->le_address_manager_->OnCommandComplete(
1205 ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1206 }
1207 sync_handler(); // |LeAddressManager::check_cached_commands|
1208
1209 ASSERT_TRUE(hci_layer_->IsPacketQueueEmpty());
1210 ASSERT_TRUE(le_impl_->address_manager_registered);
1211
1212 le_impl_->ready_to_unregister = true;
1213
1214 le_impl_->check_for_unregister();
1215 sync_handler();
1216 ASSERT_FALSE(le_impl_->address_manager_registered);
1217 ASSERT_FALSE(le_impl_->pause_connection);
1218 }
1219
TEST_F(LeImplTest,connectability_state_machine_text)1220 TEST_F(LeImplTest, connectability_state_machine_text) {
1221 ASSERT_STREQ(
1222 "ConnectabilityState::DISARMED", connectability_state_machine_text(ConnectabilityState::DISARMED).c_str());
1223 ASSERT_STREQ("ConnectabilityState::ARMING", connectability_state_machine_text(ConnectabilityState::ARMING).c_str());
1224 ASSERT_STREQ("ConnectabilityState::ARMED", connectability_state_machine_text(ConnectabilityState::ARMED).c_str());
1225 ASSERT_STREQ(
1226 "ConnectabilityState::DISARMING", connectability_state_machine_text(ConnectabilityState::DISARMING).c_str());
1227 }
1228
TEST_F(LeImplTest,on_le_event__CONNECTION_COMPLETE_CENTRAL)1229 TEST_F(LeImplTest, on_le_event__CONNECTION_COMPLETE_CENTRAL) {
1230 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1231 set_random_device_address_policy();
1232 auto command = LeConnectionCompleteBuilder::Create(
1233 ErrorCode::SUCCESS,
1234 kHciHandle,
1235 Role::CENTRAL,
1236 AddressType::PUBLIC_DEVICE_ADDRESS,
1237 remote_address_,
1238 0x0024,
1239 0x0000,
1240 0x0011,
1241 ClockAccuracy::PPM_30);
1242 auto bytes = Serialize<LeConnectionCompleteBuilder>(std::move(command));
1243 auto view = CreateLeEventView<hci::LeConnectionCompleteView>(bytes);
1244 ASSERT_TRUE(view.IsValid());
1245 le_impl_->on_le_event(view);
1246 }
1247
TEST_F(LeImplTest,on_le_event__CONNECTION_COMPLETE_PERIPHERAL)1248 TEST_F(LeImplTest, on_le_event__CONNECTION_COMPLETE_PERIPHERAL) {
1249 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1250 set_random_device_address_policy();
1251 auto command = LeConnectionCompleteBuilder::Create(
1252 ErrorCode::SUCCESS,
1253 kHciHandle,
1254 Role::PERIPHERAL,
1255 AddressType::PUBLIC_DEVICE_ADDRESS,
1256 remote_address_,
1257 0x0024,
1258 0x0000,
1259 0x0011,
1260 ClockAccuracy::PPM_30);
1261 auto bytes = Serialize<LeConnectionCompleteBuilder>(std::move(command));
1262 auto view = CreateLeEventView<hci::LeConnectionCompleteView>(bytes);
1263 ASSERT_TRUE(view.IsValid());
1264 le_impl_->on_le_event(view);
1265 }
1266
TEST_F(LeImplTest,on_le_event__ENHANCED_CONNECTION_COMPLETE_CENTRAL)1267 TEST_F(LeImplTest, on_le_event__ENHANCED_CONNECTION_COMPLETE_CENTRAL) {
1268 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(_, _)).Times(1);
1269 set_random_device_address_policy();
1270 auto command = LeEnhancedConnectionCompleteBuilder::Create(
1271 ErrorCode::SUCCESS,
1272 kHciHandle,
1273 Role::CENTRAL,
1274 AddressType::PUBLIC_DEVICE_ADDRESS,
1275 remote_address_,
1276 local_rpa_,
1277 remote_rpa_,
1278 0x0024,
1279 0x0000,
1280 0x0011,
1281 ClockAccuracy::PPM_30);
1282 auto bytes = Serialize<LeEnhancedConnectionCompleteBuilder>(std::move(command));
1283 auto view = CreateLeEventView<hci::LeEnhancedConnectionCompleteView>(bytes);
1284 ASSERT_TRUE(view.IsValid());
1285 le_impl_->on_le_event(view);
1286 }
1287
TEST_F(LeImplTest,on_le_event__ENHANCED_CONNECTION_COMPLETE_PERIPHERAL)1288 TEST_F(LeImplTest, on_le_event__ENHANCED_CONNECTION_COMPLETE_PERIPHERAL) {
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::PERIPHERAL,
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(LeImplRegisteredWithAddressManagerTest,ignore_on_pause_on_resume_after_unregistered)1309 TEST_F(LeImplRegisteredWithAddressManagerTest, ignore_on_pause_on_resume_after_unregistered) {
1310 le_impl_->ready_to_unregister = true;
1311 le_impl_->check_for_unregister();
1312 // OnPause should be ignored
1313 le_impl_->OnPause();
1314 ASSERT_FALSE(le_impl_->pause_connection);
1315 // OnResume should be ignored
1316 le_impl_->pause_connection = true;
1317 le_impl_->OnResume();
1318 ASSERT_TRUE(le_impl_->pause_connection);
1319 }
1320
TEST_F(LeImplWithConnectionTest,on_le_event__PHY_UPDATE_COMPLETE)1321 TEST_F(LeImplWithConnectionTest, on_le_event__PHY_UPDATE_COMPLETE) {
1322 hci::ErrorCode hci_status{ErrorCode::STATUS_UNKNOWN};
1323 hci::PhyType tx_phy{0};
1324 hci::PhyType rx_phy{0};
1325
1326 // Send a phy update
1327 {
1328 EXPECT_CALL(connection_management_callbacks_, OnPhyUpdate(_, _, _))
1329 .WillOnce([&](hci::ErrorCode _hci_status, uint8_t _tx_phy, uint8_t _rx_phy) {
1330 hci_status = _hci_status;
1331 tx_phy = static_cast<PhyType>(_tx_phy);
1332 rx_phy = static_cast<PhyType>(_rx_phy);
1333 });
1334 auto command = LePhyUpdateCompleteBuilder::Create(ErrorCode::SUCCESS, kHciHandle, 0x01, 0x02);
1335 auto bytes = Serialize<LePhyUpdateCompleteBuilder>(std::move(command));
1336 auto view = CreateLeEventView<hci::LePhyUpdateCompleteView>(bytes);
1337 ASSERT_TRUE(view.IsValid());
1338 le_impl_->on_le_event(view);
1339 }
1340
1341 sync_handler();
1342 ASSERT_EQ(ErrorCode::SUCCESS, hci_status);
1343 ASSERT_EQ(PhyType::LE_1M, tx_phy);
1344 ASSERT_EQ(PhyType::LE_2M, rx_phy);
1345 }
1346
TEST_F(LeImplWithConnectionTest,on_le_event__DATA_LENGTH_CHANGE)1347 TEST_F(LeImplWithConnectionTest, on_le_event__DATA_LENGTH_CHANGE) {
1348 uint16_t tx_octets{0};
1349 uint16_t tx_time{0};
1350 uint16_t rx_octets{0};
1351 uint16_t rx_time{0};
1352
1353 // Send a data length event
1354 {
1355 EXPECT_CALL(connection_management_callbacks_, OnDataLengthChange(_, _, _, _))
1356 .WillOnce([&](uint16_t _tx_octets, uint16_t _tx_time, uint16_t _rx_octets, uint16_t _rx_time) {
1357 tx_octets = _tx_octets;
1358 tx_time = _tx_time;
1359 rx_octets = _rx_octets;
1360 rx_time = _rx_time;
1361 });
1362 auto command = LeDataLengthChangeBuilder::Create(kHciHandle, 0x1234, 0x5678, 0x9abc, 0xdef0);
1363 auto bytes = Serialize<LeDataLengthChangeBuilder>(std::move(command));
1364 auto view = CreateLeEventView<hci::LeDataLengthChangeView>(bytes);
1365 ASSERT_TRUE(view.IsValid());
1366 le_impl_->on_le_event(view);
1367 }
1368
1369 sync_handler();
1370 ASSERT_EQ(0x1234, tx_octets);
1371 ASSERT_EQ(0x5678, tx_time);
1372 ASSERT_EQ(0x9abc, rx_octets);
1373 ASSERT_EQ(0xdef0, rx_time);
1374 }
1375
TEST_F(LeImplWithConnectionTest,on_le_event__REMOTE_CONNECTION_PARAMETER_REQUEST)1376 TEST_F(LeImplWithConnectionTest, on_le_event__REMOTE_CONNECTION_PARAMETER_REQUEST) {
1377 // Send a remote connection parameter request
1378 auto command = hci::LeRemoteConnectionParameterRequestBuilder::Create(
1379 kHciHandle, kIntervalMin, kIntervalMax, kLatency, kTimeout);
1380 auto bytes = Serialize<LeRemoteConnectionParameterRequestBuilder>(std::move(command));
1381 {
1382 auto view = CreateLeEventView<hci::LeRemoteConnectionParameterRequestView>(bytes);
1383 ASSERT_TRUE(view.IsValid());
1384 le_impl_->on_le_event(view);
1385 }
1386
1387 sync_handler();
1388
1389 ASSERT_FALSE(hci_layer_->IsPacketQueueEmpty());
1390
1391 auto view = CreateLeConnectionManagementCommandView<LeRemoteConnectionParameterRequestReplyView>(
1392 hci_layer_->DequeueCommandBytes());
1393 ASSERT_TRUE(view.IsValid());
1394
1395 ASSERT_EQ(kIntervalMin, view.GetIntervalMin());
1396 ASSERT_EQ(kIntervalMax, view.GetIntervalMax());
1397 ASSERT_EQ(kLatency, view.GetLatency());
1398 ASSERT_EQ(kTimeout, view.GetTimeout());
1399 }
1400
1401 // b/260920739
TEST_F(LeImplRegisteredWithAddressManagerTest,DISABLED_clear_resolving_list)1402 TEST_F(LeImplRegisteredWithAddressManagerTest, DISABLED_clear_resolving_list) {
1403 le_impl_->clear_resolving_list();
1404 ASSERT_EQ(3UL, le_impl_->le_address_manager_->NumberCachedCommands());
1405
1406 sync_handler(); // Allow |LeAddressManager::pause_registered_clients| to complete
1407 sync_handler(); // Allow |LeAddressManager::handle_next_command| to complete
1408
1409 ASSERT_EQ(1UL, hci_layer_->NumberOfQueuedCommands());
1410 {
1411 auto view = CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->DequeueCommandBytes());
1412 ASSERT_TRUE(view.IsValid());
1413 ASSERT_EQ(Enable::DISABLED, view.GetAddressResolutionEnable());
1414 le_impl_->le_address_manager_->OnCommandComplete(
1415 ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1416 }
1417
1418 sync_handler(); // Allow |LeAddressManager::check_cached_commands| to complete
1419 ASSERT_EQ(1UL, hci_layer_->NumberOfQueuedCommands());
1420 {
1421 auto view = CreateLeSecurityCommandView<LeClearResolvingListView>(hci_layer_->DequeueCommandBytes());
1422 ASSERT_TRUE(view.IsValid());
1423 le_impl_->le_address_manager_->OnCommandComplete(
1424 ReturnCommandComplete(OpCode::LE_CLEAR_RESOLVING_LIST, ErrorCode::SUCCESS));
1425 }
1426
1427 sync_handler(); // Allow |LeAddressManager::handle_next_command| to complete
1428 ASSERT_EQ(1UL, hci_layer_->NumberOfQueuedCommands());
1429 {
1430 auto view = CreateLeSecurityCommandView<LeSetAddressResolutionEnableView>(hci_layer_->DequeueCommandBytes());
1431 ASSERT_TRUE(view.IsValid());
1432 ASSERT_EQ(Enable::ENABLED, view.GetAddressResolutionEnable());
1433 le_impl_->le_address_manager_->OnCommandComplete(
1434 ReturnCommandComplete(OpCode::LE_SET_ADDRESS_RESOLUTION_ENABLE, ErrorCode::SUCCESS));
1435 }
1436 ASSERT_TRUE(hci_layer_->IsPacketQueueEmpty());
1437 }
1438
TEST_F(LeImplWithConnectionTest,HACK_get_handle)1439 TEST_F(LeImplWithConnectionTest, HACK_get_handle) {
1440 sync_handler();
1441
1442 ASSERT_EQ(kHciHandle, le_impl_->HACK_get_handle(remote_address_));
1443 }
1444
TEST_F(LeImplTest,on_le_connection_canceled_on_pause)1445 TEST_F(LeImplTest, on_le_connection_canceled_on_pause) {
1446 set_random_device_address_policy();
1447 le_impl_->pause_connection = true;
1448 le_impl_->on_le_connection_canceled_on_pause();
1449 ASSERT_TRUE(le_impl_->arm_on_resume_);
1450 ASSERT_EQ(ConnectabilityState::DISARMED, le_impl_->connectability_state_);
1451 }
1452
TEST_F(LeImplTest,on_create_connection_timeout)1453 TEST_F(LeImplTest, on_create_connection_timeout) {
1454 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectFail(_, ErrorCode::CONNECTION_ACCEPT_TIMEOUT)).Times(1);
1455 le_impl_->create_connection_timeout_alarms_.emplace(
1456 std::piecewise_construct,
1457 std::forward_as_tuple(
1458 remote_public_address_with_type_.GetAddress(), remote_public_address_with_type_.GetAddressType()),
1459 std::forward_as_tuple(handler_));
1460 le_impl_->on_create_connection_timeout(remote_public_address_with_type_);
1461 sync_handler();
1462 ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty());
1463 }
1464
1465 // b/260917913
TEST_F(LeImplTest,DISABLED_on_common_le_connection_complete__NoPriorConnection)1466 TEST_F(LeImplTest, DISABLED_on_common_le_connection_complete__NoPriorConnection) {
1467 auto log_capture = std::make_unique<LogCapture>();
1468 le_impl_->on_common_le_connection_complete(remote_public_address_with_type_);
1469 ASSERT_TRUE(le_impl_->connecting_le_.empty());
1470 ASSERT_TRUE(log_capture->Rewind()->Find("No prior connection request for"));
1471 }
1472
TEST_F(LeImplTest,cancel_connect)1473 TEST_F(LeImplTest, cancel_connect) {
1474 le_impl_->create_connection_timeout_alarms_.emplace(
1475 std::piecewise_construct,
1476 std::forward_as_tuple(
1477 remote_public_address_with_type_.GetAddress(), remote_public_address_with_type_.GetAddressType()),
1478 std::forward_as_tuple(handler_));
1479 le_impl_->cancel_connect(remote_public_address_with_type_);
1480 sync_handler();
1481 ASSERT_TRUE(le_impl_->create_connection_timeout_alarms_.empty());
1482 }
1483
TEST_F(LeImplTest,set_le_suggested_default_data_parameters)1484 TEST_F(LeImplTest, set_le_suggested_default_data_parameters) {
1485 le_impl_->set_le_suggested_default_data_parameters(kLength, kTime);
1486 sync_handler();
1487 auto view =
1488 CreateLeConnectionManagementCommandView<LeWriteSuggestedDefaultDataLengthView>(hci_layer_->DequeueCommandBytes());
1489 ASSERT_TRUE(view.IsValid());
1490 ASSERT_EQ(kLength, view.GetTxOctets());
1491 ASSERT_EQ(kTime, view.GetTxTime());
1492 }
1493
1494 } // namespace acl_manager
1495 } // namespace hci
1496 } // namespace bluetooth
1497