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