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