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