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