• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_bluetooth_sapphire/internal/host/l2cap/channel_manager.h"
16 
17 #include <memory>
18 #include <type_traits>
19 
20 #include "pw_bluetooth_sapphire/internal/host/common/macros.h"
21 #include "pw_bluetooth_sapphire/internal/host/hci-spec/protocol.h"
22 #include "pw_bluetooth_sapphire/internal/host/l2cap/channel.h"
23 #include "pw_bluetooth_sapphire/internal/host/l2cap/channel_manager_mock_controller_test_fixture.h"
24 #include "pw_bluetooth_sapphire/internal/host/l2cap/l2cap_defs.h"
25 #include "pw_bluetooth_sapphire/internal/host/l2cap/test_packets.h"
26 #include "pw_bluetooth_sapphire/internal/host/testing/inspect.h"
27 #include "pw_bluetooth_sapphire/internal/host/testing/test_helpers.h"
28 #include "pw_bluetooth_sapphire/internal/host/testing/test_packets.h"
29 #include "pw_bluetooth_sapphire/internal/host/transport/acl_data_packet.h"
30 #include "pw_bluetooth_sapphire/internal/host/transport/mock_acl_data_channel.h"
31 
32 #pragma clang diagnostic ignored "-Wshadow"
33 
34 namespace bt::l2cap {
35 namespace {
36 
37 namespace hci_android = bt::hci_spec::vendor::android;
38 using namespace inspect::testing;
39 using namespace bt::testing;
40 
41 using LEFixedChannels = ChannelManager::LEFixedChannels;
42 using BrEdrFixedChannels = ChannelManager::BrEdrFixedChannels;
43 
44 using AclPriority = pw::bluetooth::AclPriority;
45 
46 constexpr hci_spec::ConnectionHandle kTestHandle1 = 0x0001;
47 constexpr hci_spec::ConnectionHandle kTestHandle2 = 0x0002;
48 constexpr Psm kTestPsm = 0x0001;
49 constexpr ChannelId kLocalId = 0x0040;
50 constexpr ChannelId kRemoteId = 0x9042;
51 constexpr CommandId kPeerConfigRequestId = 153;
52 constexpr hci::AclDataChannel::PacketPriority kLowPriority =
53     hci::AclDataChannel::PacketPriority::kLow;
54 constexpr hci::AclDataChannel::PacketPriority kHighPriority =
55     hci::AclDataChannel::PacketPriority::kHigh;
56 constexpr ChannelParameters kChannelParams;
57 
58 constexpr pw::chrono::SystemClock::duration kFlushTimeout =
59     std::chrono::milliseconds(10);
60 constexpr uint16_t kExpectedFlushTimeoutParam =
61     16;  // 10ms * kFlushTimeoutMsToCommandParameterConversionFactor(1.6)
62 
63 // 2x Information Requests: Extended Features, Fixed Channels Supported
64 constexpr size_t kConnectionCreationPacketCount = 2;
65 
DoNothing()66 void DoNothing() {}
NopRxCallback(ByteBufferPtr)67 void NopRxCallback(ByteBufferPtr) {}
NopLeConnParamCallback(const hci_spec::LEPreferredConnectionParameters &)68 void NopLeConnParamCallback(const hci_spec::LEPreferredConnectionParameters&) {}
NopSecurityCallback(hci_spec::ConnectionHandle,sm::SecurityLevel,sm::ResultFunction<>)69 void NopSecurityCallback(hci_spec::ConnectionHandle,
70                          sm::SecurityLevel,
71                          sm::ResultFunction<>) {}
72 
73 // Holds expected outbound data packets including the source location where the
74 // expectation is set.
75 struct PacketExpectation {
76   const char* file_name;
77   int line_number;
78   DynamicByteBuffer data;
79   bt::LinkType ll_type;
80   hci::AclDataChannel::PacketPriority priority;
81 };
82 
83 // Helpers to set an outbound packet expectation with the link type and source
84 // location boilerplate prefilled.
85 // TODO(fxbug.dev/42075355): Remove packet priorities from expectations
86 #define EXPECT_LE_PACKET_OUT(packet_buffer, priority) \
87   ExpectOutboundPacket(                               \
88       bt::LinkType::kLE, (priority), (packet_buffer), __FILE__, __LINE__)
89 
90 // EXPECT_ACL_PACKET_OUT is already defined by MockController.
91 #define EXPECT_ACL_PACKET_OUT_(packet_buffer, priority) \
92   ExpectOutboundPacket(                                 \
93       bt::LinkType::kACL, (priority), (packet_buffer), __FILE__, __LINE__)
94 
MakeExtendedFeaturesInformationRequest(CommandId id,hci_spec::ConnectionHandle handle)95 auto MakeExtendedFeaturesInformationRequest(CommandId id,
96                                             hci_spec::ConnectionHandle handle) {
97   return StaticByteBuffer(
98       // ACL data header (handle, length: 10)
99       LowerBits(handle),
100       UpperBits(handle),
101       0x0a,
102       0x00,
103       // L2CAP B-frame header (length: 6, chanel-id: 0x0001 (ACL sig))
104       0x06,
105       0x00,
106       0x01,
107       0x00,
108       // Extended Features Information Request (ID, length: 2, type)
109       0x0a,
110       id,
111       0x02,
112       0x00,
113       LowerBits(
114           static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)),
115       UpperBits(
116           static_cast<uint16_t>(InformationType::kExtendedFeaturesSupported)));
117 }
118 
ConfigurationRequest(CommandId id,ChannelId dst_id,uint16_t mtu=kDefaultMTU,std::optional<RetransmissionAndFlowControlMode> mode=std::nullopt,uint8_t max_inbound_transmissions=0)119 auto ConfigurationRequest(
120     CommandId id,
121     ChannelId dst_id,
122     uint16_t mtu = kDefaultMTU,
123     std::optional<RetransmissionAndFlowControlMode> mode = std::nullopt,
124     uint8_t max_inbound_transmissions = 0) {
125   if (mode.has_value()) {
126     return DynamicByteBuffer(StaticByteBuffer(
127         // ACL data header (handle: 0x0001, length: 27 bytes)
128         0x01,
129         0x00,
130         0x1b,
131         0x00,
132         // L2CAP B-frame header (length: 23 bytes, channel-id: 0x0001 (ACL sig))
133         0x17,
134         0x00,
135         0x01,
136         0x00,
137         // Configuration Request (ID, length: 19, dst cid, flags: 0)
138         0x04,
139         id,
140         0x13,
141         0x00,
142         LowerBits(dst_id),
143         UpperBits(dst_id),
144         0x00,
145         0x00,
146         // Mtu option (ID, Length, MTU)
147         0x01,
148         0x02,
149         LowerBits(mtu),
150         UpperBits(mtu),
151         // Retransmission & Flow Control option (type, length: 9, mode,
152         // tx_window: 63, max_retransmit: 0, retransmit timeout: 0 ms, monitor
153         // timeout: 0 ms, mps: 65535)
154         0x04,
155         0x09,
156         static_cast<uint8_t>(*mode),
157         kErtmMaxUnackedInboundFrames,
158         max_inbound_transmissions,
159         0x00,
160         0x00,
161         0x00,
162         0x00,
163         LowerBits(kMaxInboundPduPayloadSize),
164         UpperBits(kMaxInboundPduPayloadSize)));
165   }
166   return DynamicByteBuffer(StaticByteBuffer(
167       // ACL data header (handle: 0x0001, length: 16 bytes)
168       0x01,
169       0x00,
170       0x10,
171       0x00,
172       // L2CAP B-frame header (length: 12 bytes, channel-id: 0x0001 (ACL sig))
173       0x0c,
174       0x00,
175       0x01,
176       0x00,
177       // Configuration Request (ID, length: 8, dst cid, flags: 0)
178       0x04,
179       id,
180       0x08,
181       0x00,
182       LowerBits(dst_id),
183       UpperBits(dst_id),
184       0x00,
185       0x00,
186       // Mtu option (ID, Length, MTU)
187       0x01,
188       0x02,
189       LowerBits(mtu),
190       UpperBits(mtu)));
191 }
192 
OutboundConnectionResponse(CommandId id)193 auto OutboundConnectionResponse(CommandId id) {
194   return testing::AclConnectionRsp(id, kTestHandle1, kRemoteId, kLocalId);
195 }
196 
InboundConnectionResponse(CommandId id)197 auto InboundConnectionResponse(CommandId id) {
198   return testing::AclConnectionRsp(id, kTestHandle1, kLocalId, kRemoteId);
199 }
200 
InboundConfigurationRequest(CommandId id,uint16_t mtu=kDefaultMTU,std::optional<RetransmissionAndFlowControlMode> mode=std::nullopt,uint8_t max_inbound_transmissions=0)201 auto InboundConfigurationRequest(
202     CommandId id,
203     uint16_t mtu = kDefaultMTU,
204     std::optional<RetransmissionAndFlowControlMode> mode = std::nullopt,
205     uint8_t max_inbound_transmissions = 0) {
206   return ConfigurationRequest(
207       id, kLocalId, mtu, mode, max_inbound_transmissions);
208 }
209 
InboundConfigurationResponse(CommandId id)210 auto InboundConfigurationResponse(CommandId id) {
211   return StaticByteBuffer(
212       // ACL data header (handle: 0x0001, length: 14 bytes)
213       0x01,
214       0x00,
215       0x0e,
216       0x00,
217       // L2CAP B-frame header (length: 10 bytes, channel-id: 0x0001 (ACL sig))
218       0x0a,
219       0x00,
220       0x01,
221       0x00,
222       // Configuration Response (ID: 2, length: 6, src cid, flags: 0, res:
223       // success)
224       0x05,
225       id,
226       0x06,
227       0x00,
228       LowerBits(kLocalId),
229       UpperBits(kLocalId),
230       0x00,
231       0x00,
232       0x00,
233       0x00);
234 }
235 
InboundConnectionRequest(CommandId id)236 auto InboundConnectionRequest(CommandId id) {
237   return StaticByteBuffer(
238       // ACL data header (handle: 0x0001, length: 12 bytes)
239       0x01,
240       0x00,
241       0x0c,
242       0x00,
243       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
244       0x08,
245       0x00,
246       0x01,
247       0x00,
248       // Connection Request (ID, length: 4, psm, src cid)
249       0x02,
250       id,
251       0x04,
252       0x00,
253       LowerBits(kTestPsm),
254       UpperBits(kTestPsm),
255       LowerBits(kRemoteId),
256       UpperBits(kRemoteId));
257 }
258 
OutboundConnectionRequest(CommandId id)259 auto OutboundConnectionRequest(CommandId id) {
260   return StaticByteBuffer(
261       // ACL data header (handle: 0x0001, length: 12 bytes)
262       0x01,
263       0x00,
264       0x0c,
265       0x00,
266       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
267       0x08,
268       0x00,
269       0x01,
270       0x00,
271       // Connection Request (ID, length: 4, psm, src cid)
272       0x02,
273       id,
274       0x04,
275       0x00,
276       LowerBits(kTestPsm),
277       UpperBits(kTestPsm),
278       LowerBits(kLocalId),
279       UpperBits(kLocalId));
280 }
281 
OutboundConfigurationRequest(CommandId id,uint16_t mtu=kMaxMTU,std::optional<RetransmissionAndFlowControlMode> mode=std::nullopt)282 auto OutboundConfigurationRequest(
283     CommandId id,
284     uint16_t mtu = kMaxMTU,
285     std::optional<RetransmissionAndFlowControlMode> mode = std::nullopt) {
286   return ConfigurationRequest(
287       id, kRemoteId, mtu, mode, kErtmMaxInboundRetransmissions);
288 }
289 
290 // |max_transmissions| is ignored per Core Spec v5.0 Vol 3, Part A, Sec 5.4 but
291 // still parameterized because this needs to match the value that is sent by our
292 // L2CAP configuration logic.
OutboundConfigurationResponse(CommandId id,uint16_t mtu=kDefaultMTU,std::optional<RetransmissionAndFlowControlMode> mode=std::nullopt,uint8_t max_transmissions=0)293 auto OutboundConfigurationResponse(
294     CommandId id,
295     uint16_t mtu = kDefaultMTU,
296     std::optional<RetransmissionAndFlowControlMode> mode = std::nullopt,
297     uint8_t max_transmissions = 0) {
298   const uint8_t kConfigLength = 10 + (mode.has_value() ? 11 : 0);
299   const uint16_t kL2capLength = kConfigLength + 4;
300   const uint16_t kAclLength = kL2capLength + 4;
301 
302   if (mode.has_value()) {
303     return DynamicByteBuffer(StaticByteBuffer(
304         // ACL data header (handle: 0x0001, length: 14 bytes)
305         0x01,
306         0x00,
307         LowerBits(kAclLength),
308         UpperBits(kAclLength),
309         // L2CAP B-frame header (length: 10 bytes, channel-id: 0x0001 (ACL sig))
310         LowerBits(kL2capLength),
311         UpperBits(kL2capLength),
312         0x01,
313         0x00,
314         // Configuration Response (ID, length, src cid, flags: 0, res: success)
315         0x05,
316         id,
317         kConfigLength,
318         0x00,
319         LowerBits(kRemoteId),
320         UpperBits(kRemoteId),
321         0x00,
322         0x00,
323         0x00,
324         0x00,
325         // MTU option (ID, Length, MTU)
326         0x01,
327         0x02,
328         LowerBits(mtu),
329         UpperBits(mtu),
330         // Retransmission & Flow Control option (type, length: 9, mode,
331         // TxWindow, MaxTransmit, rtx timeout: 2 secs, monitor timeout: 12 secs,
332         // mps)
333         0x04,
334         0x09,
335         static_cast<uint8_t>(*mode),
336         kErtmMaxUnackedInboundFrames,
337         max_transmissions,
338         LowerBits(kErtmReceiverReadyPollTimerMsecs),
339         UpperBits(kErtmReceiverReadyPollTimerMsecs),
340         LowerBits(kErtmMonitorTimerMsecs),
341         UpperBits(kErtmMonitorTimerMsecs),
342         LowerBits(kMaxInboundPduPayloadSize),
343         UpperBits(kMaxInboundPduPayloadSize)));
344   }
345 
346   return DynamicByteBuffer(StaticByteBuffer(
347       // ACL data header (handle: 0x0001, length: 14 bytes)
348       0x01,
349       0x00,
350       LowerBits(kAclLength),
351       UpperBits(kAclLength),
352       // L2CAP B-frame header (length, channel-id: 0x0001 (ACL sig))
353       LowerBits(kL2capLength),
354       UpperBits(kL2capLength),
355       0x01,
356       0x00,
357       // Configuration Response (ID, length, src cid, flags: 0, res: success)
358       0x05,
359       id,
360       kConfigLength,
361       0x00,
362       LowerBits(kRemoteId),
363       UpperBits(kRemoteId),
364       0x00,
365       0x00,
366       0x00,
367       0x00,
368       // MTU option (ID, Length, MTU)
369       0x01,
370       0x02,
371       LowerBits(mtu),
372       UpperBits(mtu)));
373 }
374 
OutboundDisconnectionRequest(CommandId id)375 auto OutboundDisconnectionRequest(CommandId id) {
376   return StaticByteBuffer(
377       // ACL data header (handle: 0x0001, length: 12 bytes)
378       0x01,
379       0x00,
380       0x0c,
381       0x00,
382       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
383       0x08,
384       0x00,
385       0x01,
386       0x00,
387       // Disconnection Request (ID, length: 4, dst cid, src cid)
388       0x06,
389       id,
390       0x04,
391       0x00,
392       LowerBits(kRemoteId),
393       UpperBits(kRemoteId),
394       LowerBits(kLocalId),
395       UpperBits(kLocalId));
396 }
397 
OutboundDisconnectionResponse(CommandId id)398 auto OutboundDisconnectionResponse(CommandId id) {
399   return StaticByteBuffer(
400       // ACL data header (handle: 0x0001, length: 12 bytes)
401       0x01,
402       0x00,
403       0x0c,
404       0x00,
405       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
406       0x08,
407       0x00,
408       0x01,
409       0x00,
410       // Disconnection Response (ID, length: 4, dst cid, src cid)
411       0x07,
412       id,
413       0x04,
414       0x00,
415       LowerBits(kLocalId),
416       UpperBits(kLocalId),
417       LowerBits(kRemoteId),
418       UpperBits(kRemoteId));
419 }
420 
BuildConfiguration(hci_android::A2dpCodecType codec=hci_android::A2dpCodecType::kSbc)421 A2dpOffloadManager::Configuration BuildConfiguration(
422     hci_android::A2dpCodecType codec = hci_android::A2dpCodecType::kSbc) {
423   hci_android::A2dpScmsTEnable scms_t_enable;
424   scms_t_enable.enabled = pw::bluetooth::emboss::GenericEnableParam::DISABLE;
425   scms_t_enable.header = 0x00;
426 
427   hci_android::A2dpOffloadCodecInformation codec_information;
428   switch (codec) {
429     case hci_android::A2dpCodecType::kSbc:
430       codec_information.sbc.blocklen_subbands_alloc_method = 0x00;
431       codec_information.sbc.min_bitpool_value = 0x00;
432       codec_information.sbc.max_bitpool_value = 0xFF;
433       memset(codec_information.sbc.reserved,
434              0,
435              sizeof(codec_information.sbc.reserved));
436       break;
437     case hci_android::A2dpCodecType::kAac:
438       codec_information.aac.object_type = 0x00;
439       codec_information.aac.variable_bit_rate =
440           hci_android::A2dpAacEnableVariableBitRate::kDisable;
441       memset(codec_information.aac.reserved,
442              0,
443              sizeof(codec_information.aac.reserved));
444       break;
445     case hci_android::A2dpCodecType::kLdac:
446       codec_information.ldac.vendor_id = 0x0000012D;
447       codec_information.ldac.codec_id = 0x00AA;
448       codec_information.ldac.bitrate_index =
449           hci_android::A2dpBitrateIndex::kLow;
450       codec_information.ldac.ldac_channel_mode =
451           hci_android::A2dpLdacChannelMode::kStereo;
452       memset(codec_information.ldac.reserved,
453              0,
454              sizeof(codec_information.ldac.reserved));
455       break;
456     default:
457       memset(codec_information.aptx.reserved,
458              0,
459              sizeof(codec_information.aptx.reserved));
460       break;
461   }
462 
463   A2dpOffloadManager::Configuration config;
464   config.codec = codec;
465   config.max_latency = 0xFFFF;
466   config.scms_t_enable = scms_t_enable;
467   config.sampling_frequency = hci_android::A2dpSamplingFrequency::k44100Hz;
468   config.bits_per_sample = hci_android::A2dpBitsPerSample::k16BitsPerSample;
469   config.channel_mode = hci_android::A2dpChannelMode::kMono;
470   config.encoded_audio_bit_rate = 0x0;
471   config.codec_information = codec_information;
472 
473   return config;
474 }
475 
476 using TestingBase = FakeDispatcherControllerTest<MockController>;
477 
478 // ChannelManager test fixture that uses MockAclDataChannel to inject inbound
479 // data and test outbound data. Unexpected outbound packets will cause test
480 // failures.
481 class ChannelManagerMockAclChannelTest : public TestingBase {
482  public:
483   ChannelManagerMockAclChannelTest() = default;
484   ~ChannelManagerMockAclChannelTest() override = default;
485 
SetUp()486   void SetUp() override {
487     SetUp(hci_spec::kMaxACLPayloadSize, hci_spec::kMaxACLPayloadSize);
488   }
489 
SetUp(size_t max_acl_payload_size,size_t max_le_payload_size)490   void SetUp(size_t max_acl_payload_size, size_t max_le_payload_size) {
491     TestingBase::SetUp();
492 
493     acl_data_channel_.set_bredr_buffer_info(
494         hci::DataBufferInfo(max_acl_payload_size, /*max_num_packets=*/1));
495     acl_data_channel_.set_le_buffer_info(
496         hci::DataBufferInfo(max_le_payload_size, /*max_num_packets=*/1));
497     acl_data_channel_.set_send_packets_cb(
498         fit::bind_member<&ChannelManagerMockAclChannelTest::SendPackets>(this));
499 
500     // TODO(fxbug.dev/42141538): Make these tests not depend on strict channel
501     // ID ordering.
502     chanmgr_ = ChannelManager::Create(&acl_data_channel_,
503                                       transport()->command_channel(),
504                                       /*random_channel_ids=*/false,
505                                       dispatcher());
506 
507     packet_rx_handler_ = [this](std::unique_ptr<hci::ACLDataPacket> packet) {
508       acl_data_channel_.ReceivePacket(std::move(packet));
509     };
510 
511     next_command_id_ = 1;
512   }
513 
TearDown()514   void TearDown() override {
515     while (!expected_packets_.empty()) {
516       auto& expected = expected_packets_.front();
517       ADD_FAILURE_AT(expected.file_name, expected.line_number)
518           << "Didn't receive expected outbound " << expected.data.size()
519           << "-byte packet";
520       expected_packets_.pop();
521     }
522     chanmgr_ = nullptr;
523     packet_rx_handler_ = nullptr;
524     TestingBase::TearDown();
525   }
526 
527   // Helper functions for registering logical links with default arguments.
RegisterLE(hci_spec::ConnectionHandle handle,pw::bluetooth::emboss::ConnectionRole role,LinkErrorCallback link_error_cb=DoNothing,LEConnectionParameterUpdateCallback cpuc=NopLeConnParamCallback,SecurityUpgradeCallback suc=NopSecurityCallback)528   [[nodiscard]] ChannelManager::LEFixedChannels RegisterLE(
529       hci_spec::ConnectionHandle handle,
530       pw::bluetooth::emboss::ConnectionRole role,
531       LinkErrorCallback link_error_cb = DoNothing,
532       LEConnectionParameterUpdateCallback cpuc = NopLeConnParamCallback,
533       SecurityUpgradeCallback suc = NopSecurityCallback) {
534     return chanmgr()->AddLEConnection(handle,
535                                       role,
536                                       std::move(link_error_cb),
537                                       std::move(cpuc),
538                                       std::move(suc));
539   }
540 
541   struct QueueRegisterACLRetVal {
542     CommandId extended_features_id;
543     CommandId fixed_channels_supported_id;
544     ChannelManager::BrEdrFixedChannels fixed_channels;
545   };
546 
QueueRegisterACL(hci_spec::ConnectionHandle handle,pw::bluetooth::emboss::ConnectionRole role,LinkErrorCallback link_error_cb=DoNothing,SecurityUpgradeCallback suc=NopSecurityCallback)547   QueueRegisterACLRetVal QueueRegisterACL(
548       hci_spec::ConnectionHandle handle,
549       pw::bluetooth::emboss::ConnectionRole role,
550       LinkErrorCallback link_error_cb = DoNothing,
551       SecurityUpgradeCallback suc = NopSecurityCallback) {
552     QueueRegisterACLRetVal return_val;
553     return_val.extended_features_id = NextCommandId();
554     return_val.fixed_channels_supported_id = NextCommandId();
555 
556     EXPECT_ACL_PACKET_OUT_(MakeExtendedFeaturesInformationRequest(
557                                return_val.extended_features_id, handle),
558                            kHighPriority);
559     EXPECT_ACL_PACKET_OUT_(testing::AclFixedChannelsSupportedInfoReq(
560                                return_val.fixed_channels_supported_id, handle),
561                            kHighPriority);
562     return_val.fixed_channels =
563         RegisterACL(handle, role, std::move(link_error_cb), std::move(suc));
564     return return_val;
565   }
566 
RegisterACL(hci_spec::ConnectionHandle handle,pw::bluetooth::emboss::ConnectionRole role,LinkErrorCallback link_error_cb=DoNothing,SecurityUpgradeCallback suc=NopSecurityCallback)567   ChannelManager::BrEdrFixedChannels RegisterACL(
568       hci_spec::ConnectionHandle handle,
569       pw::bluetooth::emboss::ConnectionRole role,
570       LinkErrorCallback link_error_cb = DoNothing,
571       SecurityUpgradeCallback suc = NopSecurityCallback) {
572     return chanmgr()->AddACLConnection(
573         handle, role, std::move(link_error_cb), std::move(suc));
574   }
575 
ReceiveL2capInformationResponses(CommandId extended_features_id,CommandId fixed_channels_supported_id,l2cap::ExtendedFeatures features=0u,l2cap::FixedChannelsSupported channels=0u)576   void ReceiveL2capInformationResponses(
577       CommandId extended_features_id,
578       CommandId fixed_channels_supported_id,
579       l2cap::ExtendedFeatures features = 0u,
580       l2cap::FixedChannelsSupported channels = 0u) {
581     ReceiveAclDataPacket(testing::AclExtFeaturesInfoRsp(
582         extended_features_id, kTestHandle1, features));
583     ReceiveAclDataPacket(testing::AclFixedChannelsSupportedInfoRsp(
584         fixed_channels_supported_id, kTestHandle1, channels));
585   }
586 
ActivateNewFixedChannel(ChannelId id,hci_spec::ConnectionHandle conn_handle=kTestHandle1,Channel::ClosedCallback closed_cb=DoNothing,Channel::RxCallback rx_cb=NopRxCallback)587   Channel::WeakPtr ActivateNewFixedChannel(
588       ChannelId id,
589       hci_spec::ConnectionHandle conn_handle = kTestHandle1,
590       Channel::ClosedCallback closed_cb = DoNothing,
591       Channel::RxCallback rx_cb = NopRxCallback) {
592     auto chan = chanmgr()->OpenFixedChannel(conn_handle, id);
593     if (!chan.is_alive() ||
594         !chan->Activate(std::move(rx_cb), std::move(closed_cb))) {
595       return Channel::WeakPtr();
596     }
597 
598     return chan;
599   }
600 
601   // |activated_cb| will be called with opened and activated Channel if
602   // successful and nullptr otherwise.
ActivateOutboundChannel(Psm psm,ChannelParameters chan_params,ChannelCallback activated_cb,hci_spec::ConnectionHandle conn_handle=kTestHandle1,Channel::ClosedCallback closed_cb=DoNothing,Channel::RxCallback rx_cb=NopRxCallback)603   void ActivateOutboundChannel(
604       Psm psm,
605       ChannelParameters chan_params,
606       ChannelCallback activated_cb,
607       hci_spec::ConnectionHandle conn_handle = kTestHandle1,
608       Channel::ClosedCallback closed_cb = DoNothing,
609       Channel::RxCallback rx_cb = NopRxCallback) {
610     ChannelCallback open_cb = [activated_cb = std::move(activated_cb),
611                                rx_cb = std::move(rx_cb),
612                                closed_cb =
613                                    std::move(closed_cb)](auto chan) mutable {
614       if (!chan.is_alive() ||
615           !chan->Activate(std::move(rx_cb), std::move(closed_cb))) {
616         activated_cb(Channel::WeakPtr());
617       } else {
618         activated_cb(std::move(chan));
619       }
620     };
621     chanmgr()->OpenL2capChannel(
622         conn_handle, psm, chan_params, std::move(open_cb));
623   }
624 
SetUpOutboundChannelWithCallback(ChannelId local_id,ChannelId remote_id,Channel::ClosedCallback closed_cb,ChannelParameters channel_params,fit::function<void (Channel::WeakPtr)> channel_cb)625   void SetUpOutboundChannelWithCallback(
626       ChannelId local_id,
627       ChannelId remote_id,
628       Channel::ClosedCallback closed_cb,
629       ChannelParameters channel_params,
630       fit::function<void(Channel::WeakPtr)> channel_cb) {
631     const auto conn_req_id = NextCommandId();
632     const auto config_req_id = NextCommandId();
633     EXPECT_ACL_PACKET_OUT_(testing::AclConnectionReq(
634                                conn_req_id, kTestHandle1, local_id, kTestPsm),
635                            kHighPriority);
636     EXPECT_ACL_PACKET_OUT_(
637         testing::AclConfigReq(
638             config_req_id, kTestHandle1, remote_id, kChannelParams),
639         kHighPriority);
640     EXPECT_ACL_PACKET_OUT_(
641         testing::AclConfigRsp(
642             kPeerConfigRequestId, kTestHandle1, remote_id, kChannelParams),
643         kHighPriority);
644 
645     ActivateOutboundChannel(kTestPsm,
646                             channel_params,
647                             std::move(channel_cb),
648                             kTestHandle1,
649                             std::move(closed_cb));
650     RunUntilIdle();
651 
652     ReceiveAclDataPacket(testing::AclConnectionRsp(
653         conn_req_id, kTestHandle1, local_id, remote_id));
654     ReceiveAclDataPacket(testing::AclConfigReq(
655         kPeerConfigRequestId, kTestHandle1, local_id, kChannelParams));
656     ReceiveAclDataPacket(testing::AclConfigRsp(
657         config_req_id, kTestHandle1, local_id, kChannelParams));
658 
659     RunUntilIdle();
660     EXPECT_TRUE(AllExpectedPacketsSent());
661   }
662 
SetUpOutboundChannel(ChannelId local_id=kLocalId,ChannelId remote_id=kRemoteId,Channel::ClosedCallback closed_cb=DoNothing,ChannelParameters channel_params=kChannelParams)663   Channel::WeakPtr SetUpOutboundChannel(
664       ChannelId local_id = kLocalId,
665       ChannelId remote_id = kRemoteId,
666       Channel::ClosedCallback closed_cb = DoNothing,
667       ChannelParameters channel_params = kChannelParams) {
668     Channel::WeakPtr channel;
669     auto channel_cb = [&channel](l2cap::Channel::WeakPtr activated_chan) {
670       channel = std::move(activated_chan);
671     };
672 
673     SetUpOutboundChannelWithCallback(
674         local_id, remote_id, std::move(closed_cb), channel_params, channel_cb);
675     EXPECT_TRUE(channel.is_alive());
676     return channel;
677   }
678 
679   // Set an expectation for an outbound ACL data packet. Packets are expected in
680   // the order that they're added. The test fails if not all expected packets
681   // have been set when the test case completes or if the outbound data doesn't
682   // match expectations, including the ordering between LE and ACL packets.
ExpectOutboundPacket(bt::LinkType ll_type,hci::AclDataChannel::PacketPriority priority,const ByteBuffer & data,const char * file_name="",int line_number=0)683   void ExpectOutboundPacket(bt::LinkType ll_type,
684                             hci::AclDataChannel::PacketPriority priority,
685                             const ByteBuffer& data,
686                             const char* file_name = "",
687                             int line_number = 0) {
688     expected_packets_.push(
689         {file_name, line_number, DynamicByteBuffer(data), ll_type, priority});
690   }
691 
ActivateOutboundErtmChannel(ChannelCallback activated_cb,hci_spec::ConnectionHandle conn_handle=kTestHandle1,uint8_t max_outbound_transmit=3,Channel::ClosedCallback closed_cb=DoNothing,Channel::RxCallback rx_cb=NopRxCallback)692   void ActivateOutboundErtmChannel(
693       ChannelCallback activated_cb,
694       hci_spec::ConnectionHandle conn_handle = kTestHandle1,
695       uint8_t max_outbound_transmit = 3,
696       Channel::ClosedCallback closed_cb = DoNothing,
697       Channel::RxCallback rx_cb = NopRxCallback) {
698     l2cap::ChannelParameters chan_params;
699     auto config_mode =
700         l2cap::RetransmissionAndFlowControlMode::kEnhancedRetransmission;
701     chan_params.mode = config_mode;
702 
703     const auto conn_req_id = NextCommandId();
704     const auto config_req_id = NextCommandId();
705     EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id),
706                            kHighPriority);
707     EXPECT_ACL_PACKET_OUT_(
708         OutboundConfigurationRequest(
709             config_req_id, kMaxInboundPduPayloadSize, config_mode),
710         kHighPriority);
711     const auto kInboundMtu = kDefaultMTU;
712     EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId,
713                                                          kInboundMtu,
714                                                          config_mode,
715                                                          max_outbound_transmit),
716                            kHighPriority);
717 
718     ActivateOutboundChannel(kTestPsm,
719                             chan_params,
720                             std::move(activated_cb),
721                             conn_handle,
722                             std::move(closed_cb),
723                             std::move(rx_cb));
724 
725     ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
726     ReceiveAclDataPacket(InboundConfigurationRequest(
727         kPeerConfigRequestId, kInboundMtu, config_mode, max_outbound_transmit));
728     ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
729   }
730 
731   // Returns true if all expected outbound packets up to this call have been
732   // sent by the test case.
AllExpectedPacketsSent() const733   [[nodiscard]] bool AllExpectedPacketsSent() const {
734     return expected_packets_.empty();
735   }
736 
ReceiveAclDataPacket(const ByteBuffer & packet)737   void ReceiveAclDataPacket(const ByteBuffer& packet) {
738     const size_t payload_size = packet.size() - sizeof(hci_spec::ACLDataHeader);
739     BT_ASSERT(payload_size <= std::numeric_limits<uint16_t>::max());
740     hci::ACLDataPacketPtr acl_packet =
741         hci::ACLDataPacket::New(static_cast<uint16_t>(payload_size));
742     auto mutable_acl_packet_data = acl_packet->mutable_view()->mutable_data();
743     packet.Copy(&mutable_acl_packet_data);
744     packet_rx_handler_(std::move(acl_packet));
745   }
746 
chanmgr() const747   ChannelManager* chanmgr() const { return chanmgr_.get(); }
748 
acl_data_channel()749   hci::testing::MockAclDataChannel* acl_data_channel() {
750     return &acl_data_channel_;
751   }
752 
NextCommandId()753   CommandId NextCommandId() { return next_command_id_++; }
754 
755  private:
SendPackets(std::list<hci::ACLDataPacketPtr> packets)756   bool SendPackets(std::list<hci::ACLDataPacketPtr> packets) {
757     for (auto& packet : packets) {
758       const ByteBuffer& data = packet->view().data();
759       if (expected_packets_.empty()) {
760         ADD_FAILURE() << "Unexpected outbound ACL data";
761         std::cout << "{ ";
762         PrintByteContainer(data);
763         std::cout << " }\n";
764       } else {
765         const auto& expected = expected_packets_.front();
766         // Prints both data in case of mismatch.
767         if (!ContainersEqual(expected.data, data)) {
768           ADD_FAILURE_AT(expected.file_name, expected.line_number)
769               << "Outbound ACL data doesn't match expected";
770         }
771         expected_packets_.pop();
772       }
773     }
774     return !packets.empty();
775   }
776 
777   std::unique_ptr<ChannelManager> chanmgr_;
778   hci::ACLPacketHandler packet_rx_handler_;
779   hci::testing::MockAclDataChannel acl_data_channel_;
780 
781   std::queue<const PacketExpectation> expected_packets_;
782 
783   CommandId next_command_id_;
784 
785   BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(ChannelManagerMockAclChannelTest);
786 };
787 
788 // ChannelManager test fixture that uses a real AclDataChannel and uses
789 // MockController for HCI packet expectations
790 using ChannelManagerRealAclChannelTest =
791     FakeDispatcherChannelManagerMockControllerTest;
792 
TEST_F(ChannelManagerRealAclChannelTest,OpenFixedChannelErrorNoConn)793 TEST_F(ChannelManagerRealAclChannelTest, OpenFixedChannelErrorNoConn) {
794   // This should fail as the ChannelManager has no entry for |kTestHandle1|.
795   EXPECT_FALSE(ActivateNewFixedChannel(kATTChannelId).is_alive());
796 
797   QueueLEConnection(kTestHandle1,
798                     pw::bluetooth::emboss::ConnectionRole::CENTRAL);
799 
800   // This should fail as the ChannelManager has no entry for |kTestHandle2|.
801   EXPECT_FALSE(ActivateNewFixedChannel(kATTChannelId, kTestHandle2).is_alive());
802 }
803 
TEST_F(ChannelManagerRealAclChannelTest,OpenFixedChannelErrorDisallowedId)804 TEST_F(ChannelManagerRealAclChannelTest, OpenFixedChannelErrorDisallowedId) {
805   // LE-U link
806   QueueLEConnection(kTestHandle1,
807                     pw::bluetooth::emboss::ConnectionRole::CENTRAL);
808 
809   // ACL-U link
810   QueueAclConnection(kTestHandle2);
811   RunUntilIdle();
812   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
813 
814   // This should fail as kSMPChannelId is ACL-U only.
815   EXPECT_FALSE(ActivateNewFixedChannel(kSMPChannelId, kTestHandle1).is_alive());
816 
817   // This should fail as kATTChannelId is LE-U only.
818   EXPECT_FALSE(ActivateNewFixedChannel(kATTChannelId, kTestHandle2).is_alive());
819 }
820 
TEST_F(ChannelManagerRealAclChannelTest,DeactivateDynamicChannelInvalidatesChannelPointer)821 TEST_F(ChannelManagerRealAclChannelTest,
822        DeactivateDynamicChannelInvalidatesChannelPointer) {
823   QueueAclConnection(kTestHandle1);
824   RunUntilIdle();
825   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
826 
827   Channel::WeakPtr channel;
828   auto chan_cb = [&](l2cap::Channel::WeakPtr activated_chan) {
829     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
830     channel = std::move(activated_chan);
831   };
832   QueueOutboundL2capConnection(
833       kTestHandle1, kTestPsm, kLocalId, kRemoteId, std::move(chan_cb));
834 
835   RunUntilIdle();
836   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
837   EXPECT_TRUE(channel.is_alive());
838   ASSERT_TRUE(channel->Activate(NopRxCallback, DoNothing));
839 
840   EXPECT_ACL_PACKET_OUT(
841       test_device(),
842       l2cap::testing::AclDisconnectionReq(
843           NextCommandId(), kTestHandle1, kLocalId, kRemoteId));
844 
845   channel->Deactivate();
846   RunUntilIdle();
847   ASSERT_FALSE(channel.is_alive());
848 }
849 
TEST_F(ChannelManagerRealAclChannelTest,DeactivateAttChannelInvalidatesChannelPointer)850 TEST_F(ChannelManagerRealAclChannelTest,
851        DeactivateAttChannelInvalidatesChannelPointer) {
852   LEFixedChannels fixed_channels = QueueLEConnection(
853       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
854   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
855   fixed_channels.att->Deactivate();
856   ASSERT_FALSE(fixed_channels.att.is_alive());
857 }
858 
TEST_F(ChannelManagerRealAclChannelTest,OpenFixedChannelAndUnregisterLink)859 TEST_F(ChannelManagerRealAclChannelTest, OpenFixedChannelAndUnregisterLink) {
860   // LE-U link
861   LEFixedChannels fixed_channels = QueueLEConnection(
862       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
863 
864   bool closed_called = false;
865   auto closed_cb = [&closed_called] { closed_called = true; };
866 
867   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, closed_cb));
868   EXPECT_EQ(kTestHandle1, fixed_channels.att->link_handle());
869 
870   // This should notify the channel.
871   chanmgr()->RemoveConnection(kTestHandle1);
872 
873   RunUntilIdle();
874 
875   // |closed_cb| will be called synchronously since it was registered using the
876   // current thread's task runner.
877   EXPECT_TRUE(closed_called);
878 }
879 
TEST_F(ChannelManagerRealAclChannelTest,OpenFixedChannelAndCloseChannel)880 TEST_F(ChannelManagerRealAclChannelTest, OpenFixedChannelAndCloseChannel) {
881   // LE-U link
882   LEFixedChannels fixed_channels = QueueLEConnection(
883       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
884 
885   bool closed_called = false;
886   auto closed_cb = [&closed_called] { closed_called = true; };
887 
888   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, closed_cb));
889 
890   // Close the channel before unregistering the link. |closed_cb| should not get
891   // called.
892   fixed_channels.att->Deactivate();
893   chanmgr()->RemoveConnection(kTestHandle1);
894 
895   RunUntilIdle();
896 
897   EXPECT_FALSE(closed_called);
898 }
899 
TEST_F(ChannelManagerRealAclChannelTest,FixedChannelsUseBasicMode)900 TEST_F(ChannelManagerRealAclChannelTest, FixedChannelsUseBasicMode) {
901   LEFixedChannels fixed_channels = QueueLEConnection(
902       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
903   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
904   EXPECT_EQ(RetransmissionAndFlowControlMode::kBasic,
905             fixed_channels.att->mode());
906 }
907 
TEST_F(ChannelManagerRealAclChannelTest,OpenAndCloseWithLinkMultipleFixedChannels)908 TEST_F(ChannelManagerRealAclChannelTest,
909        OpenAndCloseWithLinkMultipleFixedChannels) {
910   // LE-U link
911   LEFixedChannels fixed_channels = QueueLEConnection(
912       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
913 
914   bool att_closed = false;
915   auto att_closed_cb = [&att_closed] { att_closed = true; };
916   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, att_closed_cb));
917 
918   bool smp_closed = false;
919   auto smp_closed_cb = [&smp_closed] { smp_closed = true; };
920   ASSERT_TRUE(fixed_channels.smp->Activate(NopRxCallback, smp_closed_cb));
921 
922   fixed_channels.smp->Deactivate();
923   chanmgr()->RemoveConnection(kTestHandle1);
924 
925   RunUntilIdle();
926 
927   EXPECT_TRUE(att_closed);
928   EXPECT_FALSE(smp_closed);
929 }
930 
TEST_F(ChannelManagerRealAclChannelTest,SendingPacketsBeforeRemoveConnectionAndVerifyChannelClosed)931 TEST_F(ChannelManagerRealAclChannelTest,
932        SendingPacketsBeforeRemoveConnectionAndVerifyChannelClosed) {
933   // LE-U link
934   LEFixedChannels fixed_channels = QueueLEConnection(
935       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
936 
937   bool closed_called = false;
938   auto closed_cb = [&closed_called] { closed_called = true; };
939   auto chan = fixed_channels.att;
940   ASSERT_TRUE(chan.is_alive());
941   ASSERT_TRUE(chan->Activate(NopRxCallback, closed_cb));
942 
943   EXPECT_ACL_PACKET_OUT(test_device(),
944                         StaticByteBuffer(
945                             // ACL data header (handle: 1, length: 6)
946                             0x01,
947                             0x00,
948                             0x06,
949                             0x00,
950                             // L2CAP B-frame (length: 2, channel-id: ATT)
951                             0x02,
952                             0x00,
953                             LowerBits(kATTChannelId),
954                             UpperBits(kATTChannelId),
955                             'h',
956                             'i'));
957 
958   EXPECT_TRUE(chan->Send(NewBuffer('h', 'i')));
959   RunUntilIdle();
960   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
961 
962   chanmgr()->RemoveConnection(kTestHandle1);
963 
964   // The L2CAP channel should have been notified of closure immediately.
965   EXPECT_TRUE(closed_called);
966   EXPECT_FALSE(chan.is_alive());
967   RunUntilIdle();
968 }
969 
970 // Tests that destroying the ChannelManager cleanly shuts down all channels.
TEST_F(ChannelManagerRealAclChannelTest,DestroyingChannelManagerCleansUpChannels)971 TEST_F(ChannelManagerRealAclChannelTest,
972        DestroyingChannelManagerCleansUpChannels) {
973   // LE-U link
974   LEFixedChannels fixed_channels = QueueLEConnection(
975       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
976 
977   bool closed_called = false;
978   auto closed_cb = [&closed_called] { closed_called = true; };
979   auto chan = fixed_channels.att;
980   ASSERT_TRUE(chan.is_alive());
981   ASSERT_TRUE(chan->Activate(NopRxCallback, closed_cb));
982 
983   EXPECT_ACL_PACKET_OUT(test_device(),
984                         StaticByteBuffer(
985                             // ACL data header (handle: 1, length: 6)
986                             0x01,
987                             0x00,
988                             0x06,
989                             0x00,
990                             // L2CAP B-frame (length: 2, channel-id: ATT)
991                             0x02,
992                             0x00,
993                             LowerBits(kATTChannelId),
994                             UpperBits(kATTChannelId),
995                             'h',
996                             'i'));
997 
998   // Send a packet. This should be processed immediately.
999   EXPECT_TRUE(chan->Send(NewBuffer('h', 'i')));
1000   RunUntilIdle();
1001   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1002 
1003   TearDown();
1004 
1005   EXPECT_TRUE(closed_called);
1006   EXPECT_FALSE(chan.is_alive());
1007   // No outbound packet expectations were set, so this test will fail if it
1008   // sends any data.
1009   RunUntilIdle();
1010 }
1011 
TEST_F(ChannelManagerRealAclChannelTest,DeactivateDoesNotCrashOrHang)1012 TEST_F(ChannelManagerRealAclChannelTest, DeactivateDoesNotCrashOrHang) {
1013   // Tests that the clean up task posted to the LogicalLink does not crash when
1014   // a dynamic registry is not present (which is the case for LE links).
1015   LEFixedChannels fixed_channels = QueueLEConnection(
1016       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1017   ASSERT_TRUE(fixed_channels.att.is_alive());
1018   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
1019   fixed_channels.att->Deactivate();
1020 
1021   // Loop until the clean up task runs.
1022   RunUntilIdle();
1023 }
1024 
TEST_F(ChannelManagerRealAclChannelTest,CallingDeactivateFromClosedCallbackDoesNotCrashOrHang)1025 TEST_F(ChannelManagerRealAclChannelTest,
1026        CallingDeactivateFromClosedCallbackDoesNotCrashOrHang) {
1027   BrEdrFixedChannels fixed_channels =
1028       QueueAclConnection(kTestHandle1).fixed_channels;
1029   RunUntilIdle();
1030   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1031 
1032   auto chan = std::move(fixed_channels.smp);
1033   chan->Activate(NopRxCallback, [chan] { chan->Deactivate(); });
1034   chanmgr()->RemoveConnection(kTestHandle1);  // Triggers ClosedCallback.
1035   RunUntilIdle();
1036 }
1037 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveData)1038 TEST_F(ChannelManagerMockAclChannelTest, ReceiveData) {
1039   // LE-U link
1040   LEFixedChannels fixed_channels =
1041       RegisterLE(kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1042   ASSERT_TRUE(fixed_channels.att.is_alive());
1043   ASSERT_TRUE(fixed_channels.smp.is_alive());
1044 
1045   // We use the ATT channel to control incoming packets and the SMP channel to
1046   // quit the message loop
1047   std::vector<std::string> sdus;
1048   auto att_rx_cb = [&sdus](ByteBufferPtr sdu) {
1049     BT_DEBUG_ASSERT(sdu);
1050     sdus.push_back(sdu->ToString());
1051   };
1052 
1053   bool smp_cb_called = false;
1054   auto smp_rx_cb = [&smp_cb_called](ByteBufferPtr sdu) {
1055     BT_DEBUG_ASSERT(sdu);
1056     EXPECT_EQ(0u, sdu->size());
1057     smp_cb_called = true;
1058   };
1059 
1060   ASSERT_TRUE(fixed_channels.att->Activate(att_rx_cb, DoNothing));
1061   ASSERT_TRUE(fixed_channels.smp->Activate(smp_rx_cb, DoNothing));
1062 
1063   // ATT channel
1064   ReceiveAclDataPacket(StaticByteBuffer(
1065       // ACL data header (starting fragment)
1066       0x01,
1067       0x00,
1068       0x09,
1069       0x00,
1070       // L2CAP B-frame
1071       0x05,
1072       0x00,
1073       0x04,
1074       0x00,
1075       'h',
1076       'e',
1077       'l',
1078       'l',
1079       'o'));
1080 
1081   ReceiveAclDataPacket(StaticByteBuffer(
1082       // ACL data header (starting fragment)
1083       0x01,
1084       0x00,
1085       0x09,
1086       0x00,
1087       // L2CAP B-frame (partial)
1088       0x0C,
1089       0x00,
1090       0x04,
1091       0x00,
1092       'h',
1093       'o',
1094       'w',
1095       ' ',
1096       'a'));
1097 
1098   ReceiveAclDataPacket(StaticByteBuffer(
1099       // ACL data header (continuing fragment)
1100       0x01,
1101       0x10,
1102       0x07,
1103       0x00,
1104       // L2CAP B-frame (partial)
1105       'r',
1106       'e',
1107       ' ',
1108       'y',
1109       'o',
1110       'u',
1111       '?'));
1112 
1113   // SMP channel
1114   ReceiveAclDataPacket(StaticByteBuffer(
1115       // ACL data header (starting fragment)
1116       0x01,
1117       0x00,
1118       0x04,
1119       0x00,
1120       // L2CAP B-frame (empty)
1121       0x00,
1122       0x00,
1123       0x06,
1124       0x00));
1125 
1126   RunUntilIdle();
1127 
1128   EXPECT_TRUE(smp_cb_called);
1129   ASSERT_EQ(2u, sdus.size());
1130   EXPECT_EQ("hello", sdus[0]);
1131   EXPECT_EQ("how are you?", sdus[1]);
1132 }
1133 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveDataBeforeRegisteringLink)1134 TEST_F(ChannelManagerMockAclChannelTest, ReceiveDataBeforeRegisteringLink) {
1135   constexpr size_t kPacketCount = 10;
1136 
1137   StaticByteBuffer<255> buffer;
1138 
1139   // We use the ATT channel to control incoming packets and the SMP channel to
1140   // quit the message loop
1141   size_t packet_count = 0;
1142   auto att_rx_cb = [&packet_count](ByteBufferPtr sdu) { packet_count++; };
1143 
1144   bool smp_cb_called = false;
1145   auto smp_rx_cb = [&smp_cb_called](ByteBufferPtr sdu) {
1146     BT_DEBUG_ASSERT(sdu);
1147     EXPECT_EQ(0u, sdu->size());
1148     smp_cb_called = true;
1149   };
1150 
1151   // ATT channel
1152   for (size_t i = 0u; i < kPacketCount; i++) {
1153     ReceiveAclDataPacket(StaticByteBuffer(
1154         // ACL data header (starting fragment)
1155         0x01,
1156         0x00,
1157         0x04,
1158         0x00,
1159         // L2CAP B-frame
1160         0x00,
1161         0x00,
1162         0x04,
1163         0x00));
1164   }
1165 
1166   // SMP channel
1167   ReceiveAclDataPacket(StaticByteBuffer(
1168       // ACL data header (starting fragment)
1169       0x01,
1170       0x00,
1171       0x04,
1172       0x00,
1173       // L2CAP B-frame (empty)
1174       0x00,
1175       0x00,
1176       0x06,
1177       0x00));
1178 
1179   Channel::WeakPtr att_chan, smp_chan;
1180 
1181   // Run the loop so all packets are received.
1182   RunUntilIdle();
1183 
1184   LEFixedChannels fixed_channels =
1185       RegisterLE(kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1186   ASSERT_TRUE(fixed_channels.att->Activate(att_rx_cb, DoNothing));
1187   ASSERT_TRUE(fixed_channels.smp->Activate(smp_rx_cb, DoNothing));
1188 
1189   RunUntilIdle();
1190   EXPECT_TRUE(smp_cb_called);
1191   EXPECT_EQ(kPacketCount, packet_count);
1192 }
1193 
1194 // Receive data after registering the link but before creating a fixed channel.
TEST_F(ChannelManagerRealAclChannelTest,ReceiveDataBeforeCreatingFixedChannel)1195 TEST_F(ChannelManagerRealAclChannelTest,
1196        ReceiveDataBeforeCreatingFixedChannel) {
1197   constexpr size_t kPacketCount = 10;
1198 
1199   // Register an ACL connection because LE connections create fixed channels
1200   // immediately.
1201   QueueAclConnection(kTestHandle1,
1202                      pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1203   RunUntilIdle();
1204 
1205   StaticByteBuffer<255> buffer;
1206 
1207   size_t packet_count = 0;
1208   auto rx_cb = [&packet_count](ByteBufferPtr sdu) { packet_count++; };
1209   for (size_t i = 0u; i < kPacketCount; i++) {
1210     test_device()->SendACLDataChannelPacket(StaticByteBuffer(
1211         // ACL data header (starting fragment)
1212         LowerBits(kTestHandle1),
1213         UpperBits(kTestHandle1),
1214         0x04,
1215         0x00,
1216         // L2CAP B-frame (empty)
1217         0x00,
1218         0x00,
1219         LowerBits(kConnectionlessChannelId),
1220         UpperBits(kConnectionlessChannelId)));
1221   }
1222   // Run the loop so all packets are received.
1223   RunUntilIdle();
1224 
1225   auto chan = ActivateNewFixedChannel(
1226       kConnectionlessChannelId, kTestHandle1, DoNothing, std::move(rx_cb));
1227 
1228   RunUntilIdle();
1229   EXPECT_EQ(kPacketCount, packet_count);
1230 }
1231 
1232 // Receive data after registering the link and creating the channel but before
1233 // setting the rx handler.
TEST_F(ChannelManagerRealAclChannelTest,ReceiveDataBeforeSettingRxHandler)1234 TEST_F(ChannelManagerRealAclChannelTest, ReceiveDataBeforeSettingRxHandler) {
1235   constexpr size_t kPacketCount = 10;
1236 
1237   LEFixedChannels fixed_channels = QueueLEConnection(
1238       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1239 
1240   StaticByteBuffer<255> buffer;
1241 
1242   // We use the ATT channel to control incoming packets and the SMP channel to
1243   // quit the message loop
1244   size_t packet_count = 0;
1245   auto att_rx_cb = [&packet_count](ByteBufferPtr sdu) { packet_count++; };
1246 
1247   bool smp_cb_called = false;
1248   auto smp_rx_cb = [&smp_cb_called](ByteBufferPtr sdu) {
1249     BT_DEBUG_ASSERT(sdu);
1250     EXPECT_EQ(0u, sdu->size());
1251     smp_cb_called = true;
1252   };
1253 
1254   // ATT channel
1255   for (size_t i = 0u; i < kPacketCount; i++) {
1256     test_device()->SendACLDataChannelPacket(StaticByteBuffer(
1257         // ACL data header (starting fragment)
1258         0x01,
1259         0x00,
1260         0x04,
1261         0x00,
1262         // L2CAP B-frame
1263         0x00,
1264         0x00,
1265         LowerBits(kATTChannelId),
1266         UpperBits(kATTChannelId)));
1267   }
1268 
1269   // SMP channel
1270   test_device()->SendACLDataChannelPacket(StaticByteBuffer(
1271       // ACL data header (starting fragment)
1272       0x01,
1273       0x00,
1274       0x04,
1275       0x00,
1276       // L2CAP B-frame (empty)
1277       0x00,
1278       0x00,
1279       LowerBits(kLESMPChannelId),
1280       UpperBits(kLESMPChannelId)));
1281 
1282   // Run the loop so all packets are received.
1283   RunUntilIdle();
1284 
1285   fixed_channels.att->Activate(att_rx_cb, DoNothing);
1286   fixed_channels.smp->Activate(smp_rx_cb, DoNothing);
1287 
1288   RunUntilIdle();
1289 
1290   EXPECT_TRUE(smp_cb_called);
1291   EXPECT_EQ(kPacketCount, packet_count);
1292 }
1293 
TEST_F(ChannelManagerMockAclChannelTest,ActivateChannelProcessesCallbacksSynchronously)1294 TEST_F(ChannelManagerMockAclChannelTest,
1295        ActivateChannelProcessesCallbacksSynchronously) {
1296   // LE-U link
1297   LEFixedChannels fixed_channels =
1298       RegisterLE(kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1299 
1300   int att_rx_cb_count = 0;
1301   int smp_rx_cb_count = 0;
1302 
1303   auto att_rx_cb = [&att_rx_cb_count](ByteBufferPtr sdu) {
1304     EXPECT_EQ("hello", sdu->AsString());
1305     att_rx_cb_count++;
1306   };
1307   bool att_closed_called = false;
1308   auto att_closed_cb = [&att_closed_called] { att_closed_called = true; };
1309 
1310   ASSERT_TRUE(fixed_channels.att->Activate(std::move(att_rx_cb),
1311                                            std::move(att_closed_cb)));
1312 
1313   auto smp_rx_cb = [&smp_rx_cb_count](ByteBufferPtr sdu) {
1314     EXPECT_EQ("��", sdu->AsString());
1315     smp_rx_cb_count++;
1316   };
1317   bool smp_closed_called = false;
1318   auto smp_closed_cb = [&smp_closed_called] { smp_closed_called = true; };
1319 
1320   ASSERT_TRUE(fixed_channels.smp->Activate(std::move(smp_rx_cb),
1321                                            std::move(smp_closed_cb)));
1322 
1323   ReceiveAclDataPacket(StaticByteBuffer(
1324       // ACL data header (starting fragment)
1325       0x01,
1326       0x00,
1327       0x08,
1328       0x00,
1329       // L2CAP B-frame for SMP fixed channel (4-byte payload: U+1F928 in UTF-8)
1330       0x04,
1331       0x00,
1332       0x06,
1333       0x00,
1334       0xf0,
1335       0x9f,
1336       0xa4,
1337       0xa8));
1338 
1339   ReceiveAclDataPacket(StaticByteBuffer(
1340       // ACL data header (starting fragment)
1341       0x01,
1342       0x00,
1343       0x09,
1344       0x00,
1345       // L2CAP B-frame for ATT fixed channel
1346       0x05,
1347       0x00,
1348       0x04,
1349       0x00,
1350       'h',
1351       'e',
1352       'l',
1353       'l',
1354       'o'));
1355 
1356   // Receiving data in ChannelManager processes the ATT and SMP packets
1357   // synchronously so it has already routed the data to the Channels.
1358   EXPECT_EQ(1, att_rx_cb_count);
1359   EXPECT_EQ(1, smp_rx_cb_count);
1360   RunUntilIdle();
1361   EXPECT_EQ(1, att_rx_cb_count);
1362   EXPECT_EQ(1, smp_rx_cb_count);
1363 
1364   // Link closure synchronously calls the ATT and SMP channel close callbacks.
1365   chanmgr()->RemoveConnection(kTestHandle1);
1366   EXPECT_TRUE(att_closed_called);
1367   EXPECT_TRUE(smp_closed_called);
1368 }
1369 
TEST_F(ChannelManagerRealAclChannelTest,RemovingLinkInvalidatesChannelPointer)1370 TEST_F(ChannelManagerRealAclChannelTest,
1371        RemovingLinkInvalidatesChannelPointer) {
1372   LEFixedChannels fixed_channels = QueueLEConnection(
1373       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1374   BT_ASSERT(fixed_channels.att->Activate(NopRxCallback, DoNothing));
1375   chanmgr()->RemoveConnection(kTestHandle1);
1376   EXPECT_FALSE(fixed_channels.att.is_alive());
1377 }
1378 
TEST_F(ChannelManagerRealAclChannelTest,SendBasicSDU)1379 TEST_F(ChannelManagerRealAclChannelTest, SendBasicSDU) {
1380   LEFixedChannels fixed_channels = QueueLEConnection(
1381       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1382   BT_ASSERT(fixed_channels.att->Activate(NopRxCallback, DoNothing));
1383 
1384   EXPECT_ACL_PACKET_OUT(test_device(),
1385                         StaticByteBuffer(
1386                             // ACL data header (handle: 1, length 7)
1387                             0x01,
1388                             0x00,
1389                             0x08,
1390                             0x00,
1391                             // L2CAP B-frame: (length: 3, channel-id: 4)
1392                             0x04,
1393                             0x00,
1394                             0x04,
1395                             0x00,
1396                             'T',
1397                             'e',
1398                             's',
1399                             't'));
1400 
1401   EXPECT_TRUE(fixed_channels.att->Send(NewBuffer('T', 'e', 's', 't')));
1402   RunUntilIdle();
1403 }
1404 
1405 // Tests that fragmentation of BR/EDR packets uses the BR/EDR buffer size
TEST_F(ChannelManagerRealAclChannelTest,SendBREDRFragmentedSDUs)1406 TEST_F(ChannelManagerRealAclChannelTest, SendBREDRFragmentedSDUs) {
1407   // Customize setup so that ACL payload size is 6 instead of default 1024
1408   TearDown();
1409   SetUp(/*max_acl_payload_size=*/6, /*max_le_payload_size=*/0);
1410 
1411   // Send fragmented Extended Features Information Request
1412   EXPECT_ACL_PACKET_OUT(test_device(),
1413                         StaticByteBuffer(
1414                             // ACL data header (handle: 1, length: 6)
1415                             0x01,
1416                             0x00,
1417                             0x06,
1418                             0x00,
1419                             // L2CAP B-frame (length: 6, channel-id: 1)
1420                             0x06,
1421                             0x00,
1422                             0x01,
1423                             0x00,
1424                             // Extended Features Information Request
1425                             // (code = 0x0A, ID)
1426                             0x0A,
1427                             NextCommandId()));
1428   EXPECT_ACL_PACKET_OUT(
1429       test_device(),
1430       StaticByteBuffer(
1431           // ACL data header (handle: 1, pbf: continuing fr., length: 4)
1432           0x01,
1433           0x10,
1434           0x04,
1435           0x00,
1436           // Extended Features Information Request cont. (Length: 2, type)
1437           0x02,
1438           0x00,
1439           LowerBits(static_cast<uint16_t>(
1440               InformationType::kExtendedFeaturesSupported)),
1441           UpperBits(static_cast<uint16_t>(
1442               InformationType::kExtendedFeaturesSupported))));
1443 
1444   // Send fragmented Fixed Channels Supported Information Request
1445   EXPECT_ACL_PACKET_OUT(test_device(),
1446                         StaticByteBuffer(
1447                             // ACL data header (handle: 1, length: 6)
1448                             0x01,
1449                             0x00,
1450                             0x06,
1451                             0x00,
1452                             // L2CAP B-frame (length: 6, channel-id: 1)
1453                             0x06,
1454                             0x00,
1455                             0x01,
1456                             0x00,
1457                             // Fixed Channels Supported Information Request
1458                             // (command code, command ID)
1459                             l2cap::kInformationRequest,
1460                             NextCommandId()));
1461   EXPECT_ACL_PACKET_OUT(
1462       test_device(),
1463       StaticByteBuffer(
1464           // ACL data header (handle: 1, pbf: continuing fr., length: 4)
1465           0x01,
1466           0x10,
1467           0x04,
1468           0x00,
1469           // Fixed Channels Supported Information Request cont.
1470           // (length: 2, type)
1471           0x02,
1472           0x00,
1473           LowerBits(
1474               static_cast<uint16_t>(InformationType::kFixedChannelsSupported)),
1475           UpperBits(static_cast<uint16_t>(
1476               InformationType::kFixedChannelsSupported))));
1477 
1478   BrEdrFixedChannels fixed_channels = chanmgr()->AddACLConnection(
1479       kTestHandle1,
1480       pw::bluetooth::emboss::ConnectionRole::CENTRAL,
1481       /*link_error_callback=*/[]() {},
1482       /*security_callback=*/[](auto, auto, auto) {});
1483   Channel::WeakPtr sm_chan = std::move(fixed_channels.smp);
1484   sm_chan->Activate(NopRxCallback, DoNothing);
1485   ASSERT_TRUE(sm_chan.is_alive());
1486 
1487   EXPECT_ACL_PACKET_OUT(
1488       test_device(),
1489       StaticByteBuffer(
1490           // ACL data header (handle: 1, length: 6)
1491           0x01,
1492           0x00,
1493           0x06,
1494           0x00,
1495           // L2CAP B-frame: (length: 7, channel-id: 7 (SMP), partial payload)
1496           0x07,
1497           0x00,
1498           LowerBits(kSMPChannelId),
1499           UpperBits(kSMPChannelId),
1500           'G',
1501           'o'));
1502 
1503   EXPECT_ACL_PACKET_OUT(
1504       test_device(),
1505       StaticByteBuffer(
1506           // ACL data header (handle: 1, pbf: continuing fr., length: 5)
1507           0x01,
1508           0x10,
1509           0x05,
1510           0x00,
1511           // continuing payload
1512           'o',
1513           'd',
1514           'b',
1515           'y',
1516           'e'));
1517 
1518   // SDU of length 7 corresponds to a 11-octet B-frame
1519   // Due to the BR/EDR buffer size, this should be sent over a 6-byte then a
1520   // 5-byte fragment.
1521   EXPECT_TRUE(sm_chan->Send(NewBuffer('G', 'o', 'o', 'd', 'b', 'y', 'e')));
1522 
1523   RunUntilIdle();
1524 }
1525 
TEST_F(ChannelManagerRealAclChannelTest,SendBREDRFragmentedSDUsOverTwoDynamicChannels)1526 TEST_F(ChannelManagerRealAclChannelTest,
1527        SendBREDRFragmentedSDUsOverTwoDynamicChannels) {
1528   // Customize setup so that ACL payload size is 18 instead of default 1024
1529   TearDown();
1530   SetUp(/*max_acl_payload_size=*/18, /*max_le_payload_size=*/0);
1531 
1532   constexpr l2cap::Psm kPsm0 = l2cap::kAVCTP;
1533   constexpr l2cap::ChannelId kLocalId0 = 0x0040;
1534   constexpr l2cap::ChannelId kRemoteId0 = 0x9042;
1535 
1536   constexpr l2cap::Psm kPsm1 = l2cap::kAVDTP;
1537   constexpr l2cap::ChannelId kLocalId1 = 0x0041;
1538   constexpr l2cap::ChannelId kRemoteId1 = 0x9043;
1539 
1540   // L2CAP connection request/response, config request, config response
1541   constexpr size_t kChannelCreationPacketCount = 3;
1542 
1543   QueueAclConnection(kTestHandle1);
1544   RunUntilIdle();
1545   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1546 
1547   l2cap::Channel::WeakPtr channel0;
1548   auto chan_cb0 = [&](auto activated_chan) {
1549     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
1550     channel0 = std::move(activated_chan);
1551   };
1552   QueueOutboundL2capConnection(
1553       kTestHandle1, kPsm0, kLocalId0, kRemoteId0, std::move(chan_cb0));
1554 
1555   RunUntilIdle();
1556   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1557   ASSERT_TRUE(channel0.is_alive());
1558   ASSERT_TRUE(channel0->Activate(NopRxCallback, DoNothing));
1559 
1560   l2cap::Channel::WeakPtr channel1;
1561   auto chan_cb1 = [&](auto activated_chan) {
1562     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
1563     channel1 = std::move(activated_chan);
1564   };
1565   QueueOutboundL2capConnection(
1566       kTestHandle1, kPsm1, kLocalId1, kRemoteId1, std::move(chan_cb1));
1567 
1568   // Free up the buffer space from packets sent while creating |channel0|
1569   test_device()->SendCommandChannelPacket(NumberOfCompletedPacketsPacket(
1570       kTestHandle1, kChannelCreationPacketCount));
1571   RunUntilIdle();
1572 
1573   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1574   EXPECT_TRUE(channel1.is_alive());
1575   ASSERT_TRUE(channel1->Activate(NopRxCallback, DoNothing));
1576 
1577   // Free up the buffer space from packets sent while creating |channel1|
1578   test_device()->SendCommandChannelPacket(NumberOfCompletedPacketsPacket(
1579       kTestHandle1,
1580       kConnectionCreationPacketCount + kChannelCreationPacketCount));
1581   RunUntilIdle();
1582 
1583   // Queue size should be equal to or larger than |num_queued_packets| to ensure
1584   // that all packets get queued and sent
1585   uint16_t num_queued_packets = 3;
1586   EXPECT_TRUE(num_queued_packets <= kDefaultTxMaxQueuedCount);
1587 
1588   // Queue 14 packets in total, distributed between the two channels
1589   // Fill up BR/EDR controller buffer then queue 3 additional packets (which
1590   // will be later fragmented to form 6 packets)
1591   for (size_t i = 0; i < kBufferMaxNumPackets / 2 + num_queued_packets; i++) {
1592     Channel::WeakPtr channel = (i % 2) ? channel1 : channel0;
1593     ChannelId channel_id = (i % 2) ? kRemoteId1 : kRemoteId0;
1594 
1595     const StaticByteBuffer kPacket0(
1596         // ACL data header (handle: 1, length: 18)
1597         0x01,
1598         0x00,
1599         0x12,
1600         0x00,
1601         // L2CAP B-frame: (length: 14, channel-id, partial payload)
1602         0x14,
1603         0x00,
1604         LowerBits(channel_id),
1605         UpperBits(channel_id),
1606         'G',
1607         'o',
1608         'o',
1609         'o',
1610         'o',
1611         'o',
1612         'o',
1613         'o',
1614         'o',
1615         'o',
1616         'o',
1617         'o',
1618         'o',
1619         'o');
1620     EXPECT_ACL_PACKET_OUT(test_device(), kPacket0);
1621 
1622     const StaticByteBuffer kPacket1(
1623         // ACL data header (handle: 1, pbf: continuing fr., length: 6)
1624         0x01,
1625         0x10,
1626         0x06,
1627         0x00,
1628         // continuing payload
1629         'o',
1630         'o',
1631         'd',
1632         'b',
1633         'y',
1634         'e');
1635     EXPECT_ACL_PACKET_OUT(test_device(), kPacket1);
1636 
1637     // SDU of length 20 corresponds to a 24-octet B-frame
1638     // Due to the BR/EDR buffer size, this should be sent over a 18-byte then a
1639     // 6-byte fragment.
1640     EXPECT_TRUE(channel->Send(NewBuffer('G',
1641                                         'o',
1642                                         'o',
1643                                         'o',
1644                                         'o',
1645                                         'o',
1646                                         'o',
1647                                         'o',
1648                                         'o',
1649                                         'o',
1650                                         'o',
1651                                         'o',
1652                                         'o',
1653                                         'o',
1654                                         'o',
1655                                         'o',
1656                                         'd',
1657                                         'b',
1658                                         'y',
1659                                         'e')));
1660     RunUntilIdle();
1661   }
1662   EXPECT_FALSE(test_device()->AllExpectedDataPacketsSent());
1663 
1664   // Notify the processed packets with a Number Of Completed Packet HCI event
1665   // This should cause the remaining 6 fragmented packets to be sent
1666   test_device()->SendCommandChannelPacket(
1667       NumberOfCompletedPacketsPacket(kTestHandle1, 6));
1668   RunUntilIdle();
1669   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1670 }
1671 
1672 // Tests that fragmentation of LE packets uses the LE buffer size
TEST_F(ChannelManagerRealAclChannelTest,SendLEFragmentedSDUs)1673 TEST_F(ChannelManagerRealAclChannelTest, SendLEFragmentedSDUs) {
1674   TearDown();
1675   SetUp(/*max_acl_payload_size=*/6, /*max_le_payload_size=*/5);
1676 
1677   LEFixedChannels fixed_channels = QueueLEConnection(
1678       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1679   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
1680 
1681   EXPECT_ACL_PACKET_OUT(
1682       test_device(),
1683       StaticByteBuffer(
1684           // ACL data header (handle: 1, length: 5)
1685           0x01,
1686           0x00,
1687           0x05,
1688           0x00,
1689           // L2CAP B-frame: (length: 5, channel-id: 4, partial payload)
1690           0x05,
1691           0x00,
1692           0x04,
1693           0x00,
1694           'H'));
1695 
1696   EXPECT_ACL_PACKET_OUT(
1697       test_device(),
1698       StaticByteBuffer(
1699           // ACL data header (handle: 1, pbf: continuing fr., length: 4)
1700           0x01,
1701           0x10,
1702           0x04,
1703           0x00,
1704           // Continuing payload
1705           'e',
1706           'l',
1707           'l',
1708           'o'));
1709 
1710   // SDU of length 5 corresponds to a 9-octet B-frame which should be sent over
1711   // a 5-byte and a 4-byte fragment.
1712   EXPECT_TRUE(fixed_channels.att->Send(NewBuffer('H', 'e', 'l', 'l', 'o')));
1713 
1714   RunUntilIdle();
1715 }
1716 
TEST_F(ChannelManagerMockAclChannelTest,ACLChannelSignalLinkError)1717 TEST_F(ChannelManagerMockAclChannelTest, ACLChannelSignalLinkError) {
1718   bool link_error = false;
1719   auto link_error_cb = [&link_error] { link_error = true; };
1720   QueueRegisterACLRetVal acl =
1721       QueueRegisterACL(kTestHandle1,
1722                        pw::bluetooth::emboss::ConnectionRole::CENTRAL,
1723                        link_error_cb);
1724   acl.fixed_channels.smp->Activate(NopRxCallback, DoNothing);
1725   acl.fixed_channels.smp->SignalLinkError();
1726   RunUntilIdle();
1727   EXPECT_TRUE(link_error);
1728 }
1729 
TEST_F(ChannelManagerMockAclChannelTest,LEChannelSignalLinkError)1730 TEST_F(ChannelManagerMockAclChannelTest, LEChannelSignalLinkError) {
1731   bool link_error = false;
1732   auto link_error_cb = [&link_error] { link_error = true; };
1733   LEFixedChannels fixed_channels =
1734       RegisterLE(kTestHandle1,
1735                  pw::bluetooth::emboss::ConnectionRole::CENTRAL,
1736                  link_error_cb);
1737 
1738   // Activate a new Attribute channel to signal the error.
1739   fixed_channels.att->Activate(NopRxCallback, DoNothing);
1740   fixed_channels.att->SignalLinkError();
1741 
1742   RunUntilIdle();
1743 
1744   EXPECT_TRUE(link_error);
1745 }
1746 
TEST_F(ChannelManagerMockAclChannelTest,SignalLinkErrorDisconnectsChannels)1747 TEST_F(ChannelManagerMockAclChannelTest, SignalLinkErrorDisconnectsChannels) {
1748   bool link_error = false;
1749   auto link_error_cb = [this, &link_error] {
1750     // This callback is run after the expectation for
1751     // OutboundDisconnectionRequest is set, so this tests that L2CAP-level
1752     // teardown happens before ChannelManager requests a link teardown.
1753     ASSERT_TRUE(AllExpectedPacketsSent());
1754     link_error = true;
1755 
1756     // Simulate closing the link.
1757     chanmgr()->RemoveConnection(kTestHandle1);
1758   };
1759   QueueRegisterACLRetVal acl =
1760       QueueRegisterACL(kTestHandle1,
1761                        pw::bluetooth::emboss::ConnectionRole::CENTRAL,
1762                        link_error_cb);
1763 
1764   const auto conn_req_id = NextCommandId();
1765   const auto config_req_id = NextCommandId();
1766   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
1767   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
1768                          kHighPriority);
1769   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
1770                          kHighPriority);
1771 
1772   Channel::WeakPtr dynamic_channel;
1773   auto channel_cb = [&dynamic_channel](l2cap::Channel::WeakPtr activated_chan) {
1774     dynamic_channel = std::move(activated_chan);
1775   };
1776 
1777   int dynamic_channel_closed = 0;
1778   ActivateOutboundChannel(
1779       kTestPsm,
1780       kChannelParams,
1781       std::move(channel_cb),
1782       kTestHandle1,
1783       /*closed_cb=*/[&dynamic_channel_closed] { dynamic_channel_closed++; });
1784 
1785   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
1786   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
1787   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
1788 
1789   RETURN_IF_FATAL(RunUntilIdle());
1790   EXPECT_TRUE(AllExpectedPacketsSent());
1791 
1792   // The channel on kTestHandle1 should be open.
1793   EXPECT_TRUE(dynamic_channel.is_alive());
1794   EXPECT_EQ(0, dynamic_channel_closed);
1795 
1796   EXPECT_TRUE(AllExpectedPacketsSent());
1797   const auto disconn_req_id = NextCommandId();
1798   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(disconn_req_id),
1799                          kHighPriority);
1800 
1801   // Activate a new Security Manager channel to signal the error on
1802   // kTestHandle1.
1803   int fixed_channel_closed = 0;
1804   acl.fixed_channels.smp->Activate(
1805       NopRxCallback,
1806       /*closed_callback=*/[&fixed_channel_closed] { fixed_channel_closed++; });
1807   ASSERT_FALSE(link_error);
1808   acl.fixed_channels.smp->SignalLinkError();
1809 
1810   RETURN_IF_FATAL(RunUntilIdle());
1811 
1812   // link_error_cb is not called until Disconnection Response is received for
1813   // each dynamic channel
1814   EXPECT_FALSE(link_error);
1815 
1816   // But channels should be deactivated to prevent any activity.
1817   EXPECT_EQ(1, fixed_channel_closed);
1818   EXPECT_EQ(1, dynamic_channel_closed);
1819 
1820   ASSERT_TRUE(AllExpectedPacketsSent());
1821   const auto disconnection_rsp = testing::AclDisconnectionRsp(
1822       disconn_req_id, kTestHandle1, kLocalId, kRemoteId);
1823   ReceiveAclDataPacket(disconnection_rsp);
1824 
1825   RETURN_IF_FATAL(RunUntilIdle());
1826 
1827   EXPECT_TRUE(link_error);
1828 }
1829 
TEST_F(ChannelManagerRealAclChannelTest,LEConnectionParameterUpdateRequest)1830 TEST_F(ChannelManagerRealAclChannelTest, LEConnectionParameterUpdateRequest) {
1831   EXPECT_ACL_PACKET_OUT(
1832       test_device(),
1833       StaticByteBuffer(
1834           // ACL data header (handle: 0x0001, length: 10 bytes)
1835           0x01,
1836           0x00,
1837           0x0a,
1838           0x00,
1839           // L2CAP B-frame header (length: 6 bytes, channel-id: 0x0005 (LEsig))
1840           0x06,
1841           0x00,
1842           0x05,
1843           0x00,
1844           // L2CAP C-frame header
1845           // (LE conn. param. update response, id: 1, length: 2 bytes)
1846           0x13,
1847           0x01,
1848           0x02,
1849           0x00,
1850           // res: accepted
1851           0x00,
1852           0x00));
1853 
1854   LEFixedChannels fixed_channels = QueueLEConnection(
1855       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1856   ASSERT_TRUE(fixed_channels.att.is_alive());
1857   ASSERT_TRUE(fixed_channels.smp.is_alive());
1858 
1859   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
1860   ASSERT_TRUE(fixed_channels.smp->Activate(NopRxCallback, DoNothing));
1861 
1862   // clang-format off
1863   test_device()->SendACLDataChannelPacket(StaticByteBuffer(
1864       // ACL data header (handle: 0x0001, length: 16 bytes)
1865       0x01, 0x00, 0x10, 0x00,
1866       // L2CAP B-frame header (length: 12 bytes, channel-id: 0x0005 (LE sig))
1867       0x0C, 0x00, 0x05, 0x00,
1868       // L2CAP C-frame header (LE conn. param. update request, id: 1, length: 8 bytes)
1869       0x12, 0x01, 0x08, 0x00,
1870       // Connection parameters (hardcoded to match the expectations in |conn_param_cb|).
1871       0x06, 0x00,
1872       0x80, 0x0C,
1873       0xF3, 0x01,
1874       0x80, 0x0C));
1875   // clang-format on
1876 
1877   RunUntilIdle();
1878 }
1879 
TEST_F(ChannelManagerMockAclChannelTest,ACLOutboundDynamicChannelLocalDisconnect)1880 TEST_F(ChannelManagerMockAclChannelTest,
1881        ACLOutboundDynamicChannelLocalDisconnect) {
1882   QueueRegisterACL(kTestHandle1,
1883                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1884   RunUntilIdle();
1885 
1886   Channel::WeakPtr channel;
1887   auto channel_cb = [&channel](l2cap::Channel::WeakPtr activated_chan) {
1888     channel = std::move(activated_chan);
1889   };
1890 
1891   bool closed_cb_called = false;
1892   auto closed_cb = [&closed_cb_called] { closed_cb_called = true; };
1893 
1894   const auto conn_req_id = NextCommandId();
1895   const auto config_req_id = NextCommandId();
1896   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
1897   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
1898                          kHighPriority);
1899   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
1900                          kHighPriority);
1901 
1902   ActivateOutboundChannel(kTestPsm,
1903                           kChannelParams,
1904                           std::move(channel_cb),
1905                           kTestHandle1,
1906                           std::move(closed_cb));
1907   RunUntilIdle();
1908 
1909   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
1910   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
1911   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
1912 
1913   RunUntilIdle();
1914 
1915   EXPECT_TRUE(AllExpectedPacketsSent());
1916   ASSERT_TRUE(channel.is_alive());
1917   EXPECT_FALSE(closed_cb_called);
1918   EXPECT_EQ(kLocalId, channel->id());
1919   EXPECT_EQ(kRemoteId, channel->remote_id());
1920   EXPECT_EQ(RetransmissionAndFlowControlMode::kBasic, channel->mode());
1921 
1922   // Test SDU transmission.
1923   // SDU must have remote channel ID (unlike for fixed channels).
1924   EXPECT_ACL_PACKET_OUT_(StaticByteBuffer(
1925                              // ACL data header (handle: 1, length 8)
1926                              0x01,
1927                              0x00,
1928                              0x08,
1929                              0x00,
1930                              // L2CAP B-frame: (length: 4, channel-id)
1931                              0x04,
1932                              0x00,
1933                              LowerBits(kRemoteId),
1934                              UpperBits(kRemoteId),
1935                              'T',
1936                              'e',
1937                              's',
1938                              't'),
1939                          kLowPriority);
1940 
1941   EXPECT_TRUE(channel->Send(NewBuffer('T', 'e', 's', 't')));
1942 
1943   RunUntilIdle();
1944   EXPECT_TRUE(AllExpectedPacketsSent());
1945 
1946   const auto disconn_req_id = NextCommandId();
1947   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(disconn_req_id),
1948                          kHighPriority);
1949 
1950   // Explicit deactivation should not res in |closed_cb| being called.
1951   channel->Deactivate();
1952 
1953   RunUntilIdle();
1954   EXPECT_TRUE(AllExpectedPacketsSent());
1955 
1956   // Ensure callback is not called after the channel has disconnected
1957   acl_data_channel()->set_drop_queued_packets_cb(nullptr);
1958 
1959   // clang-format off
1960   ReceiveAclDataPacket(StaticByteBuffer(
1961       // ACL data header (handle: 0x0001, length: 12 bytes)
1962       0x01, 0x00, 0x0c, 0x00,
1963       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
1964       0x08, 0x00, 0x01, 0x00,
1965       // Disconnection Response
1966       // (ID, length: 4, dst cid, src cid)
1967       0x07, disconn_req_id, 0x04, 0x00,
1968       LowerBits(kRemoteId), UpperBits(kRemoteId), LowerBits(kLocalId), UpperBits(kLocalId)));
1969   // clang-format on
1970 
1971   RunUntilIdle();
1972 
1973   EXPECT_FALSE(closed_cb_called);
1974 }
1975 
TEST_F(ChannelManagerRealAclChannelTest,ACLOutboundDynamicChannelRemoteDisconnect)1976 TEST_F(ChannelManagerRealAclChannelTest,
1977        ACLOutboundDynamicChannelRemoteDisconnect) {
1978   QueueAclConnection(kTestHandle1,
1979                      pw::bluetooth::emboss::ConnectionRole::CENTRAL);
1980   RunUntilIdle();
1981   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1982 
1983   Channel::WeakPtr channel;
1984   auto chan_cb = [&](l2cap::Channel::WeakPtr activated_chan) {
1985     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
1986     channel = std::move(activated_chan);
1987   };
1988   QueueOutboundL2capConnection(
1989       kTestHandle1, kTestPsm, kLocalId, kRemoteId, std::move(chan_cb));
1990 
1991   RunUntilIdle();
1992   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
1993   EXPECT_TRUE(channel.is_alive());
1994   bool dynamic_channel_closed = false;
1995   ASSERT_TRUE(channel->Activate(NopRxCallback,
1996                                 /*closed_callback=*/[&dynamic_channel_closed] {
1997                                   dynamic_channel_closed = true;
1998                                 }));
1999   EXPECT_FALSE(dynamic_channel_closed);
2000   EXPECT_EQ(kLocalId, channel->id());
2001   EXPECT_EQ(kRemoteId, channel->remote_id());
2002   EXPECT_EQ(RetransmissionAndFlowControlMode::kBasic, channel->mode());
2003 
2004   // Test SDU reception.
2005   test_device()->SendACLDataChannelPacket(StaticByteBuffer(
2006       // ACL data header (handle: 1, length 8)
2007       0x01,
2008       0x00,
2009       0x08,
2010       0x00,
2011       // L2CAP B-frame: (length: 4, channel-id)
2012       0x04,
2013       0x00,
2014       LowerBits(kLocalId),
2015       UpperBits(kLocalId),
2016       'T',
2017       'e',
2018       's',
2019       't'));
2020 
2021   RunUntilIdle();
2022 
2023   EXPECT_ACL_PACKET_OUT(test_device(), OutboundDisconnectionResponse(7));
2024 
2025   // clang-format off
2026   test_device()->SendACLDataChannelPacket(StaticByteBuffer(
2027       // ACL data header (handle: 0x0001, length: 12 bytes)
2028       0x01, 0x00, 0x0c, 0x00,
2029       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
2030       0x08, 0x00, 0x01, 0x00,
2031       // Disconnection Request (ID: 7, length: 4, dst cid, src cid)
2032       0x06, 0x07, 0x04, 0x00,
2033       LowerBits(kLocalId), UpperBits(kLocalId), LowerBits(kRemoteId), UpperBits(kRemoteId)));
2034   // clang-format on
2035 
2036   // The preceding peer disconnection should have immediately destroyed the
2037   // route to the channel. L2CAP will process it and this following SDU
2038   // back-to-back. The latter should be dropped.
2039   test_device()->SendACLDataChannelPacket(StaticByteBuffer(
2040       // ACL data header (handle: 1, length 5)
2041       0x01,
2042       0x00,
2043       0x05,
2044       0x00,
2045       // L2CAP B-frame: (length: 1, channel-id: 0x0040)
2046       0x01,
2047       0x00,
2048       0x40,
2049       0x00,
2050       '!'));
2051 
2052   RunUntilIdle();
2053 
2054   EXPECT_TRUE(dynamic_channel_closed);
2055 }
2056 
TEST_F(ChannelManagerMockAclChannelTest,ACLOutboundDynamicChannelDataNotBuffered)2057 TEST_F(ChannelManagerMockAclChannelTest,
2058        ACLOutboundDynamicChannelDataNotBuffered) {
2059   QueueRegisterACL(kTestHandle1,
2060                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2061 
2062   Channel::WeakPtr channel;
2063   auto channel_cb = [&channel](l2cap::Channel::WeakPtr activated_chan) {
2064     channel = std::move(activated_chan);
2065   };
2066 
2067   bool channel_closed = false;
2068   auto closed_cb = [&channel_closed] { channel_closed = true; };
2069 
2070   auto data_rx_cb = [](ByteBufferPtr sdu) {
2071     FAIL() << "Unexpected data reception";
2072   };
2073 
2074   // Receive SDU for the channel about to be opened. It should be ignored.
2075   ReceiveAclDataPacket(StaticByteBuffer(
2076       // ACL data header (handle: 1, length 8)
2077       0x01,
2078       0x00,
2079       0x08,
2080       0x00,
2081       // L2CAP B-frame: (length: 4, channel-id)
2082       0x04,
2083       0x00,
2084       LowerBits(kLocalId),
2085       UpperBits(kLocalId),
2086       'T',
2087       'e',
2088       's',
2089       't'));
2090 
2091   const auto conn_req_id = NextCommandId();
2092   const auto config_req_id = NextCommandId();
2093   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
2094   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
2095                          kHighPriority);
2096   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
2097                          kHighPriority);
2098 
2099   ActivateOutboundChannel(kTestPsm,
2100                           kChannelParams,
2101                           std::move(channel_cb),
2102                           kTestHandle1,
2103                           std::move(closed_cb),
2104                           std::move(data_rx_cb));
2105   RunUntilIdle();
2106 
2107   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
2108 
2109   // The channel is connected but not configured, so no data should flow on the
2110   // channel. Test that this received data is also ignored.
2111   // clang-format off
2112   ReceiveAclDataPacket(StaticByteBuffer(
2113       // ACL data header (handle: 1, length 8)
2114       0x01, 0x00, 0x08, 0x00,
2115       // L2CAP B-frame: (length: 4, channel-id)
2116       0x04, 0x00, LowerBits(kLocalId), UpperBits(kLocalId), 'T', 'e', 's', 't'));
2117   // clang-format on
2118 
2119   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
2120   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
2121 
2122   RunUntilIdle();
2123 
2124   EXPECT_TRUE(AllExpectedPacketsSent());
2125   EXPECT_TRUE(channel.is_alive());
2126   EXPECT_FALSE(channel_closed);
2127 
2128   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionResponse(7), kHighPriority);
2129 
2130   // clang-format off
2131   ReceiveAclDataPacket(StaticByteBuffer(
2132       // ACL data header (handle: 0x0001, length: 12 bytes)
2133       0x01, 0x00, 0x0c, 0x00,
2134       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
2135       0x08, 0x00, 0x01, 0x00,
2136       // Disconnection Request
2137       // (ID: 7, length: 4, dst cid, src cid)
2138       0x06, 0x07, 0x04, 0x00,
2139       LowerBits(kLocalId), UpperBits(kLocalId), LowerBits(kRemoteId), UpperBits(kRemoteId)));
2140   // clang-format on
2141 
2142   RunUntilIdle();
2143 }
2144 
TEST_F(ChannelManagerMockAclChannelTest,ACLOutboundDynamicChannelRemoteRefused)2145 TEST_F(ChannelManagerMockAclChannelTest,
2146        ACLOutboundDynamicChannelRemoteRefused) {
2147   QueueRegisterACL(kTestHandle1,
2148                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2149 
2150   bool channel_cb_called = false;
2151   auto channel_cb = [&channel_cb_called](l2cap::Channel::WeakPtr channel) {
2152     channel_cb_called = true;
2153     EXPECT_FALSE(channel.is_alive());
2154   };
2155 
2156   const CommandId conn_req_id = NextCommandId();
2157   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
2158 
2159   ActivateOutboundChannel(kTestPsm, kChannelParams, std::move(channel_cb));
2160 
2161   // clang-format off
2162   ReceiveAclDataPacket(StaticByteBuffer(
2163       // ACL data header (handle: 0x0001, length: 16 bytes)
2164       0x01, 0x00, 0x10, 0x00,
2165       // L2CAP B-frame header (length: 12 bytes, channel-id: 0x0001 (ACL sig))
2166       0x0c, 0x00, 0x01, 0x00,
2167       // Connection Response (ID, length: 8, dst cid: 0x0000 (invalid),
2168       // src cid, res: 0x0004 (Refused; no resources available), status: none)
2169       0x03, conn_req_id, 0x08, 0x00,
2170       0x00, 0x00, LowerBits(kLocalId), UpperBits(kLocalId),
2171       0x04, 0x00, 0x00, 0x00));
2172   // clang-format on
2173 
2174   RunUntilIdle();
2175   EXPECT_TRUE(AllExpectedPacketsSent());
2176   EXPECT_TRUE(channel_cb_called);
2177 }
2178 
TEST_F(ChannelManagerMockAclChannelTest,ACLOutboundDynamicChannelFailedConfiguration)2179 TEST_F(ChannelManagerMockAclChannelTest,
2180        ACLOutboundDynamicChannelFailedConfiguration) {
2181   QueueRegisterACL(kTestHandle1,
2182                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2183 
2184   bool channel_cb_called = false;
2185   auto channel_cb = [&channel_cb_called](l2cap::Channel::WeakPtr channel) {
2186     channel_cb_called = true;
2187     EXPECT_FALSE(channel.is_alive());
2188   };
2189 
2190   const auto conn_req_id = NextCommandId();
2191   const auto config_req_id = NextCommandId();
2192   const auto disconn_req_id = NextCommandId();
2193   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
2194   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
2195                          kHighPriority);
2196   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
2197                          kHighPriority);
2198   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(disconn_req_id),
2199                          kHighPriority);
2200 
2201   ActivateOutboundChannel(kTestPsm, kChannelParams, std::move(channel_cb));
2202 
2203   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
2204   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
2205 
2206   // clang-format off
2207   ReceiveAclDataPacket(StaticByteBuffer(
2208       // ACL data header (handle: 0x0001, length: 14 bytes)
2209       0x01, 0x00, 0x0e, 0x00,
2210       // L2CAP B-frame header (length: 10 bytes, channel-id: 0x0001 (ACL sig))
2211       0x0a, 0x00, 0x01, 0x00,
2212       // Configuration Response (ID, length: 6, src cid, flags: 0,
2213       // res: 0x0002 (Rejected; no reason provided))
2214       0x05, config_req_id, 0x06, 0x00,
2215       LowerBits(kLocalId), UpperBits(kLocalId), 0x00, 0x00,
2216       0x02, 0x00));
2217 
2218   ReceiveAclDataPacket(StaticByteBuffer(
2219       // ACL data header (handle: 0x0001, length: 12 bytes)
2220       0x01, 0x00, 0x0c, 0x00,
2221       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
2222       0x08, 0x00, 0x01, 0x00,
2223       // Disconnection Response (ID, length: 4, dst cid, src cid)
2224       0x07, disconn_req_id, 0x04, 0x00,
2225       LowerBits(kRemoteId), UpperBits(kRemoteId), LowerBits(kLocalId), UpperBits(kLocalId)));
2226   // clang-format on
2227 
2228   RunUntilIdle();
2229   EXPECT_TRUE(AllExpectedPacketsSent());
2230   EXPECT_TRUE(channel_cb_called);
2231 }
2232 
TEST_F(ChannelManagerMockAclChannelTest,ACLInboundDynamicChannelLocalDisconnect)2233 TEST_F(ChannelManagerMockAclChannelTest,
2234        ACLInboundDynamicChannelLocalDisconnect) {
2235   constexpr Psm kBadPsm0 = 0x0004;
2236   constexpr Psm kBadPsm1 = 0x0103;
2237 
2238   QueueRegisterACL(kTestHandle1,
2239                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2240 
2241   bool dynamic_channel_closed = false;
2242   auto closed_cb = [&dynamic_channel_closed] { dynamic_channel_closed = true; };
2243 
2244   Channel::WeakPtr channel;
2245   auto channel_cb = [&channel, closed_cb = std::move(closed_cb)](
2246                         l2cap::Channel::WeakPtr opened_chan) {
2247     channel = std::move(opened_chan);
2248     EXPECT_TRUE(channel->Activate(NopRxCallback, std::move(closed_cb)));
2249   };
2250 
2251   EXPECT_FALSE(
2252       chanmgr()->RegisterService(kBadPsm0, ChannelParameters(), channel_cb));
2253   EXPECT_FALSE(
2254       chanmgr()->RegisterService(kBadPsm1, ChannelParameters(), channel_cb));
2255   EXPECT_TRUE(chanmgr()->RegisterService(
2256       kTestPsm, ChannelParameters(), std::move(channel_cb)));
2257 
2258   const auto config_req_id = NextCommandId();
2259   EXPECT_ACL_PACKET_OUT_(OutboundConnectionResponse(1), kHighPriority);
2260   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
2261                          kHighPriority);
2262   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
2263                          kHighPriority);
2264 
2265   ReceiveAclDataPacket(InboundConnectionRequest(1));
2266   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
2267   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
2268 
2269   RunUntilIdle();
2270 
2271   EXPECT_TRUE(AllExpectedPacketsSent());
2272   ASSERT_TRUE(channel.is_alive());
2273   EXPECT_FALSE(dynamic_channel_closed);
2274   EXPECT_EQ(kLocalId, channel->id());
2275   EXPECT_EQ(kRemoteId, channel->remote_id());
2276 
2277   // Test SDU transmission.
2278   // SDU must have remote channel ID (unlike for fixed channels).
2279   EXPECT_ACL_PACKET_OUT_(StaticByteBuffer(
2280                              // ACL data header (handle: 1, length 7)
2281                              0x01,
2282                              0x00,
2283                              0x08,
2284                              0x00,
2285                              // L2CAP B-frame: (length: 3, channel-id)
2286                              0x04,
2287                              0x00,
2288                              LowerBits(kRemoteId),
2289                              UpperBits(kRemoteId),
2290                              'T',
2291                              'e',
2292                              's',
2293                              't'),
2294                          kLowPriority);
2295 
2296   EXPECT_TRUE(channel->Send(NewBuffer('T', 'e', 's', 't')));
2297 
2298   RunUntilIdle();
2299   EXPECT_TRUE(AllExpectedPacketsSent());
2300 
2301   const auto disconn_req_id = NextCommandId();
2302   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(disconn_req_id),
2303                          kHighPriority);
2304 
2305   // Explicit deactivation should not res in |closed_cb| being called.
2306   channel->Deactivate();
2307 
2308   RunUntilIdle();
2309   EXPECT_TRUE(AllExpectedPacketsSent());
2310 
2311   // clang-format off
2312   ReceiveAclDataPacket(StaticByteBuffer(
2313       // ACL data header (handle: 0x0001, length: 12 bytes)
2314       0x01, 0x00, 0x0c, 0x00,
2315       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
2316       0x08, 0x00, 0x01, 0x00,
2317       // Disconnection Response (ID, length: 4, dst cid, src cid)
2318       0x07, disconn_req_id, 0x04, 0x00,
2319       LowerBits(kRemoteId), UpperBits(kRemoteId), LowerBits(kLocalId), UpperBits(kLocalId)));
2320   // clang-format on
2321 
2322   RunUntilIdle();
2323 
2324   EXPECT_FALSE(dynamic_channel_closed);
2325 }
2326 
TEST_F(ChannelManagerRealAclChannelTest,LinkSecurityProperties)2327 TEST_F(ChannelManagerRealAclChannelTest, LinkSecurityProperties) {
2328   sm::SecurityProperties security(sm::SecurityLevel::kEncrypted,
2329                                   16,
2330                                   /*secure_connections=*/false);
2331 
2332   // Has no effect.
2333   chanmgr()->AssignLinkSecurityProperties(kTestHandle1, security);
2334 
2335   // Register a link and open a channel.
2336   // The security properties should be accessible using the channel.
2337   LEFixedChannels fixed_channels = QueueLEConnection(
2338       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2339   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
2340 
2341   // The channel should start out at the lowest level of security.
2342   EXPECT_EQ(sm::SecurityProperties(), fixed_channels.att->security());
2343 
2344   // Assign a new security level.
2345   chanmgr()->AssignLinkSecurityProperties(kTestHandle1, security);
2346 
2347   // Channel should return the new security level.
2348   EXPECT_EQ(security, fixed_channels.att->security());
2349 }
2350 
TEST_F(ChannelManagerRealAclChannelTest,AssignLinkSecurityPropertiesOnClosedLinkDoesNothing)2351 TEST_F(ChannelManagerRealAclChannelTest,
2352        AssignLinkSecurityPropertiesOnClosedLinkDoesNothing) {
2353   // Register a link and open a channel.
2354   // The security properties should be accessible using the channel.
2355   LEFixedChannels fixed_channels = QueueLEConnection(
2356       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2357   ASSERT_TRUE(fixed_channels.att->Activate(NopRxCallback, DoNothing));
2358 
2359   chanmgr()->RemoveConnection(kTestHandle1);
2360   RunUntilIdle();
2361   EXPECT_FALSE(fixed_channels.att.is_alive());
2362 
2363   // Assign a new security level.
2364   sm::SecurityProperties security(sm::SecurityLevel::kEncrypted,
2365                                   16,
2366                                   /*secure_connections=*/false);
2367   chanmgr()->AssignLinkSecurityProperties(kTestHandle1, security);
2368 }
2369 
TEST_F(ChannelManagerMockAclChannelTest,UpgradeSecurity)2370 TEST_F(ChannelManagerMockAclChannelTest, UpgradeSecurity) {
2371   // The callback passed to to Channel::UpgradeSecurity().
2372   sm::Result<> received_status = fit::ok();
2373   int security_status_count = 0;
2374   auto status_callback = [&](sm::Result<> status) {
2375     received_status = status;
2376     security_status_count++;
2377   };
2378 
2379   // The security handler callback assigned when registering a link.
2380   sm::Result<> delivered_status = fit::ok();
2381   sm::SecurityLevel last_requested_level = sm::SecurityLevel::kNoSecurity;
2382   int security_request_count = 0;
2383   auto security_handler = [&](hci_spec::ConnectionHandle handle,
2384                               sm::SecurityLevel level,
2385                               auto callback) {
2386     EXPECT_EQ(kTestHandle1, handle);
2387     last_requested_level = level;
2388     security_request_count++;
2389 
2390     callback(delivered_status);
2391   };
2392 
2393   LEFixedChannels fixed_channels =
2394       RegisterLE(kTestHandle1,
2395                  pw::bluetooth::emboss::ConnectionRole::CENTRAL,
2396                  DoNothing,
2397                  NopLeConnParamCallback,
2398                  std::move(security_handler));
2399   l2cap::Channel::WeakPtr att = std::move(fixed_channels.att);
2400   ASSERT_TRUE(att->Activate(NopRxCallback, DoNothing));
2401 
2402   // Requesting security at or below the current level should succeed without
2403   // doing anything.
2404   att->UpgradeSecurity(sm::SecurityLevel::kNoSecurity, status_callback);
2405   RunUntilIdle();
2406   EXPECT_EQ(0, security_request_count);
2407   EXPECT_EQ(1, security_status_count);
2408   EXPECT_EQ(fit::ok(), received_status);
2409 
2410   // Test reporting an error.
2411   delivered_status = ToResult(HostError::kNotSupported);
2412   att->UpgradeSecurity(sm::SecurityLevel::kEncrypted, status_callback);
2413   RunUntilIdle();
2414   EXPECT_EQ(1, security_request_count);
2415   EXPECT_EQ(2, security_status_count);
2416   EXPECT_EQ(delivered_status, received_status);
2417   EXPECT_EQ(sm::SecurityLevel::kEncrypted, last_requested_level);
2418 
2419   chanmgr()->RemoveConnection(kTestHandle1);
2420   RunUntilIdle();
2421   EXPECT_FALSE(att.is_alive());
2422   EXPECT_EQ(1, security_request_count);
2423   EXPECT_EQ(2, security_status_count);
2424 }
2425 
TEST_F(ChannelManagerMockAclChannelTest,MtuOutboundChannelConfiguration)2426 TEST_F(ChannelManagerMockAclChannelTest, MtuOutboundChannelConfiguration) {
2427   constexpr uint16_t kRemoteMtu = kDefaultMTU - 1;
2428   constexpr uint16_t kLocalMtu = kMaxMTU;
2429 
2430   QueueRegisterACL(kTestHandle1,
2431                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2432 
2433   Channel::WeakPtr channel;
2434   auto channel_cb = [&channel](l2cap::Channel::WeakPtr activated_chan) {
2435     channel = std::move(activated_chan);
2436   };
2437 
2438   const auto conn_req_id = NextCommandId();
2439   const auto config_req_id = NextCommandId();
2440 
2441   // Signaling channel packets should be sent with high priority.
2442   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
2443   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
2444                          kHighPriority);
2445   EXPECT_ACL_PACKET_OUT_(
2446       OutboundConfigurationResponse(kPeerConfigRequestId, kRemoteMtu),
2447       kHighPriority);
2448 
2449   ActivateOutboundChannel(
2450       kTestPsm, kChannelParams, std::move(channel_cb), kTestHandle1);
2451 
2452   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
2453   ReceiveAclDataPacket(
2454       InboundConfigurationRequest(kPeerConfigRequestId, kRemoteMtu));
2455   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
2456 
2457   RunUntilIdle();
2458 
2459   EXPECT_TRUE(AllExpectedPacketsSent());
2460   EXPECT_TRUE(channel.is_alive());
2461   EXPECT_EQ(kRemoteMtu, channel->max_tx_sdu_size());
2462   EXPECT_EQ(kLocalMtu, channel->max_rx_sdu_size());
2463 }
2464 
TEST_F(ChannelManagerMockAclChannelTest,MtuInboundChannelConfiguration)2465 TEST_F(ChannelManagerMockAclChannelTest, MtuInboundChannelConfiguration) {
2466   constexpr uint16_t kRemoteMtu = kDefaultMTU - 1;
2467   constexpr uint16_t kLocalMtu = kMaxMTU;
2468 
2469   QueueRegisterACL(kTestHandle1,
2470                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2471 
2472   Channel::WeakPtr channel;
2473   auto channel_cb = [&channel](l2cap::Channel::WeakPtr opened_chan) {
2474     channel = std::move(opened_chan);
2475     EXPECT_TRUE(channel->Activate(NopRxCallback, DoNothing));
2476   };
2477 
2478   EXPECT_TRUE(chanmgr()->RegisterService(
2479       kTestPsm, kChannelParams, std::move(channel_cb)));
2480 
2481   CommandId kPeerConnectionRequestId = 3;
2482   const auto config_req_id = NextCommandId();
2483 
2484   EXPECT_ACL_PACKET_OUT_(OutboundConnectionResponse(kPeerConnectionRequestId),
2485                          kHighPriority);
2486   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
2487                          kHighPriority);
2488   EXPECT_ACL_PACKET_OUT_(
2489       OutboundConfigurationResponse(kPeerConfigRequestId, kRemoteMtu),
2490       kHighPriority);
2491 
2492   ReceiveAclDataPacket(InboundConnectionRequest(kPeerConnectionRequestId));
2493   ReceiveAclDataPacket(
2494       InboundConfigurationRequest(kPeerConfigRequestId, kRemoteMtu));
2495   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
2496 
2497   RunUntilIdle();
2498   EXPECT_TRUE(AllExpectedPacketsSent());
2499   EXPECT_TRUE(channel.is_alive());
2500   EXPECT_EQ(kRemoteMtu, channel->max_tx_sdu_size());
2501   EXPECT_EQ(kLocalMtu, channel->max_rx_sdu_size());
2502 }
2503 
TEST_F(ChannelManagerMockAclChannelTest,OutboundChannelConfigurationUsesChannelParameters)2504 TEST_F(ChannelManagerMockAclChannelTest,
2505        OutboundChannelConfigurationUsesChannelParameters) {
2506   l2cap::ChannelParameters chan_params;
2507   auto config_mode =
2508       l2cap::RetransmissionAndFlowControlMode::kEnhancedRetransmission;
2509   chan_params.mode = config_mode;
2510   chan_params.max_rx_sdu_size = l2cap::kMinACLMTU;
2511 
2512   const auto cmd_ids = QueueRegisterACL(
2513       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2514   ReceiveAclDataPacket(testing::AclExtFeaturesInfoRsp(
2515       cmd_ids.extended_features_id,
2516       kTestHandle1,
2517       kExtendedFeaturesBitEnhancedRetransmission));
2518 
2519   Channel::WeakPtr channel;
2520   auto channel_cb = [&channel](Channel::WeakPtr activated_chan) {
2521     channel = std::move(activated_chan);
2522   };
2523 
2524   const auto conn_req_id = NextCommandId();
2525   const auto config_req_id = NextCommandId();
2526   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
2527   EXPECT_ACL_PACKET_OUT_(
2528       OutboundConfigurationRequest(
2529           config_req_id, *chan_params.max_rx_sdu_size, config_mode),
2530       kHighPriority);
2531   const auto kInboundMtu = kDefaultMTU;
2532   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(
2533                              kPeerConfigRequestId, kInboundMtu, config_mode),
2534                          kHighPriority);
2535 
2536   ActivateOutboundChannel(
2537       kTestPsm, chan_params, std::move(channel_cb), kTestHandle1);
2538 
2539   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
2540   ReceiveAclDataPacket(InboundConfigurationRequest(
2541       kPeerConfigRequestId, kInboundMtu, config_mode));
2542   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
2543 
2544   RunUntilIdle();
2545 
2546   EXPECT_TRUE(AllExpectedPacketsSent());
2547   EXPECT_TRUE(channel.is_alive());
2548   EXPECT_EQ(*chan_params.max_rx_sdu_size, channel->max_rx_sdu_size());
2549   EXPECT_EQ(config_mode, channel->mode());
2550 
2551   // Receiver Ready poll request should elicit a response if ERTM has been set
2552   // up.
2553   EXPECT_ACL_PACKET_OUT_(
2554       testing::AclSFrameReceiverReady(kTestHandle1,
2555                                       kRemoteId,
2556                                       /*receive_seq_num=*/0,
2557                                       /*is_poll_request=*/false,
2558                                       /*is_poll_response=*/true),
2559       kLowPriority);
2560   ReceiveAclDataPacket(
2561       testing::AclSFrameReceiverReady(kTestHandle1,
2562                                       kLocalId,
2563                                       /*receive_seq_num=*/0,
2564                                       /*is_poll_request=*/true,
2565                                       /*is_poll_response=*/false));
2566 
2567   RunUntilIdle();
2568   EXPECT_TRUE(AllExpectedPacketsSent());
2569 }
2570 
TEST_F(ChannelManagerMockAclChannelTest,InboundChannelConfigurationUsesChannelParameters)2571 TEST_F(ChannelManagerMockAclChannelTest,
2572        InboundChannelConfigurationUsesChannelParameters) {
2573   CommandId kPeerConnReqId = 3;
2574 
2575   l2cap::ChannelParameters chan_params;
2576   auto config_mode =
2577       l2cap::RetransmissionAndFlowControlMode::kEnhancedRetransmission;
2578   chan_params.mode = config_mode;
2579   chan_params.max_rx_sdu_size = l2cap::kMinACLMTU;
2580 
2581   const auto cmd_ids = QueueRegisterACL(
2582       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2583   ReceiveAclDataPacket(testing::AclExtFeaturesInfoRsp(
2584       cmd_ids.extended_features_id,
2585       kTestHandle1,
2586       kExtendedFeaturesBitEnhancedRetransmission));
2587   Channel::WeakPtr channel;
2588   auto channel_cb = [&channel](l2cap::Channel::WeakPtr opened_chan) {
2589     channel = std::move(opened_chan);
2590     EXPECT_TRUE(channel->Activate(NopRxCallback, DoNothing));
2591   };
2592 
2593   EXPECT_TRUE(
2594       chanmgr()->RegisterService(kTestPsm, chan_params, std::move(channel_cb)));
2595 
2596   const auto config_req_id = NextCommandId();
2597   EXPECT_ACL_PACKET_OUT_(OutboundConnectionResponse(kPeerConnReqId),
2598                          kHighPriority);
2599   EXPECT_ACL_PACKET_OUT_(
2600       OutboundConfigurationRequest(
2601           config_req_id, *chan_params.max_rx_sdu_size, config_mode),
2602       kHighPriority);
2603   const auto kInboundMtu = kDefaultMTU;
2604   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(
2605                              kPeerConfigRequestId, kInboundMtu, config_mode),
2606                          kHighPriority);
2607 
2608   ReceiveAclDataPacket(InboundConnectionRequest(kPeerConnReqId));
2609   ReceiveAclDataPacket(InboundConfigurationRequest(
2610       kPeerConfigRequestId, kInboundMtu, config_mode));
2611   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
2612 
2613   RunUntilIdle();
2614   EXPECT_TRUE(AllExpectedPacketsSent());
2615   EXPECT_TRUE(channel.is_alive());
2616   EXPECT_EQ(*chan_params.max_rx_sdu_size, channel->max_rx_sdu_size());
2617   EXPECT_EQ(config_mode, channel->mode());
2618 
2619   // Receiver Ready poll request should elicit a response if ERTM has been set
2620   // up.
2621   EXPECT_ACL_PACKET_OUT_(
2622       testing::AclSFrameReceiverReady(kTestHandle1,
2623                                       kRemoteId,
2624                                       /*receive_seq_num=*/0,
2625                                       /*is_poll_request=*/false,
2626                                       /*is_poll_response=*/true),
2627       kLowPriority);
2628   ReceiveAclDataPacket(
2629       testing::AclSFrameReceiverReady(kTestHandle1,
2630                                       kLocalId,
2631                                       /*receive_seq_num=*/0,
2632                                       /*is_poll_request=*/true,
2633                                       /*is_poll_response=*/false));
2634 
2635   RunUntilIdle();
2636   EXPECT_TRUE(AllExpectedPacketsSent());
2637 }
2638 
TEST_F(ChannelManagerMockAclChannelTest,UnregisteringUnknownHandleClearsPendingPacketsAndDoesNotCrash)2639 TEST_F(ChannelManagerMockAclChannelTest,
2640        UnregisteringUnknownHandleClearsPendingPacketsAndDoesNotCrash) {
2641   // Packet for unregistered handle should be queued.
2642   ReceiveAclDataPacket(
2643       testing::AclConnectionReq(1, kTestHandle1, kRemoteId, kTestPsm));
2644   chanmgr()->RemoveConnection(kTestHandle1);
2645 
2646   QueueRegisterACL(kTestHandle1,
2647                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2648   // Since pending connection request packet was cleared, no response should be
2649   // sent.
2650   RunUntilIdle();
2651 }
2652 
TEST_F(ChannelManagerMockAclChannelTest,PacketsReceivedAfterChannelDeactivatedAndBeforeRemoveChannelCalledAreDropped)2653 TEST_F(
2654     ChannelManagerMockAclChannelTest,
2655     PacketsReceivedAfterChannelDeactivatedAndBeforeRemoveChannelCalledAreDropped) {
2656   QueueRegisterACL(kTestHandle1,
2657                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2658 
2659   Channel::WeakPtr channel;
2660   auto channel_cb = [&channel](l2cap::Channel::WeakPtr opened_chan) {
2661     channel = std::move(opened_chan);
2662     EXPECT_TRUE(channel->Activate(NopRxCallback, DoNothing));
2663   };
2664 
2665   EXPECT_TRUE(chanmgr()->RegisterService(
2666       kTestPsm, kChannelParams, std::move(channel_cb)));
2667 
2668   CommandId kPeerConnectionRequestId = 3;
2669   CommandId kLocalConfigRequestId = NextCommandId();
2670 
2671   EXPECT_ACL_PACKET_OUT_(OutboundConnectionResponse(kPeerConnectionRequestId),
2672                          kHighPriority);
2673   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(kLocalConfigRequestId),
2674                          kHighPriority);
2675   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
2676                          kHighPriority);
2677 
2678   ReceiveAclDataPacket(InboundConnectionRequest(kPeerConnectionRequestId));
2679   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
2680   ReceiveAclDataPacket(InboundConfigurationResponse(kLocalConfigRequestId));
2681 
2682   EXPECT_TRUE(AllExpectedPacketsSent());
2683   EXPECT_TRUE(channel.is_alive());
2684 
2685   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
2686                          kHighPriority);
2687 
2688   // channel marked inactive & LogicalLink::RemoveChannel called.
2689   channel->Deactivate();
2690   EXPECT_TRUE(AllExpectedPacketsSent());
2691 
2692   StaticByteBuffer kPacket(
2693       // ACL data header (handle: 0x0001, length: 4 bytes)
2694       0x01,
2695       0x00,
2696       0x04,
2697       0x00,
2698       // L2CAP B-frame header (length: 0 bytes, channel-id)
2699       0x00,
2700       0x00,
2701       LowerBits(kLocalId),
2702       UpperBits(kLocalId));
2703   // Packet for removed channel should be dropped by LogicalLink.
2704   ReceiveAclDataPacket(kPacket);
2705 }
2706 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveFixedChannelsInformationResponseWithNotSupportedResult)2707 TEST_F(ChannelManagerMockAclChannelTest,
2708        ReceiveFixedChannelsInformationResponseWithNotSupportedResult) {
2709   const auto cmd_ids = QueueRegisterACL(
2710       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2711   // Handler should check for res and not crash from reading mask or type.
2712   ReceiveAclDataPacket(testing::AclNotSupportedInformationResponse(
2713       cmd_ids.fixed_channels_supported_id, kTestHandle1));
2714   RunUntilIdle();
2715 }
2716 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveFixedChannelsInformationResponseWithInvalidResult)2717 TEST_F(ChannelManagerMockAclChannelTest,
2718        ReceiveFixedChannelsInformationResponseWithInvalidResult) {
2719   const auto cmd_ids = QueueRegisterACL(
2720       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2721   // Handler should check for res and not crash from reading mask or type.
2722   StaticByteBuffer kPacket(
2723       // ACL data header (handle: |link_handle|, length: 12 bytes)
2724       LowerBits(kTestHandle1),
2725       UpperBits(kTestHandle1),
2726       0x0c,
2727       0x00,
2728       // L2CAP B-frame header (length: 8 bytes, channel-id: 0x0001 (ACL sig))
2729       0x08,
2730       0x00,
2731       0x01,
2732       0x00,
2733       // Information Response (type, ID, length: 4)
2734       l2cap::kInformationResponse,
2735       cmd_ids.fixed_channels_supported_id,
2736       0x04,
2737       0x00,
2738       // Type = Fixed Channels Supported
2739       LowerBits(
2740           static_cast<uint16_t>(InformationType::kFixedChannelsSupported)),
2741       UpperBits(
2742           static_cast<uint16_t>(InformationType::kFixedChannelsSupported)),
2743       // Invalid Result
2744       0xFF,
2745       0xFF);
2746   ReceiveAclDataPacket(kPacket);
2747   RunUntilIdle();
2748 }
2749 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveFixedChannelsInformationResponseWithIncorrectType)2750 TEST_F(ChannelManagerMockAclChannelTest,
2751        ReceiveFixedChannelsInformationResponseWithIncorrectType) {
2752   const auto cmd_ids = QueueRegisterACL(
2753       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2754   // Handler should check type and not attempt to read fixed channel mask.
2755   ReceiveAclDataPacket(testing::AclExtFeaturesInfoRsp(
2756       cmd_ids.fixed_channels_supported_id, kTestHandle1, 0));
2757   RunUntilIdle();
2758 }
2759 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveFixedChannelsInformationResponseWithRejectStatus)2760 TEST_F(ChannelManagerMockAclChannelTest,
2761        ReceiveFixedChannelsInformationResponseWithRejectStatus) {
2762   const auto cmd_ids = QueueRegisterACL(
2763       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
2764   // Handler should check status and not attempt to read fields.
2765   ReceiveAclDataPacket(testing::AclCommandRejectNotUnderstoodRsp(
2766       cmd_ids.fixed_channels_supported_id, kTestHandle1));
2767   RunUntilIdle();
2768 }
2769 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveValidConnectionParameterUpdateRequestAsCentralAndRespondWithAcceptedResult)2770 TEST_F(
2771     ChannelManagerMockAclChannelTest,
2772     ReceiveValidConnectionParameterUpdateRequestAsCentralAndRespondWithAcceptedResult) {
2773   // Valid parameter values
2774   constexpr uint16_t kIntervalMin = 6;
2775   constexpr uint16_t kIntervalMax = 7;
2776   constexpr uint16_t kPeripheralLatency = 1;
2777   constexpr uint16_t kTimeoutMult = 10;
2778 
2779   std::optional<hci_spec::LEPreferredConnectionParameters> params;
2780   LEConnectionParameterUpdateCallback param_cb =
2781       [&params](const hci_spec::LEPreferredConnectionParameters& cb_params) {
2782         params = cb_params;
2783       };
2784 
2785   LEFixedChannels fixed_channels =
2786       RegisterLE(kTestHandle1,
2787                  pw::bluetooth::emboss::ConnectionRole::CENTRAL,
2788                  /*link_error_cb=*/DoNothing,
2789                  std::move(param_cb));
2790 
2791   constexpr CommandId kParamReqId = 4;  // random
2792 
2793   EXPECT_LE_PACKET_OUT(testing::AclConnectionParameterUpdateRsp(
2794                            kParamReqId,
2795                            kTestHandle1,
2796                            ConnectionParameterUpdateResult::kAccepted),
2797                        kHighPriority);
2798 
2799   ReceiveAclDataPacket(
2800       testing::AclConnectionParameterUpdateReq(kParamReqId,
2801                                                kTestHandle1,
2802                                                kIntervalMin,
2803                                                kIntervalMax,
2804                                                kPeripheralLatency,
2805                                                kTimeoutMult));
2806   RunUntilIdle();
2807 
2808   ASSERT_TRUE(params.has_value());
2809   EXPECT_EQ(kIntervalMin, params->min_interval());
2810   EXPECT_EQ(kIntervalMax, params->max_interval());
2811   EXPECT_EQ(kPeripheralLatency, params->max_latency());
2812   EXPECT_EQ(kTimeoutMult, params->supervision_timeout());
2813 }
2814 
2815 // If an LE Peripheral host receives a Connection Parameter Update Request, it
2816 // should reject it.
TEST_F(ChannelManagerMockAclChannelTest,ReceiveValidConnectionParameterUpdateRequestAsPeripheralAndRespondWithReject)2817 TEST_F(
2818     ChannelManagerMockAclChannelTest,
2819     ReceiveValidConnectionParameterUpdateRequestAsPeripheralAndRespondWithReject) {
2820   // Valid parameter values
2821   constexpr uint16_t kIntervalMin = 6;
2822   constexpr uint16_t kIntervalMax = 7;
2823   constexpr uint16_t kPeripheralLatency = 1;
2824   constexpr uint16_t kTimeoutMult = 10;
2825 
2826   std::optional<hci_spec::LEPreferredConnectionParameters> params;
2827   LEConnectionParameterUpdateCallback param_cb =
2828       [&params](const hci_spec::LEPreferredConnectionParameters& cb_params) {
2829         params = cb_params;
2830       };
2831 
2832   LEFixedChannels fixed_channels =
2833       RegisterLE(kTestHandle1,
2834                  pw::bluetooth::emboss::ConnectionRole::PERIPHERAL,
2835                  /*link_error_cb=*/DoNothing,
2836                  std::move(param_cb));
2837 
2838   constexpr CommandId kParamReqId = 4;  // random
2839 
2840   EXPECT_LE_PACKET_OUT(testing::AclCommandRejectNotUnderstoodRsp(
2841                            kParamReqId, kTestHandle1, kLESignalingChannelId),
2842                        kHighPriority);
2843 
2844   ReceiveAclDataPacket(
2845       testing::AclConnectionParameterUpdateReq(kParamReqId,
2846                                                kTestHandle1,
2847                                                kIntervalMin,
2848                                                kIntervalMax,
2849                                                kPeripheralLatency,
2850                                                kTimeoutMult));
2851   RunUntilIdle();
2852 
2853   ASSERT_FALSE(params.has_value());
2854 }
2855 
TEST_F(ChannelManagerMockAclChannelTest,ReceiveInvalidConnectionParameterUpdateRequestsAndRespondWithRejectedResult)2856 TEST_F(
2857     ChannelManagerMockAclChannelTest,
2858     ReceiveInvalidConnectionParameterUpdateRequestsAndRespondWithRejectedResult) {
2859   // Valid parameter values
2860   constexpr uint16_t kIntervalMin = 6;
2861   constexpr uint16_t kIntervalMax = 7;
2862   constexpr uint16_t kPeripheralLatency = 1;
2863   constexpr uint16_t kTimeoutMult = 10;
2864 
2865   // Callback should not be called for request with invalid parameters.
2866   LEConnectionParameterUpdateCallback param_cb = [](auto /*params*/) {
2867     ADD_FAILURE();
2868   };
2869   LEFixedChannels fixed_channels =
2870       RegisterLE(kTestHandle1,
2871                  pw::bluetooth::emboss::ConnectionRole::CENTRAL,
2872                  /*link_error_cb=*/DoNothing,
2873                  std::move(param_cb));
2874 
2875   constexpr CommandId kParamReqId = 4;  // random
2876 
2877   std::array invalid_requests = {
2878       // interval min > interval max
2879       testing::AclConnectionParameterUpdateReq(kParamReqId,
2880                                                kTestHandle1,
2881                                                /*interval_min=*/7,
2882                                                /*interval_max=*/6,
2883                                                kPeripheralLatency,
2884                                                kTimeoutMult),
2885       // interval_min too small
2886       testing::AclConnectionParameterUpdateReq(
2887           kParamReqId,
2888           kTestHandle1,
2889           hci_spec::kLEConnectionIntervalMin - 1,
2890           kIntervalMax,
2891           kPeripheralLatency,
2892           kTimeoutMult),
2893       // interval max too large
2894       testing::AclConnectionParameterUpdateReq(
2895           kParamReqId,
2896           kTestHandle1,
2897           kIntervalMin,
2898           hci_spec::kLEConnectionIntervalMax + 1,
2899           kPeripheralLatency,
2900           kTimeoutMult),
2901       // latency too large
2902       testing::AclConnectionParameterUpdateReq(
2903           kParamReqId,
2904           kTestHandle1,
2905           kIntervalMin,
2906           kIntervalMax,
2907           hci_spec::kLEConnectionLatencyMax + 1,
2908           kTimeoutMult),
2909       // timeout multiplier too small
2910       testing::AclConnectionParameterUpdateReq(
2911           kParamReqId,
2912           kTestHandle1,
2913           kIntervalMin,
2914           kIntervalMax,
2915           kPeripheralLatency,
2916           hci_spec::kLEConnectionSupervisionTimeoutMin - 1),
2917       // timeout multiplier too large
2918       testing::AclConnectionParameterUpdateReq(
2919           kParamReqId,
2920           kTestHandle1,
2921           kIntervalMin,
2922           kIntervalMax,
2923           kPeripheralLatency,
2924           hci_spec::kLEConnectionSupervisionTimeoutMax + 1)};
2925 
2926   for (auto& req : invalid_requests) {
2927     EXPECT_LE_PACKET_OUT(testing::AclConnectionParameterUpdateRsp(
2928                              kParamReqId,
2929                              kTestHandle1,
2930                              ConnectionParameterUpdateResult::kRejected),
2931                          kHighPriority);
2932     ReceiveAclDataPacket(req);
2933   }
2934   RunUntilIdle();
2935 }
2936 
TEST_F(ChannelManagerMockAclChannelTest,RequestConnParamUpdateForUnknownLinkIsNoOp)2937 TEST_F(ChannelManagerMockAclChannelTest,
2938        RequestConnParamUpdateForUnknownLinkIsNoOp) {
2939   auto update_cb = [](auto) { ADD_FAILURE(); };
2940   chanmgr()->RequestConnectionParameterUpdate(
2941       kTestHandle1,
2942       hci_spec::LEPreferredConnectionParameters(),
2943       std::move(update_cb));
2944   RunUntilIdle();
2945 }
2946 
TEST_F(ChannelManagerMockAclChannelTest,RequestConnParamUpdateAsPeripheralAndReceiveAcceptedAndRejectedResponses)2947 TEST_F(
2948     ChannelManagerMockAclChannelTest,
2949     RequestConnParamUpdateAsPeripheralAndReceiveAcceptedAndRejectedResponses) {
2950   LEFixedChannels fixed_channels = RegisterLE(
2951       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
2952 
2953   // Valid parameter values
2954   constexpr uint16_t kIntervalMin = 6;
2955   constexpr uint16_t kIntervalMax = 7;
2956   constexpr uint16_t kPeripheralLatency = 1;
2957   constexpr uint16_t kTimeoutMult = 10;
2958   const hci_spec::LEPreferredConnectionParameters kParams(
2959       kIntervalMin, kIntervalMax, kPeripheralLatency, kTimeoutMult);
2960 
2961   std::optional<bool> accepted;
2962   auto request_cb = [&accepted](bool cb_accepted) { accepted = cb_accepted; };
2963 
2964   // Receive "Accepted" Response:
2965 
2966   CommandId param_update_req_id = NextCommandId();
2967   EXPECT_LE_PACKET_OUT(
2968       testing::AclConnectionParameterUpdateReq(param_update_req_id,
2969                                                kTestHandle1,
2970                                                kIntervalMin,
2971                                                kIntervalMax,
2972                                                kPeripheralLatency,
2973                                                kTimeoutMult),
2974       kHighPriority);
2975   chanmgr()->RequestConnectionParameterUpdate(
2976       kTestHandle1, kParams, request_cb);
2977   RunUntilIdle();
2978   EXPECT_FALSE(accepted.has_value());
2979 
2980   ReceiveAclDataPacket(testing::AclConnectionParameterUpdateRsp(
2981       param_update_req_id,
2982       kTestHandle1,
2983       ConnectionParameterUpdateResult::kAccepted));
2984   RunUntilIdle();
2985   ASSERT_TRUE(accepted.has_value());
2986   EXPECT_TRUE(accepted.value());
2987   accepted.reset();
2988 
2989   // Receive "Rejected" Response:
2990 
2991   param_update_req_id = NextCommandId();
2992   EXPECT_LE_PACKET_OUT(
2993       testing::AclConnectionParameterUpdateReq(param_update_req_id,
2994                                                kTestHandle1,
2995                                                kIntervalMin,
2996                                                kIntervalMax,
2997                                                kPeripheralLatency,
2998                                                kTimeoutMult),
2999       kHighPriority);
3000   chanmgr()->RequestConnectionParameterUpdate(
3001       kTestHandle1, kParams, std::move(request_cb));
3002   RunUntilIdle();
3003   EXPECT_FALSE(accepted.has_value());
3004 
3005   ReceiveAclDataPacket(testing::AclConnectionParameterUpdateRsp(
3006       param_update_req_id,
3007       kTestHandle1,
3008       ConnectionParameterUpdateResult::kRejected));
3009   RunUntilIdle();
3010   ASSERT_TRUE(accepted.has_value());
3011   EXPECT_FALSE(accepted.value());
3012 }
3013 
TEST_F(ChannelManagerMockAclChannelTest,ConnParamUpdateRequestRejected)3014 TEST_F(ChannelManagerMockAclChannelTest, ConnParamUpdateRequestRejected) {
3015   LEFixedChannels fixed_channels = RegisterLE(
3016       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
3017 
3018   // Valid parameter values
3019   constexpr uint16_t kIntervalMin = 6;
3020   constexpr uint16_t kIntervalMax = 7;
3021   constexpr uint16_t kPeripheralLatency = 1;
3022   constexpr uint16_t kTimeoutMult = 10;
3023   const hci_spec::LEPreferredConnectionParameters kParams(
3024       kIntervalMin, kIntervalMax, kPeripheralLatency, kTimeoutMult);
3025 
3026   std::optional<bool> accepted;
3027   auto request_cb = [&accepted](bool cb_accepted) { accepted = cb_accepted; };
3028 
3029   const CommandId kParamUpdateReqId = NextCommandId();
3030   EXPECT_LE_PACKET_OUT(
3031       testing::AclConnectionParameterUpdateReq(kParamUpdateReqId,
3032                                                kTestHandle1,
3033                                                kIntervalMin,
3034                                                kIntervalMax,
3035                                                kPeripheralLatency,
3036                                                kTimeoutMult),
3037       kHighPriority);
3038   chanmgr()->RequestConnectionParameterUpdate(
3039       kTestHandle1, kParams, request_cb);
3040   RunUntilIdle();
3041   EXPECT_FALSE(accepted.has_value());
3042 
3043   ReceiveAclDataPacket(testing::AclCommandRejectNotUnderstoodRsp(
3044       kParamUpdateReqId, kTestHandle1, kLESignalingChannelId));
3045   RunUntilIdle();
3046   ASSERT_TRUE(accepted.has_value());
3047   EXPECT_FALSE(accepted.value());
3048 }
3049 
TEST_F(ChannelManagerRealAclChannelTest,DestroyingChannelManagerReleasesLogicalLinkAndClosesChannels)3050 TEST_F(ChannelManagerRealAclChannelTest,
3051        DestroyingChannelManagerReleasesLogicalLinkAndClosesChannels) {
3052   QueueAclConnection(kTestHandle1);
3053   RunUntilIdle();
3054   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
3055 
3056   auto link = chanmgr()->LogicalLinkForTesting(kTestHandle1);
3057   ASSERT_TRUE(link.is_alive());
3058 
3059   bool closed = false;
3060   auto closed_cb = [&] { closed = true; };
3061 
3062   auto chan = ActivateNewFixedChannel(
3063       kConnectionlessChannelId, kTestHandle1, closed_cb);
3064   ASSERT_TRUE(chan.is_alive());
3065   ASSERT_FALSE(closed);
3066 
3067   TearDown();  // Destroys channel manager
3068   RunUntilIdle();
3069   EXPECT_TRUE(closed);
3070   // If link is still valid, there may be a memory leak.
3071   EXPECT_FALSE(link.is_alive());
3072 
3073   // If the above fails, check if the channel was holding a strong reference to
3074   // the link.
3075   chan = Channel::WeakPtr();
3076   RunUntilIdle();
3077   EXPECT_TRUE(closed);
3078   EXPECT_FALSE(link.is_alive());
3079 }
3080 
TEST_F(ChannelManagerMockAclChannelTest,RequestAclPriorityNormal)3081 TEST_F(ChannelManagerMockAclChannelTest, RequestAclPriorityNormal) {
3082   QueueRegisterACL(kTestHandle1,
3083                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3084   RunUntilIdle();
3085 
3086   auto channel = SetUpOutboundChannel();
3087 
3088   std::optional<AclPriority> requested_priority;
3089   acl_data_channel()->set_request_acl_priority_cb(
3090       [&requested_priority](auto priority, auto handle, auto cb) {
3091         EXPECT_EQ(handle, kTestHandle1);
3092         requested_priority = priority;
3093         cb(fit::ok());
3094       });
3095 
3096   size_t result_cb_count = 0;
3097   channel->RequestAclPriority(AclPriority::kNormal, [&](auto res) {
3098     EXPECT_EQ(fit::ok(), res);
3099     result_cb_count++;
3100   });
3101 
3102   EXPECT_EQ(result_cb_count, 1u);
3103   EXPECT_FALSE(requested_priority.has_value());
3104 
3105   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
3106                          kHighPriority);
3107   // Closing channel should not request normal priority because it is already
3108   // the current priority.
3109   channel->Deactivate();
3110   EXPECT_EQ(result_cb_count, 1u);
3111   EXPECT_FALSE(requested_priority.has_value());
3112 }
3113 
TEST_F(ChannelManagerMockAclChannelTest,RequestAclPrioritySinkThenNormal)3114 TEST_F(ChannelManagerMockAclChannelTest, RequestAclPrioritySinkThenNormal) {
3115   QueueRegisterACL(kTestHandle1,
3116                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3117   RunUntilIdle();
3118 
3119   auto channel = SetUpOutboundChannel();
3120 
3121   std::optional<AclPriority> requested_priority;
3122   acl_data_channel()->set_request_acl_priority_cb(
3123       [&requested_priority](auto priority, auto handle, auto cb) {
3124         EXPECT_EQ(handle, kTestHandle1);
3125         requested_priority = priority;
3126         cb(fit::ok());
3127       });
3128 
3129   size_t result_cb_count = 0;
3130   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3131     EXPECT_EQ(fit::ok(), res);
3132     result_cb_count++;
3133   });
3134 
3135   EXPECT_EQ(result_cb_count, 1u);
3136   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kSink);
3137   ASSERT_TRUE(requested_priority.has_value());
3138   EXPECT_EQ(*requested_priority, AclPriority::kSink);
3139 
3140   channel->RequestAclPriority(AclPriority::kNormal, [&](auto res) {
3141     EXPECT_EQ(fit::ok(), res);
3142     result_cb_count++;
3143   });
3144 
3145   EXPECT_EQ(result_cb_count, 2u);
3146   ASSERT_TRUE(requested_priority.has_value());
3147   EXPECT_EQ(*requested_priority, AclPriority::kNormal);
3148   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kNormal);
3149 
3150   requested_priority.reset();
3151 
3152   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
3153                          kHighPriority);
3154   // Closing channel should not request normal priority because it is already
3155   // the current priority.
3156   channel->Deactivate();
3157   EXPECT_FALSE(requested_priority.has_value());
3158 }
3159 
TEST_F(ChannelManagerMockAclChannelTest,RequestAclPrioritySinkThenDeactivateChannelAfterResult)3160 TEST_F(ChannelManagerMockAclChannelTest,
3161        RequestAclPrioritySinkThenDeactivateChannelAfterResult) {
3162   QueueRegisterACL(kTestHandle1,
3163                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3164   RunUntilIdle();
3165 
3166   auto channel = SetUpOutboundChannel();
3167 
3168   std::optional<AclPriority> requested_priority;
3169   acl_data_channel()->set_request_acl_priority_cb(
3170       [&requested_priority](auto priority, auto handle, auto cb) {
3171         EXPECT_EQ(handle, kTestHandle1);
3172         requested_priority = priority;
3173         cb(fit::ok());
3174       });
3175 
3176   size_t result_cb_count = 0;
3177   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3178     EXPECT_EQ(fit::ok(), res);
3179     result_cb_count++;
3180   });
3181 
3182   EXPECT_EQ(result_cb_count, 1u);
3183   ASSERT_TRUE(requested_priority.has_value());
3184   EXPECT_EQ(*requested_priority, AclPriority::kSink);
3185 
3186   requested_priority.reset();
3187 
3188   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
3189                          kHighPriority);
3190   channel->Deactivate();
3191   ASSERT_TRUE(requested_priority.has_value());
3192   EXPECT_EQ(*requested_priority, AclPriority::kNormal);
3193 }
3194 
TEST_F(ChannelManagerMockAclChannelTest,RequestAclPrioritySinkThenReceiveDisconnectRequest)3195 TEST_F(ChannelManagerMockAclChannelTest,
3196        RequestAclPrioritySinkThenReceiveDisconnectRequest) {
3197   QueueRegisterACL(kTestHandle1,
3198                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3199   RunUntilIdle();
3200 
3201   auto channel = SetUpOutboundChannel();
3202 
3203   std::optional<AclPriority> requested_priority;
3204   acl_data_channel()->set_request_acl_priority_cb(
3205       [&requested_priority](auto priority, auto handle, auto cb) {
3206         EXPECT_EQ(handle, kTestHandle1);
3207         requested_priority = priority;
3208         cb(fit::ok());
3209       });
3210 
3211   size_t result_cb_count = 0;
3212   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3213     EXPECT_EQ(fit::ok(), res);
3214     result_cb_count++;
3215   });
3216 
3217   EXPECT_EQ(result_cb_count, 1u);
3218   ASSERT_TRUE(requested_priority.has_value());
3219   EXPECT_EQ(*requested_priority, AclPriority::kSink);
3220   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kSink);
3221 
3222   requested_priority.reset();
3223 
3224   const auto kPeerDisconReqId = 1;
3225   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionResponse(kPeerDisconReqId),
3226                          kHighPriority);
3227   ReceiveAclDataPacket(testing::AclDisconnectionReq(
3228       kPeerDisconReqId, kTestHandle1, kRemoteId, kLocalId));
3229   RunUntilIdle();
3230   ASSERT_TRUE(requested_priority.has_value());
3231   EXPECT_EQ(*requested_priority, AclPriority::kNormal);
3232 }
3233 
TEST_F(ChannelManagerMockAclChannelTest,RequestAclPrioritySinkThenDeactivateChannelBeforeResultShouldResetPriorityOnDeactivate)3234 TEST_F(
3235     ChannelManagerMockAclChannelTest,
3236     RequestAclPrioritySinkThenDeactivateChannelBeforeResultShouldResetPriorityOnDeactivate) {
3237   QueueRegisterACL(kTestHandle1,
3238                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3239   RunUntilIdle();
3240 
3241   auto channel = SetUpOutboundChannel();
3242 
3243   std::vector<
3244       std::pair<AclPriority, fit::callback<void(fit::result<fit::failed>)>>>
3245       requests;
3246   acl_data_channel()->set_request_acl_priority_cb(
3247       [&](auto priority, auto handle, auto cb) {
3248         EXPECT_EQ(handle, kTestHandle1);
3249         requests.push_back({priority, std::move(cb)});
3250       });
3251 
3252   size_t result_cb_count = 0;
3253   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3254     EXPECT_EQ(fit::ok(), res);
3255     result_cb_count++;
3256   });
3257   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kNormal);
3258   EXPECT_EQ(result_cb_count, 0u);
3259   EXPECT_EQ(requests.size(), 1u);
3260 
3261   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
3262                          kHighPriority);
3263   // Should queue kNormal ACL priority request.
3264   channel->Deactivate();
3265   ASSERT_EQ(requests.size(), 1u);
3266 
3267   requests[0].second(fit::ok());
3268   EXPECT_EQ(result_cb_count, 1u);
3269   ASSERT_EQ(requests.size(), 2u);
3270   EXPECT_EQ(requests[1].first, AclPriority::kNormal);
3271 
3272   requests[1].second(fit::ok());
3273 }
3274 
TEST_F(ChannelManagerMockAclChannelTest,RequestAclPrioritySinkFails)3275 TEST_F(ChannelManagerMockAclChannelTest, RequestAclPrioritySinkFails) {
3276   QueueRegisterACL(kTestHandle1,
3277                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3278   RunUntilIdle();
3279 
3280   auto channel = SetUpOutboundChannel();
3281 
3282   acl_data_channel()->set_request_acl_priority_cb(
3283       [](auto priority, auto handle, auto cb) {
3284         EXPECT_EQ(handle, kTestHandle1);
3285         cb(fit::failed());
3286       });
3287 
3288   size_t result_cb_count = 0;
3289   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3290     EXPECT_TRUE(res.is_error());
3291     result_cb_count++;
3292   });
3293 
3294   EXPECT_EQ(result_cb_count, 1u);
3295   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kNormal);
3296 
3297   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
3298                          kHighPriority);
3299   channel->Deactivate();
3300 }
3301 
TEST_F(ChannelManagerMockAclChannelTest,TwoChannelsRequestAclPrioritySinkAndDeactivate)3302 TEST_F(ChannelManagerMockAclChannelTest,
3303        TwoChannelsRequestAclPrioritySinkAndDeactivate) {
3304   QueueRegisterACL(kTestHandle1,
3305                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3306   RunUntilIdle();
3307 
3308   const auto kChannelIds0 = std::make_pair(ChannelId(0x40), ChannelId(0x41));
3309   const auto kChannelIds1 = std::make_pair(ChannelId(0x41), ChannelId(0x42));
3310 
3311   auto channel_0 =
3312       SetUpOutboundChannel(kChannelIds0.first, kChannelIds0.second);
3313   auto channel_1 =
3314       SetUpOutboundChannel(kChannelIds1.first, kChannelIds1.second);
3315 
3316   std::optional<AclPriority> requested_priority;
3317   acl_data_channel()->set_request_acl_priority_cb(
3318       [&](auto priority, auto handle, auto cb) {
3319         EXPECT_EQ(handle, kTestHandle1);
3320         requested_priority = priority;
3321         cb(fit::ok());
3322       });
3323 
3324   size_t result_cb_count = 0;
3325   channel_0->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3326     EXPECT_EQ(fit::ok(), res);
3327     result_cb_count++;
3328   });
3329   ASSERT_TRUE(requested_priority);
3330   EXPECT_EQ(*requested_priority, AclPriority::kSink);
3331   EXPECT_EQ(result_cb_count, 1u);
3332   EXPECT_EQ(channel_0->requested_acl_priority(), AclPriority::kSink);
3333   requested_priority.reset();
3334 
3335   channel_1->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3336     EXPECT_EQ(fit::ok(), res);
3337     result_cb_count++;
3338   });
3339   // Priority is already sink. No additional request should be sent.
3340   EXPECT_FALSE(requested_priority);
3341   EXPECT_EQ(result_cb_count, 2u);
3342   EXPECT_EQ(channel_1->requested_acl_priority(), AclPriority::kSink);
3343 
3344   EXPECT_ACL_PACKET_OUT_(testing::AclDisconnectionReq(NextCommandId(),
3345                                                       kTestHandle1,
3346                                                       kChannelIds0.first,
3347                                                       kChannelIds0.second),
3348                          kHighPriority);
3349   channel_0->Deactivate();
3350   // Because channel_1 is still using sink priority, no command should be sent.
3351   EXPECT_FALSE(requested_priority);
3352 
3353   EXPECT_ACL_PACKET_OUT_(testing::AclDisconnectionReq(NextCommandId(),
3354                                                       kTestHandle1,
3355                                                       kChannelIds1.first,
3356                                                       kChannelIds1.second),
3357                          kHighPriority);
3358   channel_1->Deactivate();
3359   ASSERT_TRUE(requested_priority);
3360   EXPECT_EQ(*requested_priority, AclPriority::kNormal);
3361 }
3362 
TEST_F(ChannelManagerMockAclChannelTest,TwoChannelsRequestConflictingAclPriorities)3363 TEST_F(ChannelManagerMockAclChannelTest,
3364        TwoChannelsRequestConflictingAclPriorities) {
3365   QueueRegisterACL(kTestHandle1,
3366                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3367   RunUntilIdle();
3368 
3369   const auto kChannelIds0 = std::make_pair(ChannelId(0x40), ChannelId(0x41));
3370   const auto kChannelIds1 = std::make_pair(ChannelId(0x41), ChannelId(0x42));
3371 
3372   auto channel_0 =
3373       SetUpOutboundChannel(kChannelIds0.first, kChannelIds0.second);
3374   auto channel_1 =
3375       SetUpOutboundChannel(kChannelIds1.first, kChannelIds1.second);
3376 
3377   std::optional<AclPriority> requested_priority;
3378   acl_data_channel()->set_request_acl_priority_cb(
3379       [&](auto priority, auto handle, auto cb) {
3380         EXPECT_EQ(handle, kTestHandle1);
3381         requested_priority = priority;
3382         cb(fit::ok());
3383       });
3384 
3385   size_t result_cb_count = 0;
3386   channel_0->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3387     EXPECT_EQ(fit::ok(), res);
3388     result_cb_count++;
3389   });
3390   ASSERT_TRUE(requested_priority);
3391   EXPECT_EQ(*requested_priority, AclPriority::kSink);
3392   EXPECT_EQ(result_cb_count, 1u);
3393   requested_priority.reset();
3394 
3395   channel_1->RequestAclPriority(AclPriority::kSource, [&](auto res) {
3396     EXPECT_TRUE(res.is_error());
3397     result_cb_count++;
3398   });
3399   // Priority conflict should prevent priority request.
3400   EXPECT_FALSE(requested_priority);
3401   EXPECT_EQ(result_cb_count, 2u);
3402   EXPECT_EQ(channel_1->requested_acl_priority(), AclPriority::kNormal);
3403 
3404   EXPECT_ACL_PACKET_OUT_(testing::AclDisconnectionReq(NextCommandId(),
3405                                                       kTestHandle1,
3406                                                       kChannelIds0.first,
3407                                                       kChannelIds0.second),
3408                          kHighPriority);
3409   channel_0->Deactivate();
3410   ASSERT_TRUE(requested_priority);
3411   EXPECT_EQ(*requested_priority, AclPriority::kNormal);
3412   requested_priority.reset();
3413 
3414   EXPECT_ACL_PACKET_OUT_(testing::AclDisconnectionReq(NextCommandId(),
3415                                                       kTestHandle1,
3416                                                       kChannelIds1.first,
3417                                                       kChannelIds1.second),
3418                          kHighPriority);
3419   channel_1->Deactivate();
3420   EXPECT_FALSE(requested_priority);
3421 }
3422 
3423 // If two channels request ACL priorities before the first command completes,
3424 // they should receive responses as if they were handled strictly sequentially.
TEST_F(ChannelManagerMockAclChannelTest,TwoChannelsRequestAclPrioritiesAtSameTime)3425 TEST_F(ChannelManagerMockAclChannelTest,
3426        TwoChannelsRequestAclPrioritiesAtSameTime) {
3427   QueueRegisterACL(kTestHandle1,
3428                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3429   RunUntilIdle();
3430 
3431   const auto kChannelIds0 = std::make_pair(ChannelId(0x40), ChannelId(0x41));
3432   const auto kChannelIds1 = std::make_pair(ChannelId(0x41), ChannelId(0x42));
3433 
3434   auto channel_0 =
3435       SetUpOutboundChannel(kChannelIds0.first, kChannelIds0.second);
3436   auto channel_1 =
3437       SetUpOutboundChannel(kChannelIds1.first, kChannelIds1.second);
3438 
3439   std::vector<fit::callback<void(fit::result<fit::failed>)>> command_callbacks;
3440   acl_data_channel()->set_request_acl_priority_cb(
3441       [&](auto priority, auto handle, auto cb) {
3442         command_callbacks.push_back(std::move(cb));
3443       });
3444 
3445   size_t result_cb_count_0 = 0;
3446   channel_0->RequestAclPriority(AclPriority::kSink,
3447                                 [&](auto res) { result_cb_count_0++; });
3448   EXPECT_EQ(command_callbacks.size(), 1u);
3449   EXPECT_EQ(result_cb_count_0, 0u);
3450 
3451   size_t result_cb_count_1 = 0;
3452   channel_1->RequestAclPriority(AclPriority::kSource,
3453                                 [&](auto res) { result_cb_count_1++; });
3454   EXPECT_EQ(result_cb_count_1, 0u);
3455   ASSERT_EQ(command_callbacks.size(), 1u);
3456 
3457   command_callbacks[0](fit::ok());
3458   EXPECT_EQ(result_cb_count_0, 1u);
3459   // Second request should be notified of conflict error.
3460   EXPECT_EQ(result_cb_count_1, 1u);
3461   EXPECT_EQ(command_callbacks.size(), 1u);
3462 
3463   // Because requests should be handled sequentially, the second request should
3464   // have failed.
3465   EXPECT_EQ(channel_0->requested_acl_priority(), AclPriority::kSink);
3466   EXPECT_EQ(channel_1->requested_acl_priority(), AclPriority::kNormal);
3467 
3468   EXPECT_ACL_PACKET_OUT_(testing::AclDisconnectionReq(NextCommandId(),
3469                                                       kTestHandle1,
3470                                                       kChannelIds0.first,
3471                                                       kChannelIds0.second),
3472                          kHighPriority);
3473   channel_0->Deactivate();
3474 
3475   EXPECT_ACL_PACKET_OUT_(testing::AclDisconnectionReq(NextCommandId(),
3476                                                       kTestHandle1,
3477                                                       kChannelIds1.first,
3478                                                       kChannelIds1.second),
3479                          kHighPriority);
3480   channel_1->Deactivate();
3481 }
3482 
TEST_F(ChannelManagerMockAclChannelTest,QueuedSinkAclPriorityForClosedChannelIsIgnored)3483 TEST_F(ChannelManagerMockAclChannelTest,
3484        QueuedSinkAclPriorityForClosedChannelIsIgnored) {
3485   QueueRegisterACL(kTestHandle1,
3486                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3487   RunUntilIdle();
3488 
3489   auto channel = SetUpOutboundChannel();
3490 
3491   std::vector<
3492       std::pair<AclPriority, fit::callback<void(fit::result<fit::failed>)>>>
3493       requests;
3494   acl_data_channel()->set_request_acl_priority_cb(
3495       [&](auto priority, auto handle, auto cb) {
3496         EXPECT_EQ(handle, kTestHandle1);
3497         requests.push_back({priority, std::move(cb)});
3498       });
3499 
3500   size_t result_cb_count = 0;
3501   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3502     EXPECT_EQ(fit::ok(), res);
3503     result_cb_count++;
3504   });
3505   ASSERT_EQ(requests.size(), 1u);
3506   requests[0].second(fit::ok());
3507   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kSink);
3508 
3509   // Source request is queued and request is sent.
3510   channel->RequestAclPriority(AclPriority::kSource, [&](auto res) {
3511     EXPECT_EQ(fit::ok(), res);
3512     result_cb_count++;
3513   });
3514   ASSERT_EQ(requests.size(), 2u);
3515   EXPECT_EQ(result_cb_count, 1u);
3516   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kSink);
3517 
3518   // Sink request is queued. It should receive an error since it is handled
3519   // after the channel is closed.
3520   channel->RequestAclPriority(AclPriority::kSink, [&](auto res) {
3521     EXPECT_TRUE(res.is_error());
3522     result_cb_count++;
3523   });
3524   ASSERT_EQ(requests.size(), 2u);
3525   EXPECT_EQ(result_cb_count, 1u);
3526   EXPECT_EQ(channel->requested_acl_priority(), AclPriority::kSink);
3527 
3528   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(NextCommandId()),
3529                          kHighPriority);
3530   // Closing channel will queue normal request.
3531   channel->Deactivate();
3532   EXPECT_FALSE(channel.is_alive());
3533 
3534   // Send res to source request. Second sink request should receive error res
3535   // too.
3536   requests[1].second(fit::ok());
3537   EXPECT_EQ(result_cb_count, 3u);
3538   ASSERT_EQ(requests.size(), 3u);
3539   EXPECT_EQ(requests[2].first, AclPriority::kNormal);
3540 
3541   // Send response to kNormal request sent on Deactivate().
3542   requests[2].second(fit::ok());
3543 }
3544 
3545 #ifndef NINSPECT
TEST_F(ChannelManagerMockAclChannelTest,InspectHierarchy)3546 TEST_F(ChannelManagerMockAclChannelTest, InspectHierarchy) {
3547   inspect::Inspector inspector;
3548   chanmgr()->AttachInspect(inspector.GetRoot(), "l2cap");
3549 
3550   chanmgr()->RegisterService(kSDP, kChannelParams, [](auto) {});
3551   auto services_matcher =
3552       AllOf(NodeMatches(NameMatches("services")),
3553             ChildrenMatch(ElementsAre(NodeMatches(
3554                 AllOf(NameMatches("service_0x0"),
3555                       PropertyList(ElementsAre(StringIs("psm", "SDP"))))))));
3556 
3557   QueueRegisterACL(kTestHandle1,
3558                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3559   RunUntilIdle();
3560 
3561   const auto conn_req_id = NextCommandId();
3562   const auto config_req_id = NextCommandId();
3563   EXPECT_ACL_PACKET_OUT_(OutboundConnectionRequest(conn_req_id), kHighPriority);
3564   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
3565                          kHighPriority);
3566   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
3567                          kHighPriority);
3568   Channel::WeakPtr dynamic_channel;
3569   auto channel_cb = [&dynamic_channel](l2cap::Channel::WeakPtr activated_chan) {
3570     dynamic_channel = std::move(activated_chan);
3571   };
3572   ActivateOutboundChannel(
3573       kTestPsm, kChannelParams, std::move(channel_cb), kTestHandle1, []() {});
3574   ReceiveAclDataPacket(InboundConnectionResponse(conn_req_id));
3575   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
3576   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
3577 
3578   auto signaling_chan_matcher = NodeMatches(AllOf(
3579       NameMatches("channel_0x2"),
3580       PropertyList(UnorderedElementsAre(StringIs("local_id", "0x0001"),
3581                                         StringIs("remote_id", "0x0001")))));
3582   auto smp_chan_matcher = NodeMatches(AllOf(
3583       NameMatches("channel_0x3"),
3584       PropertyList(UnorderedElementsAre(StringIs("local_id", "0x0007"),
3585                                         StringIs("remote_id", "0x0007")))));
3586   auto dyn_chan_matcher = NodeMatches(
3587       AllOf(NameMatches("channel_0x4"),
3588             PropertyList(UnorderedElementsAre(StringIs("local_id", "0x0040"),
3589                                               StringIs("remote_id", "0x9042"),
3590                                               StringIs("psm", "SDP")))));
3591   auto channels_matcher =
3592       AllOf(NodeMatches(NameMatches("channels")),
3593             ChildrenMatch(UnorderedElementsAre(
3594                 signaling_chan_matcher, smp_chan_matcher, dyn_chan_matcher)));
3595   auto link_matcher = AllOf(
3596       NodeMatches(NameMatches("logical_links")),
3597       ChildrenMatch(ElementsAre(AllOf(
3598           NodeMatches(AllOf(
3599               NameMatches("logical_link_0x1"),
3600               PropertyList(UnorderedElementsAre(
3601                   StringIs("handle", "0x0001"),
3602                   StringIs("link_type", "ACL"),
3603                   UintIs("flush_timeout_ms",
3604                          std::chrono::duration_cast<std::chrono::milliseconds>(
3605                              pw::chrono::SystemClock::duration::max())
3606                              .count()))))),
3607           ChildrenMatch(ElementsAre(channels_matcher))))));
3608 
3609   auto l2cap_node_matcher = AllOf(
3610       NodeMatches(NameMatches("l2cap")),
3611       ChildrenMatch(UnorderedElementsAre(link_matcher, services_matcher)));
3612 
3613   auto hierarchy = inspect::ReadFromVmo(inspector.DuplicateVmo()).take_value();
3614   EXPECT_THAT(hierarchy, ChildrenMatch(ElementsAre(l2cap_node_matcher)));
3615 
3616   // inspector must outlive ChannelManager
3617   chanmgr()->RemoveConnection(kTestHandle1);
3618 }
3619 #endif  // NINSPECT
3620 
TEST_F(ChannelManagerMockAclChannelTest,OutboundChannelWithFlushTimeoutInChannelParametersAndDelayedFlushTimeoutCallback)3621 TEST_F(
3622     ChannelManagerMockAclChannelTest,
3623     OutboundChannelWithFlushTimeoutInChannelParametersAndDelayedFlushTimeoutCallback) {
3624   QueueRegisterACL(kTestHandle1,
3625                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3626   RunUntilIdle();
3627 
3628   EXPECT_CMD_PACKET_OUT(test_device(),
3629                         WriteAutomaticFlushTimeoutPacket(
3630                             kTestHandle1, kExpectedFlushTimeoutParam));
3631 
3632   ChannelParameters chan_params;
3633   chan_params.flush_timeout = kFlushTimeout;
3634 
3635   Channel::WeakPtr channel;
3636   auto channel_cb = [&channel](l2cap::Channel::WeakPtr activated_chan) {
3637     channel = std::move(activated_chan);
3638   };
3639   SetUpOutboundChannelWithCallback(
3640       kLocalId, kRemoteId, /*closed_cb=*/DoNothing, chan_params, channel_cb);
3641   RunUntilIdle();
3642   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3643   // Channel should not be returned yet because setting flush timeout has not
3644   // completed yet.
3645   EXPECT_FALSE(channel.is_alive());
3646 
3647   // Completing the command should cause the channel to be returned.
3648   const auto kCommandComplete =
3649       CommandCompletePacket(hci_spec::kWriteAutomaticFlushTimeout,
3650                             pw::bluetooth::emboss::StatusCode::SUCCESS);
3651   test_device()->SendCommandChannelPacket(kCommandComplete);
3652   RunUntilIdle();
3653   ASSERT_TRUE(channel.is_alive());
3654   ASSERT_TRUE(channel->info().flush_timeout.has_value());
3655   EXPECT_EQ(channel->info().flush_timeout.value(), kFlushTimeout);
3656 
3657   EXPECT_ACL_PACKET_OUT_(StaticByteBuffer(
3658                              // ACL data header (handle: 1, packet boundary
3659                              // flag: kFirstFlushable, length: 6)
3660                              0x01,
3661                              0x20,
3662                              0x06,
3663                              0x00,
3664                              // L2CAP B-frame
3665                              0x02,
3666                              0x00,  // length: 2
3667                              LowerBits(kRemoteId),
3668                              UpperBits(kRemoteId),  // remote id
3669                              'h',
3670                              'i'),  // payload
3671                          kLowPriority);
3672   EXPECT_TRUE(channel->Send(NewBuffer('h', 'i')));
3673 }
3674 
TEST_F(ChannelManagerMockAclChannelTest,OutboundChannelWithFlushTimeoutInChannelParametersFailure)3675 TEST_F(ChannelManagerMockAclChannelTest,
3676        OutboundChannelWithFlushTimeoutInChannelParametersFailure) {
3677   QueueRegisterACL(kTestHandle1,
3678                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3679   RunUntilIdle();
3680 
3681   const auto kCommandCompleteError = CommandCompletePacket(
3682       hci_spec::kWriteAutomaticFlushTimeout,
3683       pw::bluetooth::emboss::StatusCode::UNSPECIFIED_ERROR);
3684   EXPECT_CMD_PACKET_OUT(test_device(),
3685                         WriteAutomaticFlushTimeoutPacket(
3686                             kTestHandle1, kExpectedFlushTimeoutParam),
3687                         &kCommandCompleteError);
3688 
3689   ChannelParameters chan_params;
3690   chan_params.flush_timeout = kFlushTimeout;
3691 
3692   auto channel = SetUpOutboundChannel(
3693       kLocalId, kRemoteId, /*closed_cb=*/DoNothing, chan_params);
3694   RunUntilIdle();
3695   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3696   // Flush timeout should not be set in channel info because setting a flush
3697   // timeout failed.
3698   EXPECT_FALSE(channel->info().flush_timeout.has_value());
3699 
3700   EXPECT_ACL_PACKET_OUT_(StaticByteBuffer(
3701                              // ACL data header (handle: 1, packet boundary
3702                              // flag: kFirstNonFlushable, length: 6)
3703                              0x01,
3704                              0x00,
3705                              0x06,
3706                              0x00,
3707                              // L2CAP B-frame
3708                              0x02,
3709                              0x00,  // length: 2
3710                              LowerBits(kRemoteId),
3711                              UpperBits(kRemoteId),  // remote id
3712                              'h',
3713                              'i'),  // payload
3714                          kLowPriority);
3715   EXPECT_TRUE(channel->Send(NewBuffer('h', 'i')));
3716 }
3717 
TEST_F(ChannelManagerMockAclChannelTest,InboundChannelWithFlushTimeoutInChannelParameters)3718 TEST_F(ChannelManagerMockAclChannelTest,
3719        InboundChannelWithFlushTimeoutInChannelParameters) {
3720   QueueRegisterACL(kTestHandle1,
3721                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3722   RunUntilIdle();
3723 
3724   const auto kCommandComplete =
3725       CommandCompletePacket(hci_spec::kWriteAutomaticFlushTimeout,
3726                             pw::bluetooth::emboss::StatusCode::SUCCESS);
3727   EXPECT_CMD_PACKET_OUT(test_device(),
3728                         WriteAutomaticFlushTimeoutPacket(
3729                             kTestHandle1, kExpectedFlushTimeoutParam),
3730                         &kCommandComplete);
3731 
3732   ChannelParameters chan_params;
3733   chan_params.flush_timeout = kFlushTimeout;
3734 
3735   Channel::WeakPtr channel;
3736   auto channel_cb = [&channel](l2cap::Channel::WeakPtr opened_chan) {
3737     channel = std::move(opened_chan);
3738     EXPECT_TRUE(channel->Activate(NopRxCallback, DoNothing));
3739   };
3740 
3741   EXPECT_TRUE(
3742       chanmgr()->RegisterService(kTestPsm, chan_params, std::move(channel_cb)));
3743 
3744   CommandId kPeerConnectionRequestId = 3;
3745   const auto config_req_id = NextCommandId();
3746 
3747   EXPECT_ACL_PACKET_OUT_(OutboundConnectionResponse(kPeerConnectionRequestId),
3748                          kHighPriority);
3749   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationRequest(config_req_id),
3750                          kHighPriority);
3751   EXPECT_ACL_PACKET_OUT_(OutboundConfigurationResponse(kPeerConfigRequestId),
3752                          kHighPriority);
3753 
3754   ReceiveAclDataPacket(InboundConnectionRequest(kPeerConnectionRequestId));
3755   ReceiveAclDataPacket(InboundConfigurationRequest(kPeerConfigRequestId));
3756   ReceiveAclDataPacket(InboundConfigurationResponse(config_req_id));
3757 
3758   RunUntilIdle();
3759   EXPECT_TRUE(AllExpectedPacketsSent());
3760   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3761   ASSERT_TRUE(channel.is_alive());
3762   ASSERT_TRUE(channel->info().flush_timeout.has_value());
3763   EXPECT_EQ(channel->info().flush_timeout.value(), kFlushTimeout);
3764 
3765   EXPECT_ACL_PACKET_OUT_(StaticByteBuffer(
3766                              // ACL data header (handle: 1, packet boundary
3767                              // flag: kFirstFlushable, length: 6)
3768                              0x01,
3769                              0x20,
3770                              0x06,
3771                              0x00,
3772                              // L2CAP B-frame
3773                              0x02,
3774                              0x00,  // length: 2
3775                              LowerBits(kRemoteId),
3776                              UpperBits(kRemoteId),  // remote id
3777                              'h',
3778                              'i'),  // payload
3779                          kLowPriority);
3780   EXPECT_TRUE(channel->Send(NewBuffer('h', 'i')));
3781 }
3782 
TEST_F(ChannelManagerMockAclChannelTest,FlushableChannelAndNonFlushableChannelOnSameLink)3783 TEST_F(ChannelManagerMockAclChannelTest,
3784        FlushableChannelAndNonFlushableChannelOnSameLink) {
3785   QueueRegisterACL(kTestHandle1,
3786                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3787   RunUntilIdle();
3788   auto nonflushable_channel = SetUpOutboundChannel();
3789   auto flushable_channel = SetUpOutboundChannel(kLocalId + 1, kRemoteId + 1);
3790 
3791   const auto kCommandComplete =
3792       CommandCompletePacket(hci_spec::kWriteAutomaticFlushTimeout,
3793                             pw::bluetooth::emboss::StatusCode::SUCCESS);
3794   EXPECT_CMD_PACKET_OUT(test_device(),
3795                         WriteAutomaticFlushTimeoutPacket(
3796                             kTestHandle1, kExpectedFlushTimeoutParam),
3797                         &kCommandComplete);
3798 
3799   flushable_channel->SetBrEdrAutomaticFlushTimeout(
3800       kFlushTimeout, [](auto res) { EXPECT_EQ(fit::ok(), res); });
3801   RunUntilIdle();
3802   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3803   EXPECT_FALSE(nonflushable_channel->info().flush_timeout.has_value());
3804   ASSERT_TRUE(flushable_channel->info().flush_timeout.has_value());
3805   EXPECT_EQ(flushable_channel->info().flush_timeout.value(), kFlushTimeout);
3806 
3807   EXPECT_ACL_PACKET_OUT_(
3808       StaticByteBuffer(
3809           // ACL data header (handle: 1, packet boundary flag: kFirstFlushable,
3810           // length: 6)
3811           0x01,
3812           0x20,
3813           0x06,
3814           0x00,
3815           // L2CAP B-frame
3816           0x02,
3817           0x00,  // length: 2
3818           LowerBits(flushable_channel->remote_id()),
3819           UpperBits(flushable_channel->remote_id()),  // remote id
3820           'h',
3821           'i'),  // payload
3822       kLowPriority);
3823   EXPECT_TRUE(flushable_channel->Send(NewBuffer('h', 'i')));
3824 
3825   EXPECT_ACL_PACKET_OUT_(
3826       StaticByteBuffer(
3827           // ACL data header (handle: 1, packet boundary flag:
3828           // kFirstNonFlushable, length: 6)
3829           0x01,
3830           0x00,
3831           0x06,
3832           0x00,
3833           // L2CAP B-frame
3834           0x02,
3835           0x00,  // length: 2
3836           LowerBits(nonflushable_channel->remote_id()),
3837           UpperBits(nonflushable_channel->remote_id()),  // remote id
3838           'h',
3839           'i'),  // payload
3840       kLowPriority);
3841   EXPECT_TRUE(nonflushable_channel->Send(NewBuffer('h', 'i')));
3842 }
3843 
TEST_F(ChannelManagerMockAclChannelTest,SettingFlushTimeoutFails)3844 TEST_F(ChannelManagerMockAclChannelTest, SettingFlushTimeoutFails) {
3845   QueueRegisterACL(kTestHandle1,
3846                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3847   RunUntilIdle();
3848   auto channel = SetUpOutboundChannel();
3849 
3850   const auto kCommandComplete = CommandCompletePacket(
3851       hci_spec::kWriteAutomaticFlushTimeout,
3852       pw::bluetooth::emboss::StatusCode::UNKNOWN_CONNECTION_ID);
3853   EXPECT_CMD_PACKET_OUT(test_device(),
3854                         WriteAutomaticFlushTimeoutPacket(
3855                             kTestHandle1, kExpectedFlushTimeoutParam),
3856                         &kCommandComplete);
3857 
3858   channel->SetBrEdrAutomaticFlushTimeout(kFlushTimeout, [](auto res) {
3859     EXPECT_EQ(
3860         ToResult(pw::bluetooth::emboss::StatusCode::UNKNOWN_CONNECTION_ID),
3861         res);
3862   });
3863   RunUntilIdle();
3864   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3865 
3866   EXPECT_ACL_PACKET_OUT_(StaticByteBuffer(
3867                              // ACL data header (handle: 1, packet boundary
3868                              // flag: kFirstNonFlushable, length: 6)
3869                              0x01,
3870                              0x00,
3871                              0x06,
3872                              0x00,
3873                              // L2CAP B-frame
3874                              0x02,
3875                              0x00,  // length: 2
3876                              LowerBits(kRemoteId),
3877                              UpperBits(kRemoteId),  // remote id
3878                              'h',
3879                              'i'),  // payload
3880                          kLowPriority);
3881   EXPECT_TRUE(channel->Send(NewBuffer('h', 'i')));
3882 }
3883 
TEST_F(ChannelManagerMockAclChannelTest,StartAndStopA2dpOffloadSuccess)3884 TEST_F(ChannelManagerMockAclChannelTest, StartAndStopA2dpOffloadSuccess) {
3885   QueueRegisterACL(kTestHandle1,
3886                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3887   RunUntilIdle();
3888 
3889   A2dpOffloadManager::Configuration config = BuildConfiguration();
3890   Channel::WeakPtr channel = SetUpOutboundChannel();
3891 
3892   const auto command_complete =
3893       CommandCompletePacket(hci_android::kA2dpOffloadCommand,
3894                             pw::bluetooth::emboss::StatusCode::SUCCESS);
3895   EXPECT_CMD_PACKET_OUT(test_device(),
3896                         StartA2dpOffloadRequest(config,
3897                                                 channel->link_handle(),
3898                                                 channel->remote_id(),
3899                                                 channel->max_tx_sdu_size()),
3900                         &command_complete);
3901 
3902   std::optional<hci::Result<>> result;
3903   channel->StartA2dpOffload(config, [&result](auto res) {
3904     EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::SUCCESS), res);
3905     result = res;
3906   });
3907   RunUntilIdle();
3908   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3909   ASSERT_TRUE(result.has_value());
3910   EXPECT_TRUE(result->is_ok());
3911 
3912   EXPECT_CMD_PACKET_OUT(
3913       test_device(), StopA2dpOffloadRequest(), &command_complete);
3914 
3915   result.reset();
3916   channel->StopA2dpOffload([&result](auto res) {
3917     EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::SUCCESS), res);
3918     result = res;
3919   });
3920   RunUntilIdle();
3921   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3922   ASSERT_TRUE(result.has_value());
3923   EXPECT_TRUE(result->is_ok());
3924 
3925   EXPECT_CMD_PACKET_OUT(test_device(),
3926                         StartA2dpOffloadRequest(config,
3927                                                 channel->link_handle(),
3928                                                 channel->remote_id(),
3929                                                 channel->max_tx_sdu_size()),
3930                         &command_complete);
3931 
3932   result.reset();
3933   channel->StartA2dpOffload(config, [&result](auto res) {
3934     EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::SUCCESS), res);
3935     result = res;
3936   });
3937   RunUntilIdle();
3938   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3939   ASSERT_TRUE(result.has_value());
3940   EXPECT_TRUE(result->is_ok());
3941 
3942   // Stop A2DP offload command sent on channel destruction
3943   EXPECT_CMD_PACKET_OUT(
3944       test_device(), StopA2dpOffloadRequest(), &command_complete);
3945 }
3946 
TEST_F(ChannelManagerMockAclChannelTest,DisconnectChannelAfterA2dpOffloadStarted)3947 TEST_F(ChannelManagerMockAclChannelTest,
3948        DisconnectChannelAfterA2dpOffloadStarted) {
3949   QueueRegisterACL(kTestHandle1,
3950                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3951   RunUntilIdle();
3952 
3953   A2dpOffloadManager::Configuration config = BuildConfiguration();
3954   Channel::WeakPtr channel = SetUpOutboundChannel();
3955 
3956   const auto command_complete =
3957       CommandCompletePacket(hci_android::kA2dpOffloadCommand,
3958                             pw::bluetooth::emboss::StatusCode::SUCCESS);
3959   EXPECT_CMD_PACKET_OUT(test_device(),
3960                         StartA2dpOffloadRequest(config,
3961                                                 channel->link_handle(),
3962                                                 channel->remote_id(),
3963                                                 channel->max_tx_sdu_size()),
3964                         &command_complete);
3965 
3966   std::optional<hci::Result<>> result;
3967   channel->StartA2dpOffload(config, [&result](auto res) {
3968     EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::SUCCESS), res);
3969     result = res;
3970   });
3971   RunUntilIdle();
3972   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3973   ASSERT_TRUE(result.has_value());
3974   EXPECT_TRUE(result->is_ok());
3975 
3976   ASSERT_TRUE(channel.is_alive());
3977   const auto disconn_req_id = NextCommandId();
3978   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(disconn_req_id),
3979                          kHighPriority);
3980   // Stop A2DP offload command sent on channel close
3981   EXPECT_CMD_PACKET_OUT(
3982       test_device(), StopA2dpOffloadRequest(), &command_complete);
3983   channel->Deactivate();
3984   ASSERT_FALSE(channel.is_alive());
3985 
3986   RunUntilIdle();
3987   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
3988 }
3989 
TEST_F(ChannelManagerMockAclChannelTest,DisconnectChannelWhileA2dpOffloadStarting)3990 TEST_F(ChannelManagerMockAclChannelTest,
3991        DisconnectChannelWhileA2dpOffloadStarting) {
3992   QueueRegisterACL(kTestHandle1,
3993                    pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3994   RunUntilIdle();
3995 
3996   A2dpOffloadManager::Configuration config = BuildConfiguration();
3997   Channel::WeakPtr channel = SetUpOutboundChannel();
3998 
3999   const auto command_complete =
4000       CommandCompletePacket(hci_android::kA2dpOffloadCommand,
4001                             pw::bluetooth::emboss::StatusCode::SUCCESS);
4002   EXPECT_CMD_PACKET_OUT(test_device(),
4003                         StartA2dpOffloadRequest(config,
4004                                                 channel->link_handle(),
4005                                                 channel->remote_id(),
4006                                                 channel->max_tx_sdu_size()),
4007                         &command_complete);
4008 
4009   std::optional<hci::Result<>> result;
4010   channel->StartA2dpOffload(config, [&result](auto res) {
4011     EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::SUCCESS), res);
4012     result = res;
4013   });
4014   EXPECT_FALSE(result.has_value());
4015   ASSERT_TRUE(channel.is_alive());
4016 
4017   const auto disconn_req_id = NextCommandId();
4018   EXPECT_ACL_PACKET_OUT_(OutboundDisconnectionRequest(disconn_req_id),
4019                          kHighPriority);
4020   // Stop A2DP offload command sent on channel close
4021   EXPECT_CMD_PACKET_OUT(
4022       test_device(), StopA2dpOffloadRequest(), &command_complete);
4023   channel->Deactivate();
4024   ASSERT_FALSE(channel.is_alive());
4025 
4026   RunUntilIdle();
4027   EXPECT_TRUE(test_device()->AllExpectedCommandPacketsSent());
4028 }
4029 
TEST_F(ChannelManagerMockAclChannelTest,SignalLinkErrorStopsDeliveryOfBufferedRxPackets)4030 TEST_F(ChannelManagerMockAclChannelTest,
4031        SignalLinkErrorStopsDeliveryOfBufferedRxPackets) {
4032   // LE-U link
4033   LEFixedChannels fixed_channels =
4034       RegisterLE(kTestHandle1, pw::bluetooth::emboss::ConnectionRole::CENTRAL);
4035 
4036   // Queue 2 packets to be delivers on channel activation.
4037   StaticByteBuffer payload_0(0x00);
4038   ReceiveAclDataPacket(StaticByteBuffer(
4039       // ACL data header (starting fragment)
4040       0x01,
4041       0x00,  // connection handle + flags
4042       0x05,
4043       0x00,  // Length
4044       // L2CAP B-frame
4045       0x01,
4046       0x00,  // Length
4047       LowerBits(kATTChannelId),
4048       UpperBits(kATTChannelId),
4049       // Payload
4050       payload_0[0]));
4051   ReceiveAclDataPacket(StaticByteBuffer(
4052       // ACL data header (starting fragment)
4053       0x01,
4054       0x00,  // connection handle + flags
4055       0x05,
4056       0x00,  // Length
4057       // L2CAP B-frame
4058       0x01,
4059       0x00,  // Length
4060       LowerBits(kATTChannelId),
4061       UpperBits(kATTChannelId),
4062       // Payload
4063       0x01));
4064   RunUntilIdle();
4065 
4066   bool closed_called = false;
4067   auto closed_cb = [&closed_called] { closed_called = true; };
4068 
4069   int rx_count = 0;
4070   auto rx_callback = [&](ByteBufferPtr payload) {
4071     rx_count++;
4072     if (rx_count == 1) {
4073       EXPECT_THAT(*payload, BufferEq(payload_0));
4074       // This should stop delivery of the second packet.
4075       fixed_channels.att->SignalLinkError();
4076       return;
4077     }
4078   };
4079   ASSERT_TRUE(fixed_channels.att->Activate(std::move(rx_callback), closed_cb));
4080   RunUntilIdle();
4081   EXPECT_EQ(rx_count, 1);
4082   EXPECT_TRUE(closed_called);
4083 
4084   // Ensure the link is removed.
4085   chanmgr()->RemoveConnection(kTestHandle1);
4086   RunUntilIdle();
4087 }
4088 
TEST_F(ChannelManagerRealAclChannelTest,InboundRfcommChannelFailsWithPsmNotSupported)4089 TEST_F(ChannelManagerRealAclChannelTest,
4090        InboundRfcommChannelFailsWithPsmNotSupported) {
4091   constexpr l2cap::Psm kPsm = l2cap::kRFCOMM;
4092   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4093 
4094   QueueAclConnection(kTestHandle1);
4095   RunUntilIdle();
4096   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4097 
4098   const l2cap::CommandId kPeerConnReqId = 1;
4099 
4100   // Incoming connection refused, RFCOMM is not routed.
4101   EXPECT_ACL_PACKET_OUT(test_device(),
4102                         l2cap::testing::AclConnectionRsp(
4103                             kPeerConnReqId,
4104                             kTestHandle1,
4105                             kRemoteId,
4106                             /*dst_id=*/0x0000,
4107                             l2cap::ConnectionResult::kPsmNotSupported));
4108 
4109   test_device()->SendACLDataChannelPacket(l2cap::testing::AclConnectionReq(
4110       kPeerConnReqId, kTestHandle1, kRemoteId, kPsm));
4111 
4112   RunUntilIdle();
4113 }
4114 
TEST_F(ChannelManagerRealAclChannelTest,InboundPacketQueuedAfterChannelOpenIsNotDropped)4115 TEST_F(ChannelManagerRealAclChannelTest,
4116        InboundPacketQueuedAfterChannelOpenIsNotDropped) {
4117   constexpr l2cap::Psm kPsm = l2cap::kSDP;
4118   constexpr l2cap::ChannelId kLocalId = 0x0040;
4119   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4120 
4121   QueueAclConnection(kTestHandle1);
4122   RunUntilIdle();
4123   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4124 
4125   Channel::WeakPtr channel;
4126   auto chan_cb = [&](l2cap::Channel::WeakPtr activated_chan) {
4127     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4128     channel = std::move(activated_chan);
4129   };
4130 
4131   chanmgr()->RegisterService(kPsm, kChannelParameters, std::move(chan_cb));
4132   RunUntilIdle();
4133 
4134   constexpr l2cap::CommandId kConnectionReqId = 1;
4135   constexpr l2cap::CommandId kPeerConfigReqId = 6;
4136   const l2cap::CommandId kConfigReqId = NextCommandId();
4137   EXPECT_ACL_PACKET_OUT(
4138       test_device(),
4139       l2cap::testing::AclConnectionRsp(
4140           kConnectionReqId, kTestHandle1, kRemoteId, kLocalId));
4141   EXPECT_ACL_PACKET_OUT(
4142       test_device(),
4143       l2cap::testing::AclConfigReq(
4144           kConfigReqId, kTestHandle1, kRemoteId, kChannelParameters));
4145   test_device()->SendACLDataChannelPacket(l2cap::testing::AclConnectionReq(
4146       kConnectionReqId, kTestHandle1, kRemoteId, kPsm));
4147 
4148   // Config negotiation will not complete yet.
4149   RunUntilIdle();
4150 
4151   // Remaining config negotiation will be added to dispatch loop.
4152   EXPECT_ACL_PACKET_OUT(
4153       test_device(),
4154       l2cap::testing::AclConfigRsp(
4155           kPeerConfigReqId, kTestHandle1, kRemoteId, kChannelParameters));
4156   test_device()->SendACLDataChannelPacket(l2cap::testing::AclConfigReq(
4157       kPeerConfigReqId, kTestHandle1, kLocalId, kChannelParameters));
4158   test_device()->SendACLDataChannelPacket(l2cap::testing::AclConfigRsp(
4159       kConfigReqId, kTestHandle1, kLocalId, kChannelParameters));
4160 
4161   // Queue up a data packet for the new channel before the channel configuration
4162   // has been processed.
4163   ASSERT_FALSE(channel.is_alive());
4164   test_device()->SendACLDataChannelPacket(StaticByteBuffer(
4165       // ACL data header (handle: 1, length 8)
4166       0x01,
4167       0x00,
4168       0x08,
4169       0x00,
4170 
4171       // L2CAP B-frame: (length: 4, channel-id: 0x0040 (kLocalId))
4172       0x04,
4173       0x00,
4174       0x40,
4175       0x00,
4176       0xf0,
4177       0x9f,
4178       0x94,
4179       0xb0));
4180 
4181   // Run until the channel opens and the packet is written to the socket buffer.
4182   RunUntilIdle();
4183   ASSERT_TRUE(channel.is_alive());
4184 
4185   std::vector<ByteBufferPtr> rx_packets;
4186   auto rx_cb = [&rx_packets](ByteBufferPtr sdu) {
4187     rx_packets.push_back(std::move(sdu));
4188   };
4189   ASSERT_TRUE(channel->Activate(rx_cb, DoNothing));
4190   RunUntilIdle();
4191   ASSERT_EQ(rx_packets.size(), 1u);
4192   ASSERT_EQ(rx_packets[0]->size(), 4u);
4193   EXPECT_EQ("��", rx_packets[0]->view(0, 4u).AsString());
4194 }
4195 
TEST_F(ChannelManagerRealAclChannelTest,NegotiateChannelParametersOnOutboundL2capChannel)4196 TEST_F(ChannelManagerRealAclChannelTest,
4197        NegotiateChannelParametersOnOutboundL2capChannel) {
4198   constexpr l2cap::Psm kPsm = l2cap::kAVDTP;
4199   constexpr l2cap::ChannelId kLocalId = 0x0040;
4200   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4201   constexpr uint16_t kMtu = l2cap::kMinACLMTU;
4202 
4203   l2cap::ChannelParameters chan_params;
4204   chan_params.mode =
4205       l2cap::RetransmissionAndFlowControlMode::kEnhancedRetransmission;
4206   chan_params.max_rx_sdu_size = kMtu;
4207 
4208   QueueAclConnection(kTestHandle1);
4209   RunUntilIdle();
4210   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4211 
4212   Channel::WeakPtr channel;
4213   auto chan_cb = [&](l2cap::Channel::WeakPtr activated_chan) {
4214     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4215     channel = std::move(activated_chan);
4216   };
4217 
4218   QueueOutboundL2capConnection(kTestHandle1,
4219                                kPsm,
4220                                kLocalId,
4221                                kRemoteId,
4222                                chan_cb,
4223                                chan_params,
4224                                chan_params);
4225 
4226   RunUntilIdle();
4227   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4228   ASSERT_TRUE(channel.is_alive());
4229   EXPECT_EQ(kTestHandle1, channel->link_handle());
4230   EXPECT_EQ(*chan_params.max_rx_sdu_size, channel->max_rx_sdu_size());
4231   EXPECT_EQ(*chan_params.mode, channel->mode());
4232 }
4233 
TEST_F(ChannelManagerRealAclChannelTest,NegotiateChannelParametersOnInboundChannel)4234 TEST_F(ChannelManagerRealAclChannelTest,
4235        NegotiateChannelParametersOnInboundChannel) {
4236   constexpr l2cap::Psm kPsm = l2cap::kAVDTP;
4237   constexpr l2cap::ChannelId kLocalId = 0x0040;
4238   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4239 
4240   l2cap::ChannelParameters chan_params;
4241   chan_params.mode =
4242       l2cap::RetransmissionAndFlowControlMode::kEnhancedRetransmission;
4243   chan_params.max_rx_sdu_size = l2cap::kMinACLMTU;
4244 
4245   QueueAclConnection(kTestHandle1);
4246   RunUntilIdle();
4247   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4248 
4249   Channel::WeakPtr channel;
4250   auto chan_cb = [&](l2cap::Channel::WeakPtr activated_chan) {
4251     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4252     channel = std::move(activated_chan);
4253   };
4254   chanmgr()->RegisterService(kPsm, chan_params, chan_cb);
4255 
4256   QueueInboundL2capConnection(
4257       kTestHandle1, kPsm, kLocalId, kRemoteId, chan_params, chan_params);
4258 
4259   RunUntilIdle();
4260   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4261   ASSERT_TRUE(channel.is_alive());
4262   EXPECT_EQ(*chan_params.max_rx_sdu_size, channel->max_rx_sdu_size());
4263   EXPECT_EQ(*chan_params.mode, channel->mode());
4264 }
4265 
TEST_F(ChannelManagerRealAclChannelTest,RequestConnectionParameterUpdateAndReceiveResponse)4266 TEST_F(ChannelManagerRealAclChannelTest,
4267        RequestConnectionParameterUpdateAndReceiveResponse) {
4268   // Valid parameter values
4269   constexpr uint16_t kIntervalMin = 6;
4270   constexpr uint16_t kIntervalMax = 7;
4271   constexpr uint16_t kPeripheralLatency = 1;
4272   constexpr uint16_t kTimeoutMult = 10;
4273   const hci_spec::LEPreferredConnectionParameters kParams(
4274       kIntervalMin, kIntervalMax, kPeripheralLatency, kTimeoutMult);
4275 
4276   QueueLEConnection(kTestHandle1,
4277                     pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
4278 
4279   std::optional<bool> accepted;
4280   auto request_cb = [&accepted](bool cb_accepted) { accepted = cb_accepted; };
4281 
4282   // Receive "Accepted" Response:
4283   l2cap::CommandId param_update_req_id = NextCommandId();
4284   EXPECT_ACL_PACKET_OUT(
4285       test_device(),
4286       l2cap::testing::AclConnectionParameterUpdateReq(param_update_req_id,
4287                                                       kTestHandle1,
4288                                                       kIntervalMin,
4289                                                       kIntervalMax,
4290                                                       kPeripheralLatency,
4291                                                       kTimeoutMult));
4292   chanmgr()->RequestConnectionParameterUpdate(
4293       kTestHandle1, kParams, request_cb);
4294   RunUntilIdle();
4295   EXPECT_FALSE(accepted.has_value());
4296 
4297   test_device()->SendACLDataChannelPacket(
4298       l2cap::testing::AclConnectionParameterUpdateRsp(
4299           param_update_req_id,
4300           kTestHandle1,
4301           l2cap::ConnectionParameterUpdateResult::kAccepted));
4302   RunUntilIdle();
4303   ASSERT_TRUE(accepted.has_value());
4304   EXPECT_TRUE(accepted.value());
4305   accepted.reset();
4306 }
4307 
TEST_F(ChannelManagerRealAclChannelTest,AddLEConnectionReturnsFixedChannels)4308 TEST_F(ChannelManagerRealAclChannelTest, AddLEConnectionReturnsFixedChannels) {
4309   auto channels = QueueLEConnection(
4310       kTestHandle1, pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
4311   ASSERT_TRUE(channels.att.is_alive());
4312   EXPECT_EQ(l2cap::kATTChannelId, channels.att->id());
4313   ASSERT_TRUE(channels.smp.is_alive());
4314   EXPECT_EQ(l2cap::kLESMPChannelId, channels.smp->id());
4315 }
4316 
TEST_F(ChannelManagerRealAclChannelTest,OutboundChannelIsInvalidWhenL2capFailsToOpenChannel)4317 TEST_F(ChannelManagerRealAclChannelTest,
4318        OutboundChannelIsInvalidWhenL2capFailsToOpenChannel) {
4319   constexpr l2cap::Psm kPsm = l2cap::kAVCTP;
4320 
4321   // Don't register any links. This should cause outbound channels to fail.
4322   bool chan_cb_called = false;
4323   auto chan_cb = [&chan_cb_called](auto chan) {
4324     chan_cb_called = true;
4325     EXPECT_FALSE(chan.is_alive());
4326   };
4327 
4328   chanmgr()->OpenL2capChannel(
4329       kTestHandle1, kPsm, kChannelParameters, std::move(chan_cb));
4330 
4331   RunUntilIdle();
4332 
4333   EXPECT_TRUE(chan_cb_called);
4334 }
4335 
TEST_F(ChannelManagerRealAclChannelTest,SignalingChannelAndOneDynamicChannel)4336 TEST_F(ChannelManagerRealAclChannelTest, SignalingChannelAndOneDynamicChannel) {
4337   constexpr l2cap::Psm kPsm = l2cap::kSDP;
4338   constexpr l2cap::ChannelId kLocalId = 0x0040;
4339   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4340 
4341   // L2CAP connection request/response, config request, config response
4342   constexpr size_t kChannelCreationPacketCount = 3;
4343 
4344   QueueAclConnection(kTestHandle1);
4345   RunUntilIdle();
4346   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4347 
4348   l2cap::Channel::WeakPtr channel;
4349   auto chan_cb = [&](auto activated_chan) {
4350     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4351     channel = std::move(activated_chan);
4352   };
4353   QueueOutboundL2capConnection(
4354       kTestHandle1, kPsm, kLocalId, kRemoteId, std::move(chan_cb));
4355 
4356   RunUntilIdle();
4357   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4358   EXPECT_TRUE(channel.is_alive());
4359   channel->Activate(NopRxCallback, DoNothing);
4360 
4361   // Free up the buffer space from packets sent while creating |channel|
4362   test_device()->SendCommandChannelPacket(NumberOfCompletedPacketsPacket(
4363       kTestHandle1,
4364       kConnectionCreationPacketCount + kChannelCreationPacketCount));
4365 
4366   // Fill up BR/EDR controller buffer then queue one additional packet
4367   for (size_t i = 0; i <= kBufferMaxNumPackets; i++) {
4368     // Last packet should remain queued
4369     if (i < kBufferMaxNumPackets) {
4370       const StaticByteBuffer kPacket(
4371           // ACL data header (handle: 0, length 1)
4372           0x01,
4373           0x00,
4374           0x05,
4375           0x00,
4376           // L2CAP B-frame: (length: 1, channel-id)
4377           0x01,
4378           0x00,
4379           LowerBits(kRemoteId),
4380           UpperBits(kRemoteId),
4381           // L2CAP payload
4382           0x01);
4383       EXPECT_ACL_PACKET_OUT(test_device(), kPacket);
4384     }
4385     // Create PDU to send on dynamic channel
4386     EXPECT_TRUE(channel->Send(NewBuffer(0x01)));
4387     RunUntilIdle();
4388   }
4389   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4390 
4391   // Send out last packet
4392   EXPECT_ACL_PACKET_OUT(test_device(),
4393                         StaticByteBuffer(
4394                             // ACL data header (handle: 0, length 1)
4395                             0x01,
4396                             0x00,
4397                             0x05,
4398                             0x00,
4399                             // L2CAP B-frame: (length: 4, channel-id)
4400                             0x01,
4401                             0x00,
4402                             LowerBits(kRemoteId),
4403                             UpperBits(kRemoteId),
4404                             // L2CAP payload
4405                             0x01));
4406   test_device()->SendCommandChannelPacket(
4407       bt::testing::NumberOfCompletedPacketsPacket(kTestHandle1, 1));
4408   RunUntilIdle();
4409 
4410   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4411 }
4412 
TEST_F(ChannelManagerRealAclChannelTest,SignalingChannelAndTwoDynamicChannels)4413 TEST_F(ChannelManagerRealAclChannelTest,
4414        SignalingChannelAndTwoDynamicChannels) {
4415   constexpr l2cap::Psm kPsm0 = l2cap::kAVCTP;
4416   constexpr l2cap::ChannelId kLocalId0 = 0x0040;
4417   constexpr l2cap::ChannelId kRemoteId0 = 0x9042;
4418 
4419   constexpr l2cap::Psm kPsm1 = l2cap::kAVDTP;
4420   constexpr l2cap::ChannelId kLocalId1 = 0x0041;
4421   constexpr l2cap::ChannelId kRemoteId1 = 0x9043;
4422 
4423   // L2CAP connection request/response, config request, config response
4424   constexpr size_t kChannelCreationPacketCount = 3;
4425 
4426   QueueAclConnection(kTestHandle1);
4427   RunUntilIdle();
4428   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4429 
4430   l2cap::Channel::WeakPtr channel0;
4431   auto chan_cb0 = [&](auto activated_chan) {
4432     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4433     channel0 = std::move(activated_chan);
4434   };
4435   QueueOutboundL2capConnection(
4436       kTestHandle1, kPsm0, kLocalId0, kRemoteId0, std::move(chan_cb0));
4437 
4438   RunUntilIdle();
4439   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4440   ASSERT_TRUE(channel0.is_alive());
4441   ASSERT_TRUE(channel0->Activate(NopRxCallback, DoNothing));
4442 
4443   l2cap::Channel::WeakPtr channel1;
4444   auto chan_cb1 = [&](auto activated_chan) {
4445     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4446     channel1 = std::move(activated_chan);
4447   };
4448   QueueOutboundL2capConnection(
4449       kTestHandle1, kPsm1, kLocalId1, kRemoteId1, std::move(chan_cb1));
4450 
4451   // Free up the buffer space from packets sent while creating |channel0|
4452   test_device()->SendCommandChannelPacket(NumberOfCompletedPacketsPacket(
4453       kTestHandle1, kChannelCreationPacketCount));
4454   RunUntilIdle();
4455 
4456   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4457   EXPECT_TRUE(channel1.is_alive());
4458   ASSERT_TRUE(channel1->Activate(NopRxCallback, DoNothing));
4459 
4460   // Free up the buffer space from packets sent while creating |channel1|
4461   test_device()->SendCommandChannelPacket(NumberOfCompletedPacketsPacket(
4462       kTestHandle1,
4463       kConnectionCreationPacketCount + kChannelCreationPacketCount));
4464   RunUntilIdle();
4465 
4466   // Queue size should be equal to or larger than |num_queued_packets| to ensure
4467   // that all packets get queued and sent
4468   uint16_t num_queued_packets = 5;
4469   EXPECT_TRUE(num_queued_packets <= kDefaultTxMaxQueuedCount);
4470 
4471   // Queue 15 packets in total, distributed between the two channels
4472   // Fill up BR/EDR controller buffer then queue 5 additional packets
4473   for (size_t i = 0; i < kBufferMaxNumPackets + num_queued_packets; i++) {
4474     Channel::WeakPtr channel = (i % 2) ? channel1 : channel0;
4475     ChannelId channel_id = (i % 2) ? kRemoteId1 : kRemoteId0;
4476 
4477     const StaticByteBuffer kPacket(
4478         // ACL data header (handle: 1, length 5)
4479         0x01,
4480         0x00,
4481         0x05,
4482         0x00,
4483         // L2CAP B-frame: (length: 1, channel_id)
4484         0x01,
4485         0x00,
4486         LowerBits(channel_id),
4487         UpperBits(channel_id),
4488         // L2CAP payload
4489         0x01);
4490     EXPECT_ACL_PACKET_OUT(test_device(), kPacket);
4491 
4492     // Create PDU to send on dynamic channel
4493     EXPECT_TRUE(channel->Send(NewBuffer(0x01)));
4494     RunUntilIdle();
4495   }
4496   EXPECT_FALSE(test_device()->AllExpectedDataPacketsSent());
4497 
4498   // Notify the processed packets with a Number Of Completed Packet HCI event
4499   // This should cause the remaining 5 packets to be sent
4500   test_device()->SendCommandChannelPacket(
4501       NumberOfCompletedPacketsPacket(kTestHandle1, 5));
4502   RunUntilIdle();
4503   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4504 }
4505 
TEST_F(ChannelManagerRealAclChannelTest,ChannelMaximumQueueSize)4506 TEST_F(ChannelManagerRealAclChannelTest, ChannelMaximumQueueSize) {
4507   constexpr l2cap::Psm kPsm = l2cap::kSDP;
4508   constexpr l2cap::ChannelId kLocalId = 0x0040;
4509   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4510 
4511   // L2CAP connection request/response, config request, config response
4512   constexpr size_t kChannelCreationPacketCount = 3;
4513 
4514   QueueAclConnection(kTestHandle1);
4515   RunUntilIdle();
4516   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4517 
4518   l2cap::Channel::WeakPtr channel;
4519   auto chan_cb = [&](auto activated_chan) {
4520     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4521     channel = std::move(activated_chan);
4522   };
4523   QueueOutboundL2capConnection(
4524       kTestHandle1, kPsm, kLocalId, kRemoteId, std::move(chan_cb));
4525 
4526   RunUntilIdle();
4527   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4528   EXPECT_TRUE(channel.is_alive());
4529   channel->Activate(NopRxCallback, DoNothing);
4530 
4531   // Free up the buffer space from packets sent while creating |channel|
4532   test_device()->SendCommandChannelPacket(NumberOfCompletedPacketsPacket(
4533       kTestHandle1,
4534       kConnectionCreationPacketCount + kChannelCreationPacketCount));
4535 
4536   // Set maximum PDU queue size for |channel|. Queue size should be less than
4537   // |num_queued_packets| to ensure that some packets are dropped in order to
4538   // test maximum queue size behaviour
4539   const uint16_t kTxMaxQueuedCount = 10;
4540   channel->set_max_tx_queued(kTxMaxQueuedCount);
4541   uint16_t num_queued_packets = 20;
4542 
4543   // Fill up BR/EDR controller buffer then queue 20 additional packets. 10 of
4544   // these packets will be dropped since the maximum PDU queue size
4545   // |kTxMaxQueuedCount| is 10
4546   for (size_t i = 0; i < kBufferMaxNumPackets + num_queued_packets; i++) {
4547     if (i < kBufferMaxNumPackets + channel->max_tx_queued()) {
4548       const StaticByteBuffer kPacket(
4549           // ACL data header (handle: 0, length 1)
4550           0x01,
4551           0x00,
4552           0x05,
4553           0x00,
4554           // L2CAP B-frame: (length: 1, channel-id)
4555           0x01,
4556           0x00,
4557           LowerBits(kRemoteId),
4558           UpperBits(kRemoteId),
4559           // L2CAP payload
4560           0x01);
4561 
4562       EXPECT_ACL_PACKET_OUT(test_device(), kPacket);
4563     }
4564 
4565     // Create PDU to send on dynamic channel
4566     EXPECT_TRUE(channel->Send(NewBuffer(0x01)));
4567     RunUntilIdle();
4568   }
4569   EXPECT_FALSE(test_device()->AllExpectedDataPacketsSent());
4570 
4571   // Notify the processed packets with a Number Of Completed Packet HCI event
4572   // This should cause the remaining 10 packets to be sent
4573   test_device()->SendCommandChannelPacket(
4574       bt::testing::NumberOfCompletedPacketsPacket(kTestHandle1, 10));
4575   RunUntilIdle();
4576   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4577 }
4578 
4579 class AclPriorityTest
4580     : public ChannelManagerRealAclChannelTest,
4581       public ::testing::WithParamInterface<std::pair<AclPriority, bool>> {};
4582 
TEST_P(AclPriorityTest,OutboundConnectAndSetPriority)4583 TEST_P(AclPriorityTest, OutboundConnectAndSetPriority) {
4584   const auto kPriority = GetParam().first;
4585   const bool kExpectSuccess = GetParam().second;
4586 
4587   // Arbitrary command payload larger than CommandHeader.
4588   const auto op_code = hci_spec::VendorOpCode(0x01);
4589   const StaticByteBuffer kEncodedCommand(LowerBits(op_code),
4590                                          UpperBits(op_code),  // op code
4591                                          0x04,                // parameter size
4592                                          0x00,
4593                                          0x01,
4594                                          0x02,
4595                                          0x03);  // test parameter
4596 
4597   constexpr l2cap::Psm kPsm = l2cap::kAVCTP;
4598   constexpr l2cap::ChannelId kLocalId = 0x0040;
4599   constexpr l2cap::ChannelId kRemoteId = 0x9042;
4600 
4601   std::optional<hci_spec::ConnectionHandle> connection_handle_from_encode_cb;
4602   std::optional<AclPriority> priority_from_encode_cb;
4603   test_device()->set_encode_vendor_command_cb(
4604       [&](pw::bluetooth::VendorCommandParameters vendor_params,
4605           fit::callback<void(pw::Result<pw::span<const std::byte>>)> callback) {
4606         ASSERT_TRUE(
4607             std::holds_alternative<
4608                 pw::bluetooth::SetAclPriorityCommandParameters>(vendor_params));
4609         auto& params = std::get<pw::bluetooth::SetAclPriorityCommandParameters>(
4610             vendor_params);
4611         connection_handle_from_encode_cb = params.connection_handle;
4612         priority_from_encode_cb = params.priority;
4613         callback(kEncodedCommand.subspan());
4614       });
4615 
4616   QueueAclConnection(kTestHandle1);
4617   RunUntilIdle();
4618   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4619 
4620   Channel::WeakPtr channel;
4621   auto chan_cb = [&](l2cap::Channel::WeakPtr activated_chan) {
4622     EXPECT_EQ(kTestHandle1, activated_chan->link_handle());
4623     channel = std::move(activated_chan);
4624   };
4625 
4626   QueueOutboundL2capConnection(
4627       kTestHandle1, kPsm, kLocalId, kRemoteId, std::move(chan_cb));
4628 
4629   RunUntilIdle();
4630   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4631   // We should have opened a channel successfully.
4632   ASSERT_TRUE(channel.is_alive());
4633   channel->Activate([](auto) {}, []() {});
4634 
4635   if (kPriority != AclPriority::kNormal) {
4636     auto cmd_complete = CommandCompletePacket(
4637         op_code,
4638         kExpectSuccess ? pw::bluetooth::emboss::StatusCode::SUCCESS
4639                        : pw::bluetooth::emboss::StatusCode::UNKNOWN_COMMAND);
4640     EXPECT_CMD_PACKET_OUT(test_device(), kEncodedCommand, &cmd_complete);
4641   }
4642 
4643   size_t request_cb_count = 0;
4644   channel->RequestAclPriority(kPriority, [&](auto res) {
4645     request_cb_count++;
4646     EXPECT_EQ(kExpectSuccess, res.is_ok());
4647   });
4648 
4649   RunUntilIdle();
4650   EXPECT_EQ(request_cb_count, 1u);
4651   if (kPriority == AclPriority::kNormal) {
4652     EXPECT_FALSE(connection_handle_from_encode_cb);
4653   } else {
4654     ASSERT_TRUE(connection_handle_from_encode_cb);
4655     EXPECT_EQ(connection_handle_from_encode_cb.value(), kTestHandle1);
4656     ASSERT_TRUE(priority_from_encode_cb);
4657     EXPECT_EQ(priority_from_encode_cb.value(), kPriority);
4658   }
4659   connection_handle_from_encode_cb.reset();
4660   priority_from_encode_cb.reset();
4661 
4662   if (kPriority != AclPriority::kNormal && kExpectSuccess) {
4663     auto cmd_complete = CommandCompletePacket(
4664         op_code, pw::bluetooth::emboss::StatusCode::SUCCESS);
4665     EXPECT_CMD_PACKET_OUT(test_device(), kEncodedCommand, &cmd_complete);
4666   }
4667 
4668   EXPECT_ACL_PACKET_OUT(
4669       test_device(),
4670       l2cap::testing::AclDisconnectionReq(
4671           NextCommandId(), kTestHandle1, kLocalId, kRemoteId));
4672 
4673   // Deactivating channel should send priority command to revert priority back
4674   // to normal if it was changed.
4675   channel->Deactivate();
4676   RunUntilIdle();
4677   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4678 
4679   if (kPriority != AclPriority::kNormal && kExpectSuccess) {
4680     ASSERT_TRUE(connection_handle_from_encode_cb);
4681     EXPECT_EQ(connection_handle_from_encode_cb.value(), kTestHandle1);
4682     ASSERT_TRUE(priority_from_encode_cb);
4683     EXPECT_EQ(priority_from_encode_cb.value(), AclPriority::kNormal);
4684   } else {
4685     EXPECT_FALSE(connection_handle_from_encode_cb);
4686   }
4687 }
4688 
4689 const std::array<std::pair<AclPriority, bool>, 4> kPriorityParams = {
4690     {{AclPriority::kSource, false},
4691      {AclPriority::kSource, true},
4692      {AclPriority::kSink, true},
4693      {AclPriority::kNormal, true}}};
4694 INSTANTIATE_TEST_SUITE_P(ChannelManagerMockControllerTest,
4695                          AclPriorityTest,
4696                          ::testing::ValuesIn(kPriorityParams));
4697 
4698 #ifndef NINSPECT
TEST_F(ChannelManagerRealAclChannelTest,InspectHierarchy)4699 TEST_F(ChannelManagerRealAclChannelTest, InspectHierarchy) {
4700   inspect::Inspector inspector;
4701   chanmgr()->AttachInspect(inspector.GetRoot(),
4702                            ChannelManager::kInspectNodeName);
4703   auto hierarchy = inspect::ReadFromVmo(inspector.DuplicateVmo());
4704   ASSERT_TRUE(hierarchy);
4705   auto l2cap_matcher = AllOf(NodeMatches(PropertyList(::testing::IsEmpty())),
4706                              ChildrenMatch(UnorderedElementsAre(
4707                                  NodeMatches(NameMatches("logical_links")),
4708                                  NodeMatches(NameMatches("services")))));
4709   EXPECT_THAT(hierarchy.value(),
4710               AllOf(ChildrenMatch(UnorderedElementsAre(l2cap_matcher))));
4711 }
4712 #endif  // NINSPECT
4713 
4714 }  // namespace
4715 }  // namespace bt::l2cap
4716