1 /*
2 * Copyright 2019 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.h"
18
19 #include <bluetooth/log.h>
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22
23 #include <chrono>
24 #include <future>
25
26 #include "common/bind.h"
27 #include "hci/acl_manager/connection_callbacks_mock.h"
28 #include "hci/acl_manager/connection_management_callbacks_mock.h"
29 #include "hci/acl_manager/le_connection_callbacks_mock.h"
30 #include "hci/acl_manager/le_connection_management_callbacks_mock.h"
31 #include "hci/address.h"
32 #include "hci/class_of_device.h"
33 #include "hci/controller.h"
34 #include "hci/controller_mock.h"
35 #include "hci/hci_layer.h"
36 #include "hci/hci_layer_fake.h"
37 #include "os/fake_timer/fake_timerfd.h"
38 #include "os/thread.h"
39 #include "packet/raw_builder.h"
40
41 using bluetooth::common::BidiQueue;
42 using bluetooth::common::BidiQueueEnd;
43 using bluetooth::os::fake_timer::fake_timerfd_advance;
44 using bluetooth::packet::kLittleEndian;
45 using bluetooth::packet::PacketView;
46 using bluetooth::packet::RawBuilder;
47 using testing::_;
48 using testing::ElementsAreArray;
49
50 namespace {
51
52 constexpr auto kTimeout = std::chrono::seconds(2);
53 constexpr auto kShortTimeout = std::chrono::milliseconds(100);
54 constexpr uint16_t kHciHandle = 123;
55 constexpr uint16_t kScanIntervalFast = 0x0060;
56 constexpr uint16_t kScanWindowFast = 0x0030;
57 constexpr uint16_t kScanIntervalSlow = 0x0800;
58 constexpr uint16_t kScanWindowSlow = 0x0030;
59 const bluetooth::hci::AddressWithType empty_address_with_type = bluetooth::hci::AddressWithType();
60
61 } // namespace
62
63 namespace bluetooth {
64 namespace hci {
65 namespace acl_manager {
66
67 class TestController : public testing::MockController {
68 public:
RegisterCompletedAclPacketsCallback(common::ContextualCallback<void (uint16_t,uint16_t)> cb)69 void RegisterCompletedAclPacketsCallback(
70 common::ContextualCallback<void(uint16_t /* handle */, uint16_t /* packets */)> cb) override {
71 acl_cb_ = cb;
72 }
73
UnregisterCompletedAclPacketsCallback()74 void UnregisterCompletedAclPacketsCallback() override {
75 acl_cb_ = {};
76 }
77
GetAclPacketLength() const78 uint16_t GetAclPacketLength() const override {
79 return acl_buffer_length_;
80 }
81
GetNumAclPacketBuffers() const82 uint16_t GetNumAclPacketBuffers() const override {
83 return total_acl_buffers_;
84 }
85
IsSupported(bluetooth::hci::OpCode) const86 bool IsSupported(bluetooth::hci::OpCode /* op_code */) const override {
87 return false;
88 }
89
GetLeBufferSize() const90 LeBufferSize GetLeBufferSize() const override {
91 LeBufferSize le_buffer_size;
92 le_buffer_size.total_num_le_packets_ = 2;
93 le_buffer_size.le_data_packet_length_ = 32;
94 return le_buffer_size;
95 }
96
CompletePackets(uint16_t handle,uint16_t packets)97 void CompletePackets(uint16_t handle, uint16_t packets) {
98 acl_cb_(handle, packets);
99 }
100
101 uint16_t acl_buffer_length_ = 1024;
102 uint16_t total_acl_buffers_ = 2;
103 common::ContextualCallback<void(uint16_t /* handle */, uint16_t /* packets */)> acl_cb_;
104
105 protected:
Start()106 void Start() override {}
Stop()107 void Stop() override {}
ListDependencies(ModuleList *) const108 void ListDependencies(ModuleList* /* list */) const {}
109 };
110
111 class AclManagerNoCallbacksTest : public ::testing::Test {
112 protected:
SetUp()113 void SetUp() override {
114 test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry
115 test_controller_ = new TestController; // Ownership is transferred to registry
116
117 EXPECT_CALL(*test_controller_, GetMacAddress());
118 EXPECT_CALL(*test_controller_, GetLeFilterAcceptListSize());
119 EXPECT_CALL(*test_controller_, GetLeResolvingListSize());
120 EXPECT_CALL(*test_controller_, SupportsBlePrivacy());
121
122 fake_registry_.InjectTestModule(&HciLayer::Factory, test_hci_layer_);
123 fake_registry_.InjectTestModule(&Controller::Factory, test_controller_);
124 client_handler_ = fake_registry_.GetTestModuleHandler(&HciLayer::Factory);
125 ASSERT_NE(client_handler_, nullptr);
126 fake_registry_.Start<AclManager>(&thread_);
127 acl_manager_ = static_cast<AclManager*>(fake_registry_.GetModuleUnderTest(&AclManager::Factory));
128 Address::FromString("A1:A2:A3:A4:A5:A6", remote);
129
130 hci::Address address;
131 Address::FromString("D0:05:04:03:02:01", address);
132 hci::AddressWithType address_with_type(address, hci::AddressType::RANDOM_DEVICE_ADDRESS);
133 auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000);
134 auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000);
135 acl_manager_->SetPrivacyPolicyForInitiatorAddress(
136 LeAddressManager::AddressPolicy::USE_STATIC_ADDRESS,
137 address_with_type,
138 minimum_rotation_time,
139 maximum_rotation_time);
140
141 auto set_random_address_packet =
142 LeSetRandomAddressView::Create(LeAdvertisingCommandView::Create(
143 GetConnectionManagementCommand(OpCode::LE_SET_RANDOM_ADDRESS)));
144 ASSERT_TRUE(set_random_address_packet.IsValid());
145 my_initiating_address = AddressWithType(
146 set_random_address_packet.GetRandomAddress(), AddressType::RANDOM_DEVICE_ADDRESS);
147 test_hci_layer_->IncomingEvent(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
148
149 ON_CALL(mock_connection_callback_, OnConnectSuccess)
150 .WillByDefault([this](std::unique_ptr<ClassicAclConnection> connection) {
151 connections_.push_back(std::move(connection));
152 if (connection_promise_ != nullptr) {
153 connection_promise_->set_value();
154 connection_promise_.reset();
155 }
156 });
157 }
158
TearDown()159 void TearDown() override {
160 // Invalid mutex exception is raised if the connections
161 // are cleared after the AclConnectionInterface is deleted
162 // through fake_registry_.
163 connections_.clear();
164 le_connections_.clear();
165 fake_registry_.SynchronizeModuleHandler(&AclManager::Factory, std::chrono::milliseconds(20));
166 fake_registry_.StopAll();
167 }
168
sync_client_handler()169 void sync_client_handler() {
170 log::assert_that(
171 thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2)),
172 "assert failed: thread_.GetReactor()->WaitForIdle(std::chrono::seconds(2))");
173 }
174
175 TestModuleRegistry fake_registry_;
176 HciLayerFake* test_hci_layer_ = nullptr;
177 TestController* test_controller_ = nullptr;
178 os::Thread& thread_ = fake_registry_.GetTestThread();
179 AclManager* acl_manager_ = nullptr;
180 os::Handler* client_handler_ = nullptr;
181 Address remote;
182 AddressWithType my_initiating_address;
183 const bool use_accept_list_ = true; // gd currently only supports connect list
184
GetConnectionFuture()185 std::future<void> GetConnectionFuture() {
186 log::assert_that(connection_promise_ == nullptr, "Promises promises ... Only one at a time");
187 connection_promise_ = std::make_unique<std::promise<void>>();
188 return connection_promise_->get_future();
189 }
190
GetLeConnectionFuture()191 std::future<void> GetLeConnectionFuture() {
192 log::assert_that(le_connection_promise_ == nullptr, "Promises promises ... Only one at a time");
193 le_connection_promise_ = std::make_unique<std::promise<void>>();
194 return le_connection_promise_->get_future();
195 }
196
GetLastConnection()197 std::shared_ptr<ClassicAclConnection> GetLastConnection() {
198 return connections_.back();
199 }
200
GetLastLeConnection()201 std::shared_ptr<LeAclConnection> GetLastLeConnection() {
202 return le_connections_.back();
203 }
204
SendAclData(uint16_t handle,AclConnection::QueueUpEnd * queue_end)205 void SendAclData(uint16_t handle, AclConnection::QueueUpEnd* queue_end) {
206 std::promise<void> promise;
207 auto future = promise.get_future();
208 queue_end->RegisterEnqueue(client_handler_,
209 common::Bind(
210 [](decltype(queue_end) queue_end, uint16_t handle, std::promise<void> promise) {
211 queue_end->UnregisterEnqueue();
212 promise.set_value();
213 return NextPayload(handle);
214 },
215 queue_end, handle, common::Passed(std::move(promise))));
216 auto status = future.wait_for(kTimeout);
217 ASSERT_EQ(status, std::future_status::ready);
218 }
219
GetConnectionManagementCommand(OpCode op_code)220 ConnectionManagementCommandView GetConnectionManagementCommand(OpCode op_code) {
221 auto base_command = test_hci_layer_->GetCommand();
222 ConnectionManagementCommandView command =
223 ConnectionManagementCommandView::Create(AclCommandView::Create(base_command));
224 EXPECT_TRUE(command.IsValid());
225 EXPECT_EQ(command.GetOpCode(), op_code);
226 return command;
227 }
228
229 std::list<std::shared_ptr<ClassicAclConnection>> connections_;
230 std::unique_ptr<std::promise<void>> connection_promise_;
231 MockConnectionCallback mock_connection_callback_;
232
233 std::list<std::shared_ptr<LeAclConnection>> le_connections_;
234 std::unique_ptr<std::promise<void>> le_connection_promise_;
235 MockLeConnectionCallbacks mock_le_connection_callbacks_;
236 };
237
238 class AclManagerTest : public AclManagerNoCallbacksTest {
239 protected:
SetUp()240 void SetUp() override {
241 AclManagerNoCallbacksTest::SetUp();
242 acl_manager_->RegisterCallbacks(&mock_connection_callback_, client_handler_);
243 acl_manager_->RegisterLeCallbacks(&mock_le_connection_callbacks_, client_handler_);
244 }
245 };
246
247 class AclManagerWithConnectionTest : public AclManagerTest {
248 protected:
SetUp()249 void SetUp() override {
250 AclManagerTest::SetUp();
251
252 handle_ = 0x123;
253 acl_manager_->CreateConnection(remote);
254
255 // Wait for the connection request
256 auto last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
257 while (!last_command.IsValid()) {
258 last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
259 }
260
261 EXPECT_CALL(mock_connection_management_callbacks_, OnRoleChange(hci::ErrorCode::SUCCESS, Role::CENTRAL));
262
263 auto first_connection = GetConnectionFuture();
264 test_hci_layer_->IncomingEvent(
265 ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED));
266
267 auto first_connection_status = first_connection.wait_for(kTimeout);
268 ASSERT_EQ(first_connection_status, std::future_status::ready);
269
270 connection_ = GetLastConnection();
271 connection_->RegisterCallbacks(&mock_connection_management_callbacks_, client_handler_);
272 }
273
TearDown()274 void TearDown() override {
275 // Invalid mutex exception is raised if the connection
276 // is cleared after the AclConnectionInterface is deleted
277 // through fake_registry_.
278 connections_.clear();
279 le_connections_.clear();
280 connection_.reset();
281 fake_registry_.SynchronizeModuleHandler(&HciLayer::Factory, std::chrono::milliseconds(20));
282 fake_registry_.SynchronizeModuleHandler(&AclManager::Factory, std::chrono::milliseconds(20));
283 fake_registry_.StopAll();
284 }
285
286 uint16_t handle_;
287 std::shared_ptr<ClassicAclConnection> connection_;
288
289 MockConnectionManagementCallbacks mock_connection_management_callbacks_;
290 };
291
TEST_F(AclManagerTest,startup_teardown)292 TEST_F(AclManagerTest, startup_teardown) {}
293
TEST_F(AclManagerTest,invoke_registered_callback_connection_complete_success)294 TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_success) {
295 acl_manager_->CreateConnection(remote);
296
297 // Wait for the connection request
298 auto last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
299 while (!last_command.IsValid()) {
300 last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
301 }
302
303 auto first_connection = GetConnectionFuture();
304
305 test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create(
306 ErrorCode::SUCCESS, kHciHandle, remote, LinkType::ACL, Enable::DISABLED));
307
308 auto first_connection_status = first_connection.wait_for(kTimeout);
309 ASSERT_EQ(first_connection_status, std::future_status::ready);
310
311 auto connection = GetLastConnection();
312 ASSERT_EQ(connection->GetAddress(), remote);
313 }
314
TEST_F(AclManagerTest,invoke_registered_callback_connection_complete_fail)315 TEST_F(AclManagerTest, invoke_registered_callback_connection_complete_fail) {
316 acl_manager_->CreateConnection(remote);
317
318 // Wait for the connection request
319 auto last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
320 while (!last_command.IsValid()) {
321 last_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
322 }
323
324 struct callback_t {
325 hci::Address bd_addr;
326 hci::ErrorCode reason;
327 bool is_locally_initiated;
328 };
329
330 auto promise = std::promise<callback_t>();
331 auto future = promise.get_future();
332 ON_CALL(mock_connection_callback_, OnConnectFail)
333 .WillByDefault(
334 [&promise](hci::Address bd_addr, hci::ErrorCode reason, bool is_locally_initiated) {
335 promise.set_value({
336 .bd_addr = bd_addr,
337 .reason = reason,
338 .is_locally_initiated = is_locally_initiated,
339 });
340 });
341
342 EXPECT_CALL(mock_connection_callback_, OnConnectFail(remote, ErrorCode::PAGE_TIMEOUT, true));
343
344 // Remote response event to the connection request
345 test_hci_layer_->IncomingEvent(ConnectionCompleteBuilder::Create(
346 ErrorCode::PAGE_TIMEOUT, kHciHandle, remote, LinkType::ACL, Enable::DISABLED));
347
348 ASSERT_EQ(std::future_status::ready, future.wait_for(kTimeout));
349 auto callback = future.get();
350
351 ASSERT_EQ(remote, callback.bd_addr);
352 ASSERT_EQ(ErrorCode::PAGE_TIMEOUT, callback.reason);
353 ASSERT_EQ(true, callback.is_locally_initiated);
354 }
355
356 class AclManagerWithLeConnectionTest : public AclManagerTest {
357 protected:
SetUp()358 void SetUp() override {
359 AclManagerTest::SetUp();
360
361 remote_with_type_ = AddressWithType(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
362 acl_manager_->CreateLeConnection(remote_with_type_, true);
363 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
364 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
365 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
366 auto le_connection_management_command_view =
367 LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
368 auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
369 ASSERT_TRUE(command_view.IsValid());
370 if (use_accept_list_) {
371 ASSERT_EQ(command_view.GetPeerAddress(), empty_address_with_type.GetAddress());
372 ASSERT_EQ(command_view.GetPeerAddressType(), empty_address_with_type.GetAddressType());
373 } else {
374 ASSERT_EQ(command_view.GetPeerAddress(), remote);
375 ASSERT_EQ(command_view.GetPeerAddressType(), AddressType::PUBLIC_DEVICE_ADDRESS);
376 }
377
378 test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
379
380 auto first_connection = GetLeConnectionFuture();
381 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(remote_with_type_, _))
382 .WillRepeatedly([this](
383 hci::AddressWithType /* address_with_type */,
384 std::unique_ptr<LeAclConnection> connection) {
385 le_connections_.push_back(std::move(connection));
386 if (le_connection_promise_ != nullptr) {
387 le_connection_promise_->set_value();
388 le_connection_promise_.reset();
389 }
390 });
391
392 if (send_early_acl_) {
393 log::info("Sending a packet with handle 0x{:02x} ({})", handle_, handle_);
394 test_hci_layer_->IncomingAclData(handle_);
395 }
396
397 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
398 ErrorCode::SUCCESS,
399 handle_,
400 Role::CENTRAL,
401 AddressType::PUBLIC_DEVICE_ADDRESS,
402 remote,
403 0x0100,
404 0x0010,
405 0x0C80,
406 ClockAccuracy::PPM_30));
407
408 GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
409 test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
410
411 auto first_connection_status = first_connection.wait_for(kTimeout);
412 ASSERT_EQ(first_connection_status, std::future_status::ready);
413
414 connection_ = GetLastLeConnection();
415 }
416
TearDown()417 void TearDown() override {
418 // Invalid mutex exception is raised if the connection
419 // is cleared after the AclConnectionInterface is deleted
420 // through fake_registry_.
421 connections_.clear();
422 le_connections_.clear();
423 connection_.reset();
424 fake_registry_.SynchronizeModuleHandler(&HciLayer::Factory, std::chrono::milliseconds(20));
425 fake_registry_.SynchronizeModuleHandler(&AclManager::Factory, std::chrono::milliseconds(20));
426 fake_registry_.StopAll();
427 }
428
429 uint16_t handle_ = 0x123;
430 bool send_early_acl_ = false;
431 std::shared_ptr<LeAclConnection> connection_;
432 AddressWithType remote_with_type_;
433 MockLeConnectionManagementCallbacks mock_le_connection_management_callbacks_;
434 };
435
436 class AclManagerWithLateLeConnectionTest : public AclManagerWithLeConnectionTest {
437 protected:
SetUp()438 void SetUp() override {
439 send_early_acl_ = true;
440 AclManagerWithLeConnectionTest::SetUp();
441 }
442 };
443
444 // TODO: implement version of this test where controller supports Extended Advertising Feature in
445 // GetLeLocalSupportedFeatures, and LE Extended Create Connection is used
TEST_F(AclManagerWithLeConnectionTest,invoke_registered_callback_le_connection_complete_success)446 TEST_F(AclManagerWithLeConnectionTest, invoke_registered_callback_le_connection_complete_success) {
447 ASSERT_EQ(connection_->GetLocalAddress(), my_initiating_address);
448 ASSERT_EQ(connection_->GetRemoteAddress(), remote_with_type_);
449 }
450
TEST_F(AclManagerTest,invoke_registered_callback_le_connection_complete_fail)451 TEST_F(AclManagerTest, invoke_registered_callback_le_connection_complete_fail) {
452 AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
453 acl_manager_->CreateLeConnection(remote_with_type, true);
454 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
455 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
456 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
457 auto le_connection_management_command_view =
458 LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
459 auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
460 ASSERT_TRUE(command_view.IsValid());
461 if (use_accept_list_) {
462 ASSERT_EQ(command_view.GetPeerAddress(), hci::Address::kEmpty);
463 } else {
464 ASSERT_EQ(command_view.GetPeerAddress(), remote);
465 }
466 EXPECT_EQ(command_view.GetPeerAddressType(), AddressType::PUBLIC_DEVICE_ADDRESS);
467
468 test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
469
470 EXPECT_CALL(
471 mock_le_connection_callbacks_,
472 OnLeConnectFail(remote_with_type, ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES));
473
474 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
475 ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES,
476 0x123,
477 Role::CENTRAL,
478 AddressType::PUBLIC_DEVICE_ADDRESS,
479 remote,
480 0x0100,
481 0x0010,
482 0x0011,
483 ClockAccuracy::PPM_30));
484
485 packet = GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
486 le_connection_management_command_view = LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
487 auto remove_command_view = LeRemoveDeviceFromFilterAcceptListView::Create(le_connection_management_command_view);
488 ASSERT_TRUE(remove_command_view.IsValid());
489 test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
490 }
491
TEST_F(AclManagerTest,cancel_le_connection)492 TEST_F(AclManagerTest, cancel_le_connection) {
493 AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
494 acl_manager_->CreateLeConnection(remote_with_type, true);
495 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
496 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
497 GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
498 test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
499
500 acl_manager_->CancelLeConnect(remote_with_type);
501 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION_CANCEL);
502 auto le_connection_management_command_view =
503 LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
504 auto command_view = LeCreateConnectionCancelView::Create(le_connection_management_command_view);
505 ASSERT_TRUE(command_view.IsValid());
506
507 test_hci_layer_->IncomingEvent(LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
508 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
509 ErrorCode::UNKNOWN_CONNECTION,
510 0x123,
511 Role::CENTRAL,
512 AddressType::PUBLIC_DEVICE_ADDRESS,
513 remote,
514 0x0100,
515 0x0010,
516 0x0011,
517 ClockAccuracy::PPM_30));
518
519 packet = GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
520 le_connection_management_command_view = LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
521 auto remove_command_view = LeRemoveDeviceFromFilterAcceptListView::Create(le_connection_management_command_view);
522 ASSERT_TRUE(remove_command_view.IsValid());
523
524 test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
525 }
526
TEST_F(AclManagerTest,create_connection_with_fast_mode)527 TEST_F(AclManagerTest, create_connection_with_fast_mode) {
528 AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
529 acl_manager_->CreateLeConnection(remote_with_type, true);
530 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
531 test_hci_layer_->IncomingEvent(
532 LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
533
534 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
535 auto command_view =
536 LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)));
537 ASSERT_TRUE(command_view.IsValid());
538 ASSERT_EQ(command_view.GetLeScanInterval(), kScanIntervalFast);
539 ASSERT_EQ(command_view.GetLeScanWindow(), kScanWindowFast);
540 test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
541
542 auto first_connection = GetLeConnectionFuture();
543 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(remote_with_type, _))
544 .WillRepeatedly([this](
545 hci::AddressWithType /* address_with_type */,
546 std::unique_ptr<LeAclConnection> connection) {
547 le_connections_.push_back(std::move(connection));
548 if (le_connection_promise_ != nullptr) {
549 le_connection_promise_->set_value();
550 le_connection_promise_.reset();
551 }
552 });
553
554 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
555 ErrorCode::SUCCESS,
556 0x00,
557 Role::CENTRAL,
558 AddressType::PUBLIC_DEVICE_ADDRESS,
559 remote,
560 0x0100,
561 0x0010,
562 0x0C80,
563 ClockAccuracy::PPM_30));
564
565 GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
566 test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
567 auto first_connection_status = first_connection.wait_for(kTimeout);
568 ASSERT_EQ(first_connection_status, std::future_status::ready);
569 }
570
TEST_F(AclManagerTest,create_connection_with_slow_mode)571 TEST_F(AclManagerTest, create_connection_with_slow_mode) {
572 AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
573 acl_manager_->CreateLeConnection(remote_with_type, false);
574 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
575 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
576 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
577 auto command_view =
578 LeCreateConnectionView::Create(LeConnectionManagementCommandView::Create(AclCommandView::Create(packet)));
579 ASSERT_TRUE(command_view.IsValid());
580 ASSERT_EQ(command_view.GetLeScanInterval(), kScanIntervalSlow);
581 ASSERT_EQ(command_view.GetLeScanWindow(), kScanWindowSlow);
582 test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
583 auto first_connection = GetLeConnectionFuture();
584 EXPECT_CALL(mock_le_connection_callbacks_, OnLeConnectSuccess(remote_with_type, _))
585 .WillRepeatedly([this](
586 hci::AddressWithType /* address_with_type */,
587 std::unique_ptr<LeAclConnection> connection) {
588 le_connections_.push_back(std::move(connection));
589 if (le_connection_promise_ != nullptr) {
590 le_connection_promise_->set_value();
591 le_connection_promise_.reset();
592 }
593 });
594
595 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
596 ErrorCode::SUCCESS,
597 0x00,
598 Role::CENTRAL,
599 AddressType::PUBLIC_DEVICE_ADDRESS,
600 remote,
601 0x0100,
602 0x0010,
603 0x0C80,
604 ClockAccuracy::PPM_30));
605 GetConnectionManagementCommand(OpCode::LE_REMOVE_DEVICE_FROM_FILTER_ACCEPT_LIST);
606 test_hci_layer_->IncomingEvent(LeRemoveDeviceFromFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
607 auto first_connection_status = first_connection.wait_for(kTimeout);
608 ASSERT_EQ(first_connection_status, std::future_status::ready);
609 }
610
TEST_F(AclManagerWithLeConnectionTest,acl_send_data_one_le_connection)611 TEST_F(AclManagerWithLeConnectionTest, acl_send_data_one_le_connection) {
612 ASSERT_EQ(connection_->GetRemoteAddress(), remote_with_type_);
613 ASSERT_EQ(connection_->GetHandle(), handle_);
614
615 // Send a packet from HCI
616 test_hci_layer_->IncomingAclData(handle_);
617 auto queue_end = connection_->GetAclQueueEnd();
618
619 std::unique_ptr<PacketView<kLittleEndian>> received;
620 do {
621 received = queue_end->TryDequeue();
622 } while (received == nullptr);
623
624 PacketView<kLittleEndian> received_packet = *received;
625
626 // Send a packet from the connection
627 SendAclData(handle_, connection_->GetAclQueueEnd());
628
629 auto sent_packet = test_hci_layer_->OutgoingAclData();
630
631 // Send another packet from the connection
632 SendAclData(handle_, connection_->GetAclQueueEnd());
633
634 sent_packet = test_hci_layer_->OutgoingAclData();
635 }
636
TEST_F(AclManagerWithLeConnectionTest,invoke_registered_callback_le_connection_update_success)637 TEST_F(AclManagerWithLeConnectionTest, invoke_registered_callback_le_connection_update_success) {
638 ASSERT_EQ(connection_->GetLocalAddress(), my_initiating_address);
639 ASSERT_EQ(connection_->GetRemoteAddress(), remote_with_type_);
640 ASSERT_EQ(connection_->GetHandle(), handle_);
641 connection_->RegisterCallbacks(&mock_le_connection_management_callbacks_, client_handler_);
642
643 std::promise<ErrorCode> promise;
644 ErrorCode hci_status = hci::ErrorCode::SUCCESS;
645 uint16_t connection_interval_min = 0x0012;
646 uint16_t connection_interval_max = 0x0080;
647 uint16_t connection_interval = (connection_interval_max + connection_interval_min) / 2;
648 uint16_t connection_latency = 0x0001;
649 uint16_t supervision_timeout = 0x0A00;
650 connection_->LeConnectionUpdate(
651 connection_interval_min,
652 connection_interval_max,
653 connection_latency,
654 supervision_timeout,
655 0x10,
656 0x20);
657 auto update_packet = GetConnectionManagementCommand(OpCode::LE_CONNECTION_UPDATE);
658 auto update_view =
659 LeConnectionUpdateView::Create(LeConnectionManagementCommandView::Create(AclCommandView::Create(update_packet)));
660 ASSERT_TRUE(update_view.IsValid());
661 EXPECT_EQ(update_view.GetConnectionHandle(), handle_);
662 test_hci_layer_->IncomingEvent(LeConnectionUpdateStatusBuilder::Create(ErrorCode::SUCCESS, 0x1));
663 EXPECT_CALL(
664 mock_le_connection_management_callbacks_,
665 OnConnectionUpdate(hci_status, connection_interval, connection_latency, supervision_timeout));
666 test_hci_layer_->IncomingLeMetaEvent(LeConnectionUpdateCompleteBuilder::Create(
667 ErrorCode::SUCCESS, handle_, connection_interval, connection_latency, supervision_timeout));
668 sync_client_handler();
669 }
670
TEST_F(AclManagerWithLeConnectionTest,invoke_registered_callback_le_disconnect)671 TEST_F(AclManagerWithLeConnectionTest, invoke_registered_callback_le_disconnect) {
672 ASSERT_EQ(connection_->GetRemoteAddress(), remote_with_type_);
673 ASSERT_EQ(connection_->GetHandle(), handle_);
674 connection_->RegisterCallbacks(&mock_le_connection_management_callbacks_, client_handler_);
675
676 auto reason = ErrorCode::REMOTE_USER_TERMINATED_CONNECTION;
677 EXPECT_CALL(mock_le_connection_management_callbacks_, OnDisconnection(reason));
678 test_hci_layer_->Disconnect(handle_, reason);
679 sync_client_handler();
680 }
681
TEST_F(AclManagerWithLeConnectionTest,invoke_registered_callback_le_disconnect_data_race)682 TEST_F(AclManagerWithLeConnectionTest, invoke_registered_callback_le_disconnect_data_race) {
683 ASSERT_EQ(connection_->GetRemoteAddress(), remote_with_type_);
684 ASSERT_EQ(connection_->GetHandle(), handle_);
685 connection_->RegisterCallbacks(&mock_le_connection_management_callbacks_, client_handler_);
686
687 test_hci_layer_->IncomingAclData(handle_);
688 auto reason = ErrorCode::REMOTE_USER_TERMINATED_CONNECTION;
689 EXPECT_CALL(mock_le_connection_management_callbacks_, OnDisconnection(reason));
690 test_hci_layer_->Disconnect(handle_, reason);
691 sync_client_handler();
692 }
693
TEST_F(AclManagerWithLeConnectionTest,invoke_registered_callback_le_queue_disconnect)694 TEST_F(AclManagerWithLeConnectionTest, invoke_registered_callback_le_queue_disconnect) {
695 auto reason = ErrorCode::REMOTE_USER_TERMINATED_CONNECTION;
696 test_hci_layer_->Disconnect(handle_, reason);
697 fake_registry_.SynchronizeModuleHandler(&HciLayer::Factory, std::chrono::milliseconds(20));
698 fake_registry_.SynchronizeModuleHandler(&AclManager::Factory, std::chrono::milliseconds(20));
699
700 EXPECT_CALL(mock_le_connection_management_callbacks_, OnDisconnection(reason));
701 connection_->RegisterCallbacks(&mock_le_connection_management_callbacks_, client_handler_);
702 sync_client_handler();
703 }
704
TEST_F(AclManagerWithLateLeConnectionTest,and_receive_nothing)705 TEST_F(AclManagerWithLateLeConnectionTest, and_receive_nothing) {}
706
TEST_F(AclManagerWithLateLeConnectionTest,receive_acl)707 TEST_F(AclManagerWithLateLeConnectionTest, receive_acl) {
708 client_handler_->Post(common::BindOnce(fake_timerfd_advance, 1200));
709 auto queue_end = connection_->GetAclQueueEnd();
710 std::unique_ptr<PacketView<kLittleEndian>> received;
711 do {
712 received = queue_end->TryDequeue();
713 } while (received == nullptr);
714
715 {
716 ASSERT_EQ(received->size(), 10u);
717 auto itr = received->begin();
718 ASSERT_EQ(itr.extract<uint16_t>(), 6u); // L2CAP PDU size
719 ASSERT_EQ(itr.extract<uint16_t>(), 2u); // L2CAP CID
720 ASSERT_EQ(itr.extract<uint16_t>(), handle_);
721 ASSERT_GE(itr.extract<uint32_t>(), 0u); // packet number
722 }
723 }
724
TEST_F(AclManagerWithLateLeConnectionTest,receive_acl_in_order)725 TEST_F(AclManagerWithLateLeConnectionTest, receive_acl_in_order) {
726 // Send packet #2 from HCI (the first was sent in the test)
727 test_hci_layer_->IncomingAclData(handle_);
728 auto queue_end = connection_->GetAclQueueEnd();
729
730 std::unique_ptr<PacketView<kLittleEndian>> received;
731 do {
732 received = queue_end->TryDequeue();
733 } while (received == nullptr);
734
735 uint32_t first_packet_number = 0;
736 {
737 ASSERT_EQ(received->size(), 10u);
738 auto itr = received->begin();
739 ASSERT_EQ(itr.extract<uint16_t>(), 6u); // L2CAP PDU size
740 ASSERT_EQ(itr.extract<uint16_t>(), 2u); // L2CAP CID
741 ASSERT_EQ(itr.extract<uint16_t>(), handle_);
742
743 first_packet_number = itr.extract<uint32_t>();
744 }
745
746 do {
747 received = queue_end->TryDequeue();
748 } while (received == nullptr);
749 {
750 ASSERT_EQ(received->size(), 10u);
751 auto itr = received->begin();
752 ASSERT_EQ(itr.extract<uint16_t>(), 6u); // L2CAP PDU size
753 ASSERT_EQ(itr.extract<uint16_t>(), 2u); // L2CAP CID
754 ASSERT_EQ(itr.extract<uint16_t>(), handle_);
755 ASSERT_GT(itr.extract<uint32_t>(), first_packet_number);
756 }
757 }
758
TEST_F(AclManagerWithConnectionTest,invoke_registered_callback_disconnection_complete)759 TEST_F(AclManagerWithConnectionTest, invoke_registered_callback_disconnection_complete) {
760 auto reason = ErrorCode::REMOTE_USER_TERMINATED_CONNECTION;
761 EXPECT_CALL(mock_connection_management_callbacks_, OnDisconnection(reason));
762 test_hci_layer_->Disconnect(handle_, reason);
763 sync_client_handler();
764 }
765
TEST_F(AclManagerWithConnectionTest,acl_send_data_one_connection)766 TEST_F(AclManagerWithConnectionTest, acl_send_data_one_connection) {
767 // Send a packet from HCI
768 test_hci_layer_->IncomingAclData(handle_);
769 auto queue_end = connection_->GetAclQueueEnd();
770
771 std::unique_ptr<PacketView<kLittleEndian>> received;
772 do {
773 received = queue_end->TryDequeue();
774 } while (received == nullptr);
775
776 PacketView<kLittleEndian> received_packet = *received;
777
778 // Send a packet from the connection
779 SendAclData(handle_, connection_->GetAclQueueEnd());
780
781 auto sent_packet = test_hci_layer_->OutgoingAclData();
782
783 // Send another packet from the connection
784 SendAclData(handle_, connection_->GetAclQueueEnd());
785
786 sent_packet = test_hci_layer_->OutgoingAclData();
787 auto reason = ErrorCode::AUTHENTICATION_FAILURE;
788 EXPECT_CALL(mock_connection_management_callbacks_, OnDisconnection(reason));
789 connection_->Disconnect(DisconnectReason::AUTHENTICATION_FAILURE);
790 auto packet = GetConnectionManagementCommand(OpCode::DISCONNECT);
791 auto command_view = DisconnectView::Create(packet);
792 ASSERT_TRUE(command_view.IsValid());
793 ASSERT_EQ(command_view.GetConnectionHandle(), handle_);
794 test_hci_layer_->Disconnect(handle_, reason);
795 sync_client_handler();
796 }
797
TEST_F(AclManagerWithConnectionTest,acl_send_data_credits)798 TEST_F(AclManagerWithConnectionTest, acl_send_data_credits) {
799 // Use all the credits
800 for (uint16_t credits = 0; credits < test_controller_->total_acl_buffers_; credits++) {
801 // Send a packet from the connection
802 SendAclData(handle_, connection_->GetAclQueueEnd());
803
804 auto sent_packet = test_hci_layer_->OutgoingAclData();
805 }
806
807 // Send another packet from the connection
808 SendAclData(handle_, connection_->GetAclQueueEnd());
809
810 test_hci_layer_->AssertNoOutgoingAclData();
811
812 test_controller_->CompletePackets(handle_, 1);
813
814 auto after_credits_sent_packet = test_hci_layer_->OutgoingAclData();
815 sync_client_handler();
816 }
817
TEST_F(AclManagerWithConnectionTest,send_switch_role)818 TEST_F(AclManagerWithConnectionTest, send_switch_role) {
819 acl_manager_->SwitchRole(connection_->GetAddress(), Role::PERIPHERAL);
820 auto packet = GetConnectionManagementCommand(OpCode::SWITCH_ROLE);
821 auto command_view = SwitchRoleView::Create(packet);
822 ASSERT_TRUE(command_view.IsValid());
823 ASSERT_EQ(command_view.GetBdAddr(), connection_->GetAddress());
824 ASSERT_EQ(command_view.GetRole(), Role::PERIPHERAL);
825
826 EXPECT_CALL(mock_connection_management_callbacks_, OnRoleChange(hci::ErrorCode::SUCCESS, Role::PERIPHERAL));
827 test_hci_layer_->IncomingEvent(
828 RoleChangeBuilder::Create(ErrorCode::SUCCESS, connection_->GetAddress(), Role::PERIPHERAL));
829 sync_client_handler();
830 }
831
TEST_F(AclManagerWithConnectionTest,send_write_default_link_policy_settings)832 TEST_F(AclManagerWithConnectionTest, send_write_default_link_policy_settings) {
833 uint16_t link_policy_settings = 0x05;
834 acl_manager_->WriteDefaultLinkPolicySettings(link_policy_settings);
835 auto packet = GetConnectionManagementCommand(OpCode::WRITE_DEFAULT_LINK_POLICY_SETTINGS);
836 auto command_view = WriteDefaultLinkPolicySettingsView::Create(packet);
837 ASSERT_TRUE(command_view.IsValid());
838 ASSERT_EQ(command_view.GetDefaultLinkPolicySettings(), 0x05);
839
840 uint8_t num_packets = 1;
841 test_hci_layer_->IncomingEvent(
842 WriteDefaultLinkPolicySettingsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS));
843 sync_client_handler();
844
845 ASSERT_EQ(link_policy_settings, acl_manager_->ReadDefaultLinkPolicySettings());
846 }
847
TEST_F(AclManagerWithConnectionTest,send_authentication_requested)848 TEST_F(AclManagerWithConnectionTest, send_authentication_requested) {
849 connection_->AuthenticationRequested();
850 auto packet = GetConnectionManagementCommand(OpCode::AUTHENTICATION_REQUESTED);
851 auto command_view = AuthenticationRequestedView::Create(packet);
852 ASSERT_TRUE(command_view.IsValid());
853
854 EXPECT_CALL(mock_connection_management_callbacks_, OnAuthenticationComplete);
855 test_hci_layer_->IncomingEvent(
856 AuthenticationCompleteBuilder::Create(ErrorCode::SUCCESS, handle_));
857 sync_client_handler();
858 }
859
TEST_F(AclManagerWithConnectionTest,send_read_clock_offset)860 TEST_F(AclManagerWithConnectionTest, send_read_clock_offset) {
861 connection_->ReadClockOffset();
862 auto packet = GetConnectionManagementCommand(OpCode::READ_CLOCK_OFFSET);
863 auto command_view = ReadClockOffsetView::Create(packet);
864 ASSERT_TRUE(command_view.IsValid());
865
866 EXPECT_CALL(mock_connection_management_callbacks_, OnReadClockOffsetComplete(0x0123));
867 test_hci_layer_->IncomingEvent(
868 ReadClockOffsetCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, 0x0123));
869 sync_client_handler();
870 }
871
TEST_F(AclManagerWithConnectionTest,send_hold_mode)872 TEST_F(AclManagerWithConnectionTest, send_hold_mode) {
873 connection_->HoldMode(0x0500, 0x0020);
874 auto packet = GetConnectionManagementCommand(OpCode::HOLD_MODE);
875 auto command_view = HoldModeView::Create(packet);
876 ASSERT_TRUE(command_view.IsValid());
877 ASSERT_EQ(command_view.GetHoldModeMaxInterval(), 0x0500);
878 ASSERT_EQ(command_view.GetHoldModeMinInterval(), 0x0020);
879
880 EXPECT_CALL(mock_connection_management_callbacks_, OnModeChange(ErrorCode::SUCCESS, Mode::HOLD, 0x0020));
881 test_hci_layer_->IncomingEvent(
882 ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::HOLD, 0x0020));
883 sync_client_handler();
884 }
885
TEST_F(AclManagerWithConnectionTest,send_sniff_mode)886 TEST_F(AclManagerWithConnectionTest, send_sniff_mode) {
887 connection_->SniffMode(0x0500, 0x0020, 0x0040, 0x0014);
888 auto packet = GetConnectionManagementCommand(OpCode::SNIFF_MODE);
889 auto command_view = SniffModeView::Create(packet);
890 ASSERT_TRUE(command_view.IsValid());
891 ASSERT_EQ(command_view.GetSniffMaxInterval(), 0x0500);
892 ASSERT_EQ(command_view.GetSniffMinInterval(), 0x0020);
893 ASSERT_EQ(command_view.GetSniffAttempt(), 0x0040);
894 ASSERT_EQ(command_view.GetSniffTimeout(), 0x0014);
895
896 EXPECT_CALL(mock_connection_management_callbacks_, OnModeChange(ErrorCode::SUCCESS, Mode::SNIFF, 0x0028));
897 test_hci_layer_->IncomingEvent(
898 ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::SNIFF, 0x0028));
899 sync_client_handler();
900 }
901
TEST_F(AclManagerWithConnectionTest,send_exit_sniff_mode)902 TEST_F(AclManagerWithConnectionTest, send_exit_sniff_mode) {
903 connection_->ExitSniffMode();
904 auto packet = GetConnectionManagementCommand(OpCode::EXIT_SNIFF_MODE);
905 auto command_view = ExitSniffModeView::Create(packet);
906 ASSERT_TRUE(command_view.IsValid());
907
908 EXPECT_CALL(mock_connection_management_callbacks_, OnModeChange(ErrorCode::SUCCESS, Mode::ACTIVE, 0x00));
909 test_hci_layer_->IncomingEvent(
910 ModeChangeBuilder::Create(ErrorCode::SUCCESS, handle_, Mode::ACTIVE, 0x00));
911 sync_client_handler();
912 }
913
TEST_F(AclManagerWithConnectionTest,send_qos_setup)914 TEST_F(AclManagerWithConnectionTest, send_qos_setup) {
915 connection_->QosSetup(ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231);
916 auto packet = GetConnectionManagementCommand(OpCode::QOS_SETUP);
917 auto command_view = QosSetupView::Create(packet);
918 ASSERT_TRUE(command_view.IsValid());
919 ASSERT_EQ(command_view.GetServiceType(), ServiceType::BEST_EFFORT);
920 ASSERT_EQ(command_view.GetTokenRate(), 0x1234u);
921 ASSERT_EQ(command_view.GetPeakBandwidth(), 0x1233u);
922 ASSERT_EQ(command_view.GetLatency(), 0x1232u);
923 ASSERT_EQ(command_view.GetDelayVariation(), 0x1231u);
924
925 EXPECT_CALL(mock_connection_management_callbacks_,
926 OnQosSetupComplete(ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231));
927 test_hci_layer_->IncomingEvent(QosSetupCompleteBuilder::Create(
928 ErrorCode::SUCCESS, handle_, ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231));
929 sync_client_handler();
930 }
931
TEST_F(AclManagerWithConnectionTest,send_flow_specification)932 TEST_F(AclManagerWithConnectionTest, send_flow_specification) {
933 connection_->FlowSpecification(
934 FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, 0x1234, 0x1233, 0x1232, 0x1231);
935 auto packet = GetConnectionManagementCommand(OpCode::FLOW_SPECIFICATION);
936 auto command_view = FlowSpecificationView::Create(packet);
937 ASSERT_TRUE(command_view.IsValid());
938 ASSERT_EQ(command_view.GetFlowDirection(), FlowDirection::OUTGOING_FLOW);
939 ASSERT_EQ(command_view.GetServiceType(), ServiceType::BEST_EFFORT);
940 ASSERT_EQ(command_view.GetTokenRate(), 0x1234u);
941 ASSERT_EQ(command_view.GetTokenBucketSize(), 0x1233u);
942 ASSERT_EQ(command_view.GetPeakBandwidth(), 0x1232u);
943 ASSERT_EQ(command_view.GetAccessLatency(), 0x1231u);
944
945 EXPECT_CALL(mock_connection_management_callbacks_,
946 OnFlowSpecificationComplete(FlowDirection::OUTGOING_FLOW, ServiceType::BEST_EFFORT, 0x1234, 0x1233,
947 0x1232, 0x1231));
948 test_hci_layer_->IncomingEvent(FlowSpecificationCompleteBuilder::Create(
949 ErrorCode::SUCCESS,
950 handle_,
951 FlowDirection::OUTGOING_FLOW,
952 ServiceType::BEST_EFFORT,
953 0x1234,
954 0x1233,
955 0x1232,
956 0x1231));
957 sync_client_handler();
958 }
959
TEST_F(AclManagerWithConnectionTest,send_flush)960 TEST_F(AclManagerWithConnectionTest, send_flush) {
961 connection_->Flush();
962 auto packet = GetConnectionManagementCommand(OpCode::ENHANCED_FLUSH);
963 auto command_view = EnhancedFlushView::Create(packet);
964 ASSERT_TRUE(command_view.IsValid());
965
966 EXPECT_CALL(mock_connection_management_callbacks_, OnFlushOccurred());
967 test_hci_layer_->IncomingEvent(EnhancedFlushCompleteBuilder::Create(handle_));
968 sync_client_handler();
969 }
970
TEST_F(AclManagerWithConnectionTest,send_role_discovery)971 TEST_F(AclManagerWithConnectionTest, send_role_discovery) {
972 connection_->RoleDiscovery();
973 auto packet = GetConnectionManagementCommand(OpCode::ROLE_DISCOVERY);
974 auto command_view = RoleDiscoveryView::Create(packet);
975 ASSERT_TRUE(command_view.IsValid());
976
977 EXPECT_CALL(mock_connection_management_callbacks_, OnRoleDiscoveryComplete(Role::CENTRAL));
978 uint8_t num_packets = 1;
979 test_hci_layer_->IncomingEvent(RoleDiscoveryCompleteBuilder::Create(
980 num_packets, ErrorCode::SUCCESS, handle_, Role::CENTRAL));
981 sync_client_handler();
982 }
983
TEST_F(AclManagerWithConnectionTest,send_read_link_policy_settings)984 TEST_F(AclManagerWithConnectionTest, send_read_link_policy_settings) {
985 connection_->ReadLinkPolicySettings();
986 auto packet = GetConnectionManagementCommand(OpCode::READ_LINK_POLICY_SETTINGS);
987 auto command_view = ReadLinkPolicySettingsView::Create(packet);
988 ASSERT_TRUE(command_view.IsValid());
989
990 EXPECT_CALL(mock_connection_management_callbacks_, OnReadLinkPolicySettingsComplete(0x07));
991 uint8_t num_packets = 1;
992 test_hci_layer_->IncomingEvent(ReadLinkPolicySettingsCompleteBuilder::Create(
993 num_packets, ErrorCode::SUCCESS, handle_, 0x07));
994 sync_client_handler();
995 }
996
TEST_F(AclManagerWithConnectionTest,send_write_link_policy_settings)997 TEST_F(AclManagerWithConnectionTest, send_write_link_policy_settings) {
998 connection_->WriteLinkPolicySettings(0x05);
999 auto packet = GetConnectionManagementCommand(OpCode::WRITE_LINK_POLICY_SETTINGS);
1000 auto command_view = WriteLinkPolicySettingsView::Create(packet);
1001 ASSERT_TRUE(command_view.IsValid());
1002 ASSERT_EQ(command_view.GetLinkPolicySettings(), 0x05);
1003
1004 uint8_t num_packets = 1;
1005 test_hci_layer_->IncomingEvent(
1006 WriteLinkPolicySettingsCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_));
1007 sync_client_handler();
1008 }
1009
TEST_F(AclManagerWithConnectionTest,send_sniff_subrating)1010 TEST_F(AclManagerWithConnectionTest, send_sniff_subrating) {
1011 connection_->SniffSubrating(0x1234, 0x1235, 0x1236);
1012 auto packet = GetConnectionManagementCommand(OpCode::SNIFF_SUBRATING);
1013 auto command_view = SniffSubratingView::Create(packet);
1014 ASSERT_TRUE(command_view.IsValid());
1015 ASSERT_EQ(command_view.GetMaximumLatency(), 0x1234);
1016 ASSERT_EQ(command_view.GetMinimumRemoteTimeout(), 0x1235);
1017 ASSERT_EQ(command_view.GetMinimumLocalTimeout(), 0x1236);
1018
1019 uint8_t num_packets = 1;
1020 test_hci_layer_->IncomingEvent(
1021 SniffSubratingCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_));
1022 sync_client_handler();
1023 }
1024
TEST_F(AclManagerWithConnectionTest,send_read_automatic_flush_timeout)1025 TEST_F(AclManagerWithConnectionTest, send_read_automatic_flush_timeout) {
1026 connection_->ReadAutomaticFlushTimeout();
1027 auto packet = GetConnectionManagementCommand(OpCode::READ_AUTOMATIC_FLUSH_TIMEOUT);
1028 auto command_view = ReadAutomaticFlushTimeoutView::Create(packet);
1029 ASSERT_TRUE(command_view.IsValid());
1030
1031 EXPECT_CALL(mock_connection_management_callbacks_, OnReadAutomaticFlushTimeoutComplete(0x07ff));
1032 uint8_t num_packets = 1;
1033 test_hci_layer_->IncomingEvent(ReadAutomaticFlushTimeoutCompleteBuilder::Create(
1034 num_packets, ErrorCode::SUCCESS, handle_, 0x07ff));
1035 sync_client_handler();
1036 }
1037
TEST_F(AclManagerWithConnectionTest,send_write_automatic_flush_timeout)1038 TEST_F(AclManagerWithConnectionTest, send_write_automatic_flush_timeout) {
1039 connection_->WriteAutomaticFlushTimeout(0x07FF);
1040 auto packet = GetConnectionManagementCommand(OpCode::WRITE_AUTOMATIC_FLUSH_TIMEOUT);
1041 auto command_view = WriteAutomaticFlushTimeoutView::Create(packet);
1042 ASSERT_TRUE(command_view.IsValid());
1043 ASSERT_EQ(command_view.GetFlushTimeout(), 0x07FF);
1044
1045 uint8_t num_packets = 1;
1046 test_hci_layer_->IncomingEvent(
1047 WriteAutomaticFlushTimeoutCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_));
1048 sync_client_handler();
1049 }
1050
TEST_F(AclManagerWithConnectionTest,send_read_transmit_power_level)1051 TEST_F(AclManagerWithConnectionTest, send_read_transmit_power_level) {
1052 connection_->ReadTransmitPowerLevel(TransmitPowerLevelType::CURRENT);
1053 auto packet = GetConnectionManagementCommand(OpCode::READ_TRANSMIT_POWER_LEVEL);
1054 auto command_view = ReadTransmitPowerLevelView::Create(packet);
1055 ASSERT_TRUE(command_view.IsValid());
1056 ASSERT_EQ(command_view.GetTransmitPowerLevelType(), TransmitPowerLevelType::CURRENT);
1057
1058 EXPECT_CALL(mock_connection_management_callbacks_, OnReadTransmitPowerLevelComplete(0x07));
1059 uint8_t num_packets = 1;
1060 test_hci_layer_->IncomingEvent(ReadTransmitPowerLevelCompleteBuilder::Create(
1061 num_packets, ErrorCode::SUCCESS, handle_, 0x07));
1062 sync_client_handler();
1063 }
1064
TEST_F(AclManagerWithConnectionTest,send_read_link_supervision_timeout)1065 TEST_F(AclManagerWithConnectionTest, send_read_link_supervision_timeout) {
1066 connection_->ReadLinkSupervisionTimeout();
1067 auto packet = GetConnectionManagementCommand(OpCode::READ_LINK_SUPERVISION_TIMEOUT);
1068 auto command_view = ReadLinkSupervisionTimeoutView::Create(packet);
1069 ASSERT_TRUE(command_view.IsValid());
1070
1071 EXPECT_CALL(mock_connection_management_callbacks_, OnReadLinkSupervisionTimeoutComplete(0x5677));
1072 uint8_t num_packets = 1;
1073 test_hci_layer_->IncomingEvent(ReadLinkSupervisionTimeoutCompleteBuilder::Create(
1074 num_packets, ErrorCode::SUCCESS, handle_, 0x5677));
1075 sync_client_handler();
1076 }
1077
TEST_F(AclManagerWithConnectionTest,send_write_link_supervision_timeout)1078 TEST_F(AclManagerWithConnectionTest, send_write_link_supervision_timeout) {
1079 connection_->WriteLinkSupervisionTimeout(0x5678);
1080 auto packet = GetConnectionManagementCommand(OpCode::WRITE_LINK_SUPERVISION_TIMEOUT);
1081 auto command_view = WriteLinkSupervisionTimeoutView::Create(packet);
1082 ASSERT_TRUE(command_view.IsValid());
1083 ASSERT_EQ(command_view.GetLinkSupervisionTimeout(), 0x5678);
1084
1085 uint8_t num_packets = 1;
1086 test_hci_layer_->IncomingEvent(
1087 WriteLinkSupervisionTimeoutCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_));
1088 sync_client_handler();
1089 }
1090
TEST_F(AclManagerWithConnectionTest,send_read_failed_contact_counter)1091 TEST_F(AclManagerWithConnectionTest, send_read_failed_contact_counter) {
1092 connection_->ReadFailedContactCounter();
1093 auto packet = GetConnectionManagementCommand(OpCode::READ_FAILED_CONTACT_COUNTER);
1094 auto command_view = ReadFailedContactCounterView::Create(packet);
1095 ASSERT_TRUE(command_view.IsValid());
1096
1097 EXPECT_CALL(mock_connection_management_callbacks_, OnReadFailedContactCounterComplete(0x00));
1098 uint8_t num_packets = 1;
1099 test_hci_layer_->IncomingEvent(ReadFailedContactCounterCompleteBuilder::Create(
1100 num_packets, ErrorCode::SUCCESS, handle_, 0x00));
1101 sync_client_handler();
1102 }
1103
TEST_F(AclManagerWithConnectionTest,send_reset_failed_contact_counter)1104 TEST_F(AclManagerWithConnectionTest, send_reset_failed_contact_counter) {
1105 connection_->ResetFailedContactCounter();
1106 auto packet = GetConnectionManagementCommand(OpCode::RESET_FAILED_CONTACT_COUNTER);
1107 auto command_view = ResetFailedContactCounterView::Create(packet);
1108 ASSERT_TRUE(command_view.IsValid());
1109
1110 uint8_t num_packets = 1;
1111 test_hci_layer_->IncomingEvent(
1112 ResetFailedContactCounterCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_));
1113 sync_client_handler();
1114 }
1115
TEST_F(AclManagerWithConnectionTest,send_read_link_quality)1116 TEST_F(AclManagerWithConnectionTest, send_read_link_quality) {
1117 connection_->ReadLinkQuality();
1118 auto packet = GetConnectionManagementCommand(OpCode::READ_LINK_QUALITY);
1119 auto command_view = ReadLinkQualityView::Create(packet);
1120 ASSERT_TRUE(command_view.IsValid());
1121
1122 EXPECT_CALL(mock_connection_management_callbacks_, OnReadLinkQualityComplete(0xa9));
1123 uint8_t num_packets = 1;
1124 test_hci_layer_->IncomingEvent(
1125 ReadLinkQualityCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_, 0xa9));
1126 sync_client_handler();
1127 }
1128
TEST_F(AclManagerWithConnectionTest,send_read_afh_channel_map)1129 TEST_F(AclManagerWithConnectionTest, send_read_afh_channel_map) {
1130 connection_->ReadAfhChannelMap();
1131 auto packet = GetConnectionManagementCommand(OpCode::READ_AFH_CHANNEL_MAP);
1132 auto command_view = ReadAfhChannelMapView::Create(packet);
1133 ASSERT_TRUE(command_view.IsValid());
1134 std::array<uint8_t, 10> afh_channel_map = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09};
1135
1136 EXPECT_CALL(mock_connection_management_callbacks_,
1137 OnReadAfhChannelMapComplete(AfhMode::AFH_ENABLED, afh_channel_map));
1138 uint8_t num_packets = 1;
1139 test_hci_layer_->IncomingEvent(ReadAfhChannelMapCompleteBuilder::Create(
1140 num_packets, ErrorCode::SUCCESS, handle_, AfhMode::AFH_ENABLED, afh_channel_map));
1141 sync_client_handler();
1142 }
1143
TEST_F(AclManagerWithConnectionTest,send_read_rssi)1144 TEST_F(AclManagerWithConnectionTest, send_read_rssi) {
1145 connection_->ReadRssi();
1146 auto packet = GetConnectionManagementCommand(OpCode::READ_RSSI);
1147 auto command_view = ReadRssiView::Create(packet);
1148 ASSERT_TRUE(command_view.IsValid());
1149 sync_client_handler();
1150 EXPECT_CALL(mock_connection_management_callbacks_, OnReadRssiComplete(0x00));
1151 uint8_t num_packets = 1;
1152 test_hci_layer_->IncomingEvent(
1153 ReadRssiCompleteBuilder::Create(num_packets, ErrorCode::SUCCESS, handle_, 0x00));
1154 sync_client_handler();
1155 }
1156
TEST_F(AclManagerWithConnectionTest,send_read_clock)1157 TEST_F(AclManagerWithConnectionTest, send_read_clock) {
1158 connection_->ReadClock(WhichClock::LOCAL);
1159 auto packet = GetConnectionManagementCommand(OpCode::READ_CLOCK);
1160 auto command_view = ReadClockView::Create(packet);
1161 ASSERT_TRUE(command_view.IsValid());
1162 ASSERT_EQ(command_view.GetWhichClock(), WhichClock::LOCAL);
1163
1164 EXPECT_CALL(mock_connection_management_callbacks_, OnReadClockComplete(0x00002e6a, 0x0000));
1165 uint8_t num_packets = 1;
1166 test_hci_layer_->IncomingEvent(ReadClockCompleteBuilder::Create(
1167 num_packets, ErrorCode::SUCCESS, handle_, 0x00002e6a, 0x0000));
1168 sync_client_handler();
1169 }
1170
1171 class AclManagerWithResolvableAddressTest : public AclManagerNoCallbacksTest {
1172 protected:
SetUp()1173 void SetUp() override {
1174 test_hci_layer_ = new HciLayerFake; // Ownership is transferred to registry
1175 test_controller_ = new TestController;
1176 fake_registry_.InjectTestModule(&HciLayer::Factory, test_hci_layer_);
1177 fake_registry_.InjectTestModule(&Controller::Factory, test_controller_);
1178 client_handler_ = fake_registry_.GetTestModuleHandler(&HciLayer::Factory);
1179 ASSERT_NE(client_handler_, nullptr);
1180 fake_registry_.Start<AclManager>(&thread_);
1181 acl_manager_ = static_cast<AclManager*>(fake_registry_.GetModuleUnderTest(&AclManager::Factory));
1182 Address::FromString("A1:A2:A3:A4:A5:A6", remote);
1183
1184 hci::Address address;
1185 Address::FromString("D0:05:04:03:02:01", address);
1186 hci::AddressWithType address_with_type(address, hci::AddressType::RANDOM_DEVICE_ADDRESS);
1187 acl_manager_->RegisterCallbacks(&mock_connection_callback_, client_handler_);
1188 acl_manager_->RegisterLeCallbacks(&mock_le_connection_callbacks_, client_handler_);
1189 auto minimum_rotation_time = std::chrono::milliseconds(7 * 60 * 1000);
1190 auto maximum_rotation_time = std::chrono::milliseconds(15 * 60 * 1000);
1191 acl_manager_->SetPrivacyPolicyForInitiatorAddress(
1192 LeAddressManager::AddressPolicy::USE_RESOLVABLE_ADDRESS,
1193 address_with_type,
1194 minimum_rotation_time,
1195 maximum_rotation_time);
1196
1197 GetConnectionManagementCommand(OpCode::LE_SET_RANDOM_ADDRESS);
1198 test_hci_layer_->IncomingEvent(LeSetRandomAddressCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1199 }
1200 };
1201
TEST_F(AclManagerWithResolvableAddressTest,create_connection_cancel_fail)1202 TEST_F(AclManagerWithResolvableAddressTest, create_connection_cancel_fail) {
1203 auto remote_with_type_ = AddressWithType(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
1204 acl_manager_->CreateLeConnection(remote_with_type_, true);
1205
1206 // Add device to connect list
1207 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1208 test_hci_layer_->IncomingEvent(
1209 LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1210
1211 // send create connection command
1212 GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
1213 test_hci_layer_->IncomingEvent(LeCreateConnectionStatusBuilder::Create(ErrorCode::SUCCESS, 0x01));
1214
1215 fake_registry_.SynchronizeModuleHandler(&HciLayer::Factory, std::chrono::milliseconds(20));
1216 fake_registry_.SynchronizeModuleHandler(&AclManager::Factory, std::chrono::milliseconds(20));
1217
1218 Address remote2;
1219 Address::FromString("A1:A2:A3:A4:A5:A7", remote2);
1220 auto remote_with_type2 = AddressWithType(remote2, AddressType::PUBLIC_DEVICE_ADDRESS);
1221
1222 // create another connection
1223 acl_manager_->CreateLeConnection(remote_with_type2, true);
1224
1225 // cancel previous connection
1226 GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION_CANCEL);
1227
1228 // receive connection complete of first device
1229 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1230 ErrorCode::SUCCESS,
1231 0x123,
1232 Role::PERIPHERAL,
1233 AddressType::PUBLIC_DEVICE_ADDRESS,
1234 remote,
1235 0x0100,
1236 0x0010,
1237 0x0011,
1238 ClockAccuracy::PPM_30));
1239
1240 // receive create connection cancel complete with ErrorCode::CONNECTION_ALREADY_EXISTS
1241 test_hci_layer_->IncomingEvent(
1242 LeCreateConnectionCancelCompleteBuilder::Create(0x01, ErrorCode::CONNECTION_ALREADY_EXISTS));
1243
1244 // Add another device to connect list
1245 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1246 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1247
1248 // Sync events.
1249 }
1250
1251 class AclManagerLifeCycleTest : public AclManagerNoCallbacksTest {
1252 protected:
SetUp()1253 void SetUp() override {
1254 AclManagerNoCallbacksTest::SetUp();
1255 acl_manager_->RegisterCallbacks(&mock_connection_callback_, client_handler_);
1256 acl_manager_->RegisterLeCallbacks(&mock_le_connection_callbacks_, client_handler_);
1257 }
1258
1259 AddressWithType remote_with_type_;
1260 uint16_t handle_{0x123};
1261 };
1262
TEST_F(AclManagerLifeCycleTest,unregister_classic_after_create_connection)1263 TEST_F(AclManagerLifeCycleTest, unregister_classic_after_create_connection) {
1264 // Inject create connection
1265 acl_manager_->CreateConnection(remote);
1266 auto connection_command = GetConnectionManagementCommand(OpCode::CREATE_CONNECTION);
1267
1268 // Unregister callbacks after sending connection request
1269 auto promise = std::promise<void>();
1270 auto future = promise.get_future();
1271 acl_manager_->UnregisterCallbacks(&mock_connection_callback_, std::move(promise));
1272 future.get();
1273
1274 // Inject peer sending connection complete
1275 auto connection_future = GetConnectionFuture();
1276 test_hci_layer_->IncomingEvent(
1277 ConnectionCompleteBuilder::Create(ErrorCode::SUCCESS, handle_, remote, LinkType::ACL, Enable::DISABLED));
1278
1279 sync_client_handler();
1280 auto connection_future_status = connection_future.wait_for(kShortTimeout);
1281 ASSERT_NE(connection_future_status, std::future_status::ready);
1282 }
1283
TEST_F(AclManagerLifeCycleTest,unregister_le_before_connection_complete)1284 TEST_F(AclManagerLifeCycleTest, unregister_le_before_connection_complete) {
1285 AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
1286 acl_manager_->CreateLeConnection(remote_with_type, true);
1287 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1288 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1289
1290 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
1291 auto le_connection_management_command_view =
1292 LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
1293 auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
1294 ASSERT_TRUE(command_view.IsValid());
1295 if (use_accept_list_) {
1296 ASSERT_EQ(command_view.GetPeerAddress(), hci::Address::kEmpty);
1297 } else {
1298 ASSERT_EQ(command_view.GetPeerAddress(), remote);
1299 }
1300 ASSERT_EQ(command_view.GetPeerAddressType(), AddressType::PUBLIC_DEVICE_ADDRESS);
1301
1302 // Unregister callbacks after sending connection request
1303 auto promise = std::promise<void>();
1304 auto future = promise.get_future();
1305 acl_manager_->UnregisterLeCallbacks(&mock_le_connection_callbacks_, std::move(promise));
1306 future.get();
1307
1308 auto connection_future = GetLeConnectionFuture();
1309 test_hci_layer_->IncomingLeMetaEvent(LeConnectionCompleteBuilder::Create(
1310 ErrorCode::SUCCESS,
1311 0x123,
1312 Role::PERIPHERAL,
1313 AddressType::PUBLIC_DEVICE_ADDRESS,
1314 remote,
1315 0x0100,
1316 0x0010,
1317 0x0500,
1318 ClockAccuracy::PPM_30));
1319
1320 sync_client_handler();
1321 auto connection_future_status = connection_future.wait_for(kShortTimeout);
1322 ASSERT_NE(connection_future_status, std::future_status::ready);
1323 }
1324
TEST_F(AclManagerLifeCycleTest,unregister_le_before_enhanced_connection_complete)1325 TEST_F(AclManagerLifeCycleTest, unregister_le_before_enhanced_connection_complete) {
1326 AddressWithType remote_with_type(remote, AddressType::PUBLIC_DEVICE_ADDRESS);
1327 acl_manager_->CreateLeConnection(remote_with_type, true);
1328 GetConnectionManagementCommand(OpCode::LE_ADD_DEVICE_TO_FILTER_ACCEPT_LIST);
1329 test_hci_layer_->IncomingEvent(LeAddDeviceToFilterAcceptListCompleteBuilder::Create(0x01, ErrorCode::SUCCESS));
1330
1331 auto packet = GetConnectionManagementCommand(OpCode::LE_CREATE_CONNECTION);
1332 auto le_connection_management_command_view =
1333 LeConnectionManagementCommandView::Create(AclCommandView::Create(packet));
1334 auto command_view = LeCreateConnectionView::Create(le_connection_management_command_view);
1335 ASSERT_TRUE(command_view.IsValid());
1336 if (use_accept_list_) {
1337 ASSERT_EQ(command_view.GetPeerAddress(), hci::Address::kEmpty);
1338 } else {
1339 ASSERT_EQ(command_view.GetPeerAddress(), remote);
1340 }
1341 ASSERT_EQ(command_view.GetPeerAddressType(), AddressType::PUBLIC_DEVICE_ADDRESS);
1342
1343 // Unregister callbacks after sending connection request
1344 auto promise = std::promise<void>();
1345 auto future = promise.get_future();
1346 acl_manager_->UnregisterLeCallbacks(&mock_le_connection_callbacks_, std::move(promise));
1347 future.get();
1348
1349 auto connection_future = GetLeConnectionFuture();
1350 test_hci_layer_->IncomingLeMetaEvent(LeEnhancedConnectionCompleteBuilder::Create(
1351 ErrorCode::SUCCESS,
1352 0x123,
1353 Role::PERIPHERAL,
1354 AddressType::PUBLIC_DEVICE_ADDRESS,
1355 remote,
1356 Address::kEmpty,
1357 Address::kEmpty,
1358 0x0100,
1359 0x0010,
1360 0x0500,
1361 ClockAccuracy::PPM_30));
1362
1363 sync_client_handler();
1364 auto connection_future_status = connection_future.wait_for(kShortTimeout);
1365 ASSERT_NE(connection_future_status, std::future_status::ready);
1366 }
1367
1368 class AclManagerWithConnectionAssemblerTest : public AclManagerWithConnectionTest {
1369 protected:
SetUp()1370 void SetUp() override {
1371 AclManagerWithConnectionTest::SetUp();
1372 connection_queue_end_ = connection_->GetAclQueueEnd();
1373 }
1374
MakeAclPayload(size_t length,uint16_t cid,uint8_t offset)1375 std::vector<uint8_t> MakeAclPayload(size_t length, uint16_t cid, uint8_t offset) {
1376 std::vector<uint8_t> acl_payload;
1377 acl_payload.push_back(length & 0xff);
1378 acl_payload.push_back((length >> 8u) & 0xff);
1379 acl_payload.push_back(cid & 0xff);
1380 acl_payload.push_back((cid >> 8u) & 0xff);
1381 for (uint8_t i = 0; i < length; i++) {
1382 acl_payload.push_back(i + offset);
1383 }
1384 return acl_payload;
1385 }
1386
SendSinglePacket(const std::vector<uint8_t> & acl_payload)1387 void SendSinglePacket(const std::vector<uint8_t>& acl_payload) {
1388 auto payload_builder = std::make_unique<RawBuilder>(acl_payload);
1389
1390 test_hci_layer_->IncomingAclData(
1391 handle_,
1392 AclBuilder::Create(
1393 handle_,
1394 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1395 BroadcastFlag::POINT_TO_POINT,
1396 std::move(payload_builder)));
1397 }
1398
ReceiveAndCheckSinglePacket(const std::vector<uint8_t> & acl_payload)1399 void ReceiveAndCheckSinglePacket(const std::vector<uint8_t>& acl_payload) {
1400 std::unique_ptr<PacketView<kLittleEndian>> received;
1401 do {
1402 received = connection_queue_end_->TryDequeue();
1403 } while (received == nullptr);
1404
1405 std::vector<uint8_t> received_vector;
1406 for (uint8_t byte : *received) {
1407 received_vector.push_back(byte);
1408 }
1409
1410 EXPECT_THAT(received_vector, ElementsAreArray(acl_payload));
1411 }
1412
SendAndReceiveSinglePacket(const std::vector<uint8_t> & acl_payload)1413 void SendAndReceiveSinglePacket(const std::vector<uint8_t>& acl_payload) {
1414 SendSinglePacket(acl_payload);
1415 ReceiveAndCheckSinglePacket(acl_payload);
1416 }
1417
TearDown()1418 void TearDown() override {
1419 // Make sure that all previous packets were received and the assembler is in a good state.
1420 SendAndReceiveSinglePacket(MakeAclPayload(0x60, 0xACC, 3));
1421 AclManagerWithConnectionTest::TearDown();
1422 }
1423 AclConnection::QueueUpEnd* connection_queue_end_{};
1424 };
1425
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_single_packet)1426 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_single_packet) {}
1427
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_short_packet_discarded)1428 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_short_packet_discarded) {
1429 std::vector<uint8_t> invalid_payload{1, 2};
1430 test_hci_layer_->IncomingAclData(
1431 handle_,
1432 AclBuilder::Create(
1433 handle_,
1434 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1435 BroadcastFlag::POINT_TO_POINT,
1436 std::make_unique<RawBuilder>(invalid_payload)));
1437 }
1438
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_two_short_packets_discarded)1439 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_two_short_packets_discarded) {
1440 std::vector<uint8_t> invalid_payload{1, 2};
1441 test_hci_layer_->IncomingAclData(
1442 handle_,
1443 AclBuilder::Create(
1444 handle_,
1445 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1446 BroadcastFlag::POINT_TO_POINT,
1447 std::make_unique<RawBuilder>(invalid_payload)));
1448 test_hci_layer_->IncomingAclData(
1449 handle_,
1450 AclBuilder::Create(
1451 handle_,
1452 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1453 BroadcastFlag::POINT_TO_POINT,
1454 std::make_unique<RawBuilder>(invalid_payload)));
1455 }
1456
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_single_valid_packet)1457 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_single_valid_packet) {
1458 SendAndReceiveSinglePacket(MakeAclPayload(20, 0x41, 2));
1459 }
1460
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_one_byte_packets)1461 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_one_byte_packets) {
1462 size_t payload_size = 0x30;
1463 std::vector<uint8_t> payload = MakeAclPayload(payload_size, 0xABB /* cid */, 4 /* offset */);
1464 test_hci_layer_->IncomingAclData(
1465 handle_,
1466 AclBuilder::Create(
1467 handle_,
1468 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1469 BroadcastFlag::POINT_TO_POINT,
1470 std::make_unique<RawBuilder>(
1471 std::vector<uint8_t>{payload.cbegin(), payload.cbegin() + 1})));
1472 for (size_t i = 1; i < payload.size(); i++) {
1473 test_hci_layer_->IncomingAclData(
1474 handle_,
1475 AclBuilder::Create(
1476 handle_,
1477 PacketBoundaryFlag::CONTINUING_FRAGMENT,
1478 BroadcastFlag::POINT_TO_POINT,
1479 std::make_unique<RawBuilder>(
1480 std::vector<uint8_t>{payload.cbegin() + i, payload.cbegin() + i + 1})));
1481 }
1482 ReceiveAndCheckSinglePacket(payload);
1483 }
1484
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_two_byte_packets)1485 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_two_byte_packets) {
1486 size_t payload_size = 0x30; // must be even
1487 std::vector<uint8_t> payload = MakeAclPayload(payload_size, 0xABB /* cid */, 4 /* offset */);
1488 test_hci_layer_->IncomingAclData(
1489 handle_,
1490 AclBuilder::Create(
1491 handle_,
1492 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1493 BroadcastFlag::POINT_TO_POINT,
1494 std::make_unique<RawBuilder>(
1495 std::vector<uint8_t>{payload.cbegin(), payload.cbegin() + 2})));
1496 for (size_t i = 1; i < payload.size() / 2; i++) {
1497 test_hci_layer_->IncomingAclData(
1498 handle_,
1499 AclBuilder::Create(
1500 handle_,
1501 PacketBoundaryFlag::CONTINUING_FRAGMENT,
1502 BroadcastFlag::POINT_TO_POINT,
1503 std::make_unique<RawBuilder>(
1504 std::vector<uint8_t>{payload.cbegin() + 2 * i, payload.cbegin() + 2 * (i + 1)})));
1505 }
1506 ReceiveAndCheckSinglePacket(payload);
1507 }
1508
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_continuation_without_begin)1509 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_continuation_without_begin) {
1510 size_t payload_size = 0x30;
1511 std::vector<uint8_t> payload = MakeAclPayload(payload_size, 0xABB /* cid */, 4 /* offset */);
1512 test_hci_layer_->IncomingAclData(
1513 handle_,
1514 AclBuilder::Create(
1515 handle_,
1516 PacketBoundaryFlag::CONTINUING_FRAGMENT,
1517 BroadcastFlag::POINT_TO_POINT,
1518 std::make_unique<RawBuilder>(std::vector<uint8_t>{payload.cbegin(), payload.cend()})));
1519 }
1520
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_drop_broadcasts)1521 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_drop_broadcasts) {
1522 test_hci_layer_->IncomingAclData(
1523 handle_,
1524 AclBuilder::Create(
1525 handle_,
1526 PacketBoundaryFlag::FIRST_AUTOMATICALLY_FLUSHABLE,
1527 BroadcastFlag::ACTIVE_PERIPHERAL_BROADCAST,
1528 std::make_unique<RawBuilder>(MakeAclPayload(20, 0xBBB /* cid */, 5 /* offset */))));
1529 }
1530
TEST_F(AclManagerWithConnectionAssemblerTest,assembler_test_drop_non_flushable)1531 TEST_F(AclManagerWithConnectionAssemblerTest, assembler_test_drop_non_flushable) {
1532 test_hci_layer_->IncomingAclData(
1533 handle_,
1534 AclBuilder::Create(
1535 handle_,
1536 PacketBoundaryFlag::FIRST_NON_AUTOMATICALLY_FLUSHABLE,
1537 BroadcastFlag::POINT_TO_POINT,
1538 std::make_unique<RawBuilder>(MakeAclPayload(20, 0xAAA /* cid */, 6 /* offset */))));
1539 }
1540
1541 } // namespace acl_manager
1542 } // namespace hci
1543 } // namespace bluetooth
1544