1 /*
2  *  Copyright 2012 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <stdint.h>
12 
13 #include <algorithm>
14 #include <memory>
15 #include <string>
16 #include <vector>
17 
18 #include "absl/types/optional.h"
19 #include "api/data_channel_interface.h"
20 #include "api/dtmf_sender_interface.h"
21 #include "api/peer_connection_interface.h"
22 #include "api/scoped_refptr.h"
23 #include "api/units/time_delta.h"
24 #include "pc/test/integration_test_helpers.h"
25 #include "pc/test/mock_peer_connection_observers.h"
26 #include "rtc_base/fake_clock.h"
27 #include "rtc_base/gunit.h"
28 #include "rtc_base/ref_counted_object.h"
29 #include "rtc_base/virtual_socket_server.h"
30 
31 namespace webrtc {
32 
33 namespace {
34 
35 class DataChannelIntegrationTest
36     : public PeerConnectionIntegrationBaseTest,
37       public ::testing::WithParamInterface<SdpSemantics> {
38  protected:
DataChannelIntegrationTest()39   DataChannelIntegrationTest()
40       : PeerConnectionIntegrationBaseTest(GetParam()) {}
41 };
42 
43 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DataChannelIntegrationTest);
44 
45 // Fake clock must be set before threads are started to prevent race on
46 // Set/GetClockForTesting().
47 // To achieve that, multiple inheritance is used as a mixin pattern
48 // where order of construction is finely controlled.
49 // This also ensures peerconnection is closed before switching back to non-fake
50 // clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
51 class FakeClockForTest : public rtc::ScopedFakeClock {
52  protected:
FakeClockForTest()53   FakeClockForTest() {
54     // Some things use a time of "0" as a special value, so we need to start out
55     // the fake clock at a nonzero time.
56     // TODO(deadbeef): Fix this.
57     AdvanceTime(webrtc::TimeDelta::Seconds(1));
58   }
59 
60   // Explicit handle.
FakeClock()61   ScopedFakeClock& FakeClock() { return *this; }
62 };
63 
64 // Ensure FakeClockForTest is constructed first (see class for rationale).
65 class DataChannelIntegrationTestWithFakeClock
66     : public FakeClockForTest,
67       public DataChannelIntegrationTest {};
68 
69 class DataChannelIntegrationTestPlanB
70     : public PeerConnectionIntegrationBaseTest {
71  protected:
DataChannelIntegrationTestPlanB()72   DataChannelIntegrationTestPlanB()
73       : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
74 };
75 
76 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(
77     DataChannelIntegrationTestWithFakeClock);
78 
79 class DataChannelIntegrationTestUnifiedPlan
80     : public PeerConnectionIntegrationBaseTest {
81  protected:
DataChannelIntegrationTestUnifiedPlan()82   DataChannelIntegrationTestUnifiedPlan()
83       : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
84 };
85 
86 #ifdef WEBRTC_HAVE_SCTP
87 
88 // This test causes a PeerConnection to enter Disconnected state, and
89 // sends data on a DataChannel while disconnected.
90 // The data should be surfaced when the connection reestablishes.
TEST_P(DataChannelIntegrationTest,DataChannelWhileDisconnected)91 TEST_P(DataChannelIntegrationTest, DataChannelWhileDisconnected) {
92   CreatePeerConnectionWrappers();
93   ConnectFakeSignaling();
94   caller()->CreateDataChannel();
95   caller()->CreateAndSetAndSignalOffer();
96   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
97   ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
98   std::string data1 = "hello first";
99   caller()->data_channel()->Send(DataBuffer(data1));
100   EXPECT_EQ_WAIT(data1, callee()->data_observer()->last_message(),
101                  kDefaultTimeout);
102   // Cause a network outage
103   virtual_socket_server()->set_drop_probability(1.0);
104   EXPECT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
105                  caller()->standardized_ice_connection_state(),
106                  kDefaultTimeout);
107   std::string data2 = "hello second";
108   caller()->data_channel()->Send(DataBuffer(data2));
109   // Remove the network outage. The connection should reestablish.
110   virtual_socket_server()->set_drop_probability(0.0);
111   EXPECT_EQ_WAIT(data2, callee()->data_observer()->last_message(),
112                  kDefaultTimeout);
113 }
114 
115 // This test causes a PeerConnection to enter Disconnected state,
116 // sends data on a DataChannel while disconnected, and then triggers
117 // an ICE restart.
118 // The data should be surfaced when the connection reestablishes.
TEST_P(DataChannelIntegrationTest,DataChannelWhileDisconnectedIceRestart)119 TEST_P(DataChannelIntegrationTest, DataChannelWhileDisconnectedIceRestart) {
120   CreatePeerConnectionWrappers();
121   ConnectFakeSignaling();
122   caller()->CreateDataChannel();
123   caller()->CreateAndSetAndSignalOffer();
124   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
125   ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
126   std::string data1 = "hello first";
127   caller()->data_channel()->Send(DataBuffer(data1));
128   EXPECT_EQ_WAIT(data1, callee()->data_observer()->last_message(),
129                  kDefaultTimeout);
130   // Cause a network outage
131   virtual_socket_server()->set_drop_probability(1.0);
132   ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
133                  caller()->standardized_ice_connection_state(),
134                  kDefaultTimeout);
135   std::string data2 = "hello second";
136   caller()->data_channel()->Send(DataBuffer(data2));
137 
138   // Trigger an ICE restart. The signaling channel is not affected by
139   // the network outage.
140   caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
141   caller()->CreateAndSetAndSignalOffer();
142   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
143   // Remove the network outage. The connection should reestablish.
144   virtual_socket_server()->set_drop_probability(0.0);
145   EXPECT_EQ_WAIT(data2, callee()->data_observer()->last_message(),
146                  kDefaultTimeout);
147 }
148 
149 #endif  // WEBRTC_HAVE_SCTP
150 
151 // This test sets up a call between two parties with audio, video and an RTP
152 // data channel.
TEST_P(DataChannelIntegrationTest,EndToEndCallWithRtpDataChannel)153 TEST_P(DataChannelIntegrationTest, EndToEndCallWithRtpDataChannel) {
154   PeerConnectionInterface::RTCConfiguration rtc_config;
155   rtc_config.enable_rtp_data_channel = true;
156   rtc_config.enable_dtls_srtp = false;
157   ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
158   ConnectFakeSignaling();
159   // Expect that data channel created on caller side will show up for callee as
160   // well.
161   caller()->CreateDataChannel();
162   caller()->AddAudioVideoTracks();
163   callee()->AddAudioVideoTracks();
164   caller()->CreateAndSetAndSignalOffer();
165   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
166   // Ensure the existence of the RTP data channel didn't impede audio/video.
167   MediaExpectations media_expectations;
168   media_expectations.ExpectBidirectionalAudioAndVideo();
169   ASSERT_TRUE(ExpectNewFrames(media_expectations));
170   ASSERT_NE(nullptr, caller()->data_channel());
171   ASSERT_NE(nullptr, callee()->data_channel());
172   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
173   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
174 
175   // Ensure data can be sent in both directions.
176   std::string data = "hello world";
177   SendRtpDataWithRetries(caller()->data_channel(), data, 5);
178   EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
179                  kDefaultTimeout);
180   SendRtpDataWithRetries(callee()->data_channel(), data, 5);
181   EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
182                  kDefaultTimeout);
183 }
184 
TEST_P(DataChannelIntegrationTest,RtpDataChannelWorksAfterRollback)185 TEST_P(DataChannelIntegrationTest, RtpDataChannelWorksAfterRollback) {
186   PeerConnectionInterface::RTCConfiguration rtc_config;
187   rtc_config.enable_rtp_data_channel = true;
188   rtc_config.enable_dtls_srtp = false;
189   ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
190   ConnectFakeSignaling();
191   auto data_channel = caller()->pc()->CreateDataChannel("label_1", nullptr);
192   ASSERT_TRUE(data_channel.get() != nullptr);
193   caller()->CreateAndSetAndSignalOffer();
194   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
195 
196   caller()->CreateDataChannel("label_2", nullptr);
197   rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
198       new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
199   caller()->pc()->SetLocalDescription(observer,
200                                       caller()->CreateOfferAndWait().release());
201   EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
202   caller()->Rollback();
203 
204   std::string data = "hello world";
205   SendRtpDataWithRetries(data_channel, data, 5);
206   EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
207                  kDefaultTimeout);
208 }
209 
210 // Ensure that an RTP data channel is signaled as closed for the caller when
211 // the callee rejects it in a subsequent offer.
TEST_P(DataChannelIntegrationTest,RtpDataChannelSignaledClosedInCalleeOffer)212 TEST_P(DataChannelIntegrationTest, RtpDataChannelSignaledClosedInCalleeOffer) {
213   // Same procedure as above test.
214   PeerConnectionInterface::RTCConfiguration rtc_config;
215   rtc_config.enable_rtp_data_channel = true;
216   rtc_config.enable_dtls_srtp = false;
217   ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
218   ConnectFakeSignaling();
219   caller()->CreateDataChannel();
220   caller()->AddAudioVideoTracks();
221   callee()->AddAudioVideoTracks();
222   caller()->CreateAndSetAndSignalOffer();
223   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
224   ASSERT_NE(nullptr, caller()->data_channel());
225   ASSERT_NE(nullptr, callee()->data_channel());
226   ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
227   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
228 
229   // Close the data channel on the callee, and do an updated offer/answer.
230   callee()->data_channel()->Close();
231   callee()->CreateAndSetAndSignalOffer();
232   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
233   EXPECT_FALSE(caller()->data_observer()->IsOpen());
234   EXPECT_FALSE(callee()->data_observer()->IsOpen());
235 }
236 
237 #if !defined(THREAD_SANITIZER)
238 // This test provokes TSAN errors. See bugs.webrtc.org/11282
239 
240 // Tests that data is buffered in an RTP data channel until an observer is
241 // registered for it.
242 //
243 // NOTE: RTP data channels can receive data before the underlying
244 // transport has detected that a channel is writable and thus data can be
245 // received before the data channel state changes to open. That is hard to test
246 // but the same buffering is expected to be used in that case.
247 //
248 // Use fake clock and simulated network delay so that we predictably can wait
249 // until an SCTP message has been delivered without "sleep()"ing.
TEST_P(DataChannelIntegrationTestWithFakeClock,DataBufferedUntilRtpDataChannelObserverRegistered)250 TEST_P(DataChannelIntegrationTestWithFakeClock,
251        DataBufferedUntilRtpDataChannelObserverRegistered) {
252   virtual_socket_server()->set_delay_mean(5);  // 5 ms per hop.
253   virtual_socket_server()->UpdateDelayDistribution();
254 
255   PeerConnectionInterface::RTCConfiguration rtc_config;
256   rtc_config.enable_rtp_data_channel = true;
257   rtc_config.enable_dtls_srtp = false;
258   ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
259   ConnectFakeSignaling();
260   caller()->CreateDataChannel();
261   caller()->CreateAndSetAndSignalOffer();
262   ASSERT_TRUE(caller()->data_channel() != nullptr);
263   ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
264                              kDefaultTimeout, FakeClock());
265   ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
266                              kDefaultTimeout, FakeClock());
267   ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
268                            callee()->data_channel()->state(), kDefaultTimeout,
269                            FakeClock());
270 
271   // Unregister the observer which is normally automatically registered.
272   callee()->data_channel()->UnregisterObserver();
273   // Send data and advance fake clock until it should have been received.
274   std::string data = "hello world";
275   caller()->data_channel()->Send(DataBuffer(data));
276   SIMULATED_WAIT(false, 50, FakeClock());
277 
278   // Attach data channel and expect data to be received immediately. Note that
279   // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
280   // further, but data can be received even if the callback is asynchronous.
281   MockDataChannelObserver new_observer(callee()->data_channel());
282   EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
283                            FakeClock());
284 }
285 
286 #endif  // !defined(THREAD_SANITIZER)
287 
288 // This test sets up a call between two parties with audio, video and but only
289 // the caller client supports RTP data channels.
TEST_P(DataChannelIntegrationTest,RtpDataChannelsRejectedByCallee)290 TEST_P(DataChannelIntegrationTest, RtpDataChannelsRejectedByCallee) {
291   PeerConnectionInterface::RTCConfiguration rtc_config_1;
292   rtc_config_1.enable_rtp_data_channel = true;
293   // Must disable DTLS to make negotiation succeed.
294   rtc_config_1.enable_dtls_srtp = false;
295   PeerConnectionInterface::RTCConfiguration rtc_config_2;
296   rtc_config_2.enable_dtls_srtp = false;
297   rtc_config_2.enable_dtls_srtp = false;
298   ASSERT_TRUE(
299       CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
300   ConnectFakeSignaling();
301   caller()->CreateDataChannel();
302   ASSERT_TRUE(caller()->data_channel() != nullptr);
303   caller()->AddAudioVideoTracks();
304   callee()->AddAudioVideoTracks();
305   caller()->CreateAndSetAndSignalOffer();
306   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
307   // The caller should still have a data channel, but it should be closed, and
308   // one should ever have been created for the callee.
309   EXPECT_TRUE(caller()->data_channel() != nullptr);
310   EXPECT_FALSE(caller()->data_observer()->IsOpen());
311   EXPECT_EQ(nullptr, callee()->data_channel());
312 }
313 
314 // This test sets up a call between two parties with audio, and video. When
315 // audio and video is setup and flowing, an RTP data channel is negotiated.
TEST_P(DataChannelIntegrationTest,AddRtpDataChannelInSubsequentOffer)316 TEST_P(DataChannelIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
317   PeerConnectionInterface::RTCConfiguration rtc_config;
318   rtc_config.enable_rtp_data_channel = true;
319   rtc_config.enable_dtls_srtp = false;
320   ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
321   ConnectFakeSignaling();
322   // Do initial offer/answer with audio/video.
323   caller()->AddAudioVideoTracks();
324   callee()->AddAudioVideoTracks();
325   caller()->CreateAndSetAndSignalOffer();
326   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
327   // Create data channel and do new offer and answer.
328   caller()->CreateDataChannel();
329   caller()->CreateAndSetAndSignalOffer();
330   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
331   ASSERT_NE(nullptr, caller()->data_channel());
332   ASSERT_NE(nullptr, callee()->data_channel());
333   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
334   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
335   // Ensure data can be sent in both directions.
336   std::string data = "hello world";
337   SendRtpDataWithRetries(caller()->data_channel(), data, 5);
338   EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
339                  kDefaultTimeout);
340   SendRtpDataWithRetries(callee()->data_channel(), data, 5);
341   EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
342                  kDefaultTimeout);
343 }
344 
345 #ifdef WEBRTC_HAVE_SCTP
346 
347 // This test sets up a call between two parties with audio, video and an SCTP
348 // data channel.
TEST_P(DataChannelIntegrationTest,EndToEndCallWithSctpDataChannel)349 TEST_P(DataChannelIntegrationTest, EndToEndCallWithSctpDataChannel) {
350   ASSERT_TRUE(CreatePeerConnectionWrappers());
351   ConnectFakeSignaling();
352   // Expect that data channel created on caller side will show up for callee as
353   // well.
354   caller()->CreateDataChannel();
355   caller()->AddAudioVideoTracks();
356   callee()->AddAudioVideoTracks();
357   caller()->CreateAndSetAndSignalOffer();
358   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
359   // Ensure the existence of the SCTP data channel didn't impede audio/video.
360   MediaExpectations media_expectations;
361   media_expectations.ExpectBidirectionalAudioAndVideo();
362   ASSERT_TRUE(ExpectNewFrames(media_expectations));
363   // Caller data channel should already exist (it created one). Callee data
364   // channel may not exist yet, since negotiation happens in-band, not in SDP.
365   ASSERT_NE(nullptr, caller()->data_channel());
366   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
367   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
368   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
369 
370   // Ensure data can be sent in both directions.
371   std::string data = "hello world";
372   caller()->data_channel()->Send(DataBuffer(data));
373   EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
374                  kDefaultTimeout);
375   callee()->data_channel()->Send(DataBuffer(data));
376   EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
377                  kDefaultTimeout);
378 }
379 
380 // This test sets up a call between two parties with an SCTP
381 // data channel only, and sends messages of various sizes.
TEST_P(DataChannelIntegrationTest,EndToEndCallWithSctpDataChannelVariousSizes)382 TEST_P(DataChannelIntegrationTest,
383        EndToEndCallWithSctpDataChannelVariousSizes) {
384   ASSERT_TRUE(CreatePeerConnectionWrappers());
385   ConnectFakeSignaling();
386   // Expect that data channel created on caller side will show up for callee as
387   // well.
388   caller()->CreateDataChannel();
389   caller()->CreateAndSetAndSignalOffer();
390   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
391   // Caller data channel should already exist (it created one). Callee data
392   // channel may not exist yet, since negotiation happens in-band, not in SDP.
393   ASSERT_NE(nullptr, caller()->data_channel());
394   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
395   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
396   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
397 
398   for (int message_size = 1; message_size < 100000; message_size *= 2) {
399     std::string data(message_size, 'a');
400     caller()->data_channel()->Send(DataBuffer(data));
401     EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
402                    kDefaultTimeout);
403     callee()->data_channel()->Send(DataBuffer(data));
404     EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
405                    kDefaultTimeout);
406   }
407   // Specifically probe the area around the MTU size.
408   for (int message_size = 1100; message_size < 1300; message_size += 1) {
409     std::string data(message_size, 'a');
410     caller()->data_channel()->Send(DataBuffer(data));
411     EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
412                    kDefaultTimeout);
413     callee()->data_channel()->Send(DataBuffer(data));
414     EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
415                    kDefaultTimeout);
416   }
417 }
418 
TEST_P(DataChannelIntegrationTest,EndToEndCallWithSctpDataChannelLowestSafeMtu)419 TEST_P(DataChannelIntegrationTest,
420        EndToEndCallWithSctpDataChannelLowestSafeMtu) {
421   // The lowest payload size limit that's tested and found safe for this
422   // application. Note that this is not the safe limit under all conditions;
423   // in particular, the default is not the largest DTLS signature, and
424   // this test does not use TURN.
425   const size_t kLowestSafePayloadSizeLimit = 1225;
426 
427   ASSERT_TRUE(CreatePeerConnectionWrappers());
428   ConnectFakeSignaling();
429   // Expect that data channel created on caller side will show up for callee as
430   // well.
431   caller()->CreateDataChannel();
432   caller()->CreateAndSetAndSignalOffer();
433   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
434   // Caller data channel should already exist (it created one). Callee data
435   // channel may not exist yet, since negotiation happens in-band, not in SDP.
436   ASSERT_NE(nullptr, caller()->data_channel());
437   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
438   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
439   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
440 
441   virtual_socket_server()->set_max_udp_payload(kLowestSafePayloadSizeLimit);
442   for (int message_size = 1140; message_size < 1240; message_size += 1) {
443     std::string data(message_size, 'a');
444     caller()->data_channel()->Send(DataBuffer(data));
445     ASSERT_EQ_WAIT(data, callee()->data_observer()->last_message(),
446                    kDefaultTimeout);
447     callee()->data_channel()->Send(DataBuffer(data));
448     ASSERT_EQ_WAIT(data, caller()->data_observer()->last_message(),
449                    kDefaultTimeout);
450   }
451 }
452 
453 // This test verifies that lowering the MTU of the connection will cause
454 // the datachannel to not transmit reliably.
455 // The purpose of this test is to ensure that we know how a too-small MTU
456 // error manifests itself.
TEST_P(DataChannelIntegrationTest,EndToEndCallWithSctpDataChannelHarmfulMtu)457 TEST_P(DataChannelIntegrationTest, EndToEndCallWithSctpDataChannelHarmfulMtu) {
458   // The lowest payload size limit that's tested and found safe for this
459   // application in this configuration (see test above).
460   const size_t kLowestSafePayloadSizeLimit = 1225;
461   // The size of the smallest message that fails to be delivered.
462   const size_t kMessageSizeThatIsNotDelivered = 1157;
463 
464   ASSERT_TRUE(CreatePeerConnectionWrappers());
465   ConnectFakeSignaling();
466   caller()->CreateDataChannel();
467   caller()->CreateAndSetAndSignalOffer();
468   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
469   ASSERT_NE(nullptr, caller()->data_channel());
470   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
471   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
472   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
473 
474   virtual_socket_server()->set_max_udp_payload(kLowestSafePayloadSizeLimit - 1);
475   // Probe for an undelivered or slowly delivered message. The exact
476   // size limit seems to be dependent on the message history, so make the
477   // code easily able to find the current value.
478   bool failure_seen = false;
479   for (size_t message_size = 1110; message_size < 1400; message_size++) {
480     const size_t message_count =
481         callee()->data_observer()->received_message_count();
482     const std::string data(message_size, 'a');
483     caller()->data_channel()->Send(DataBuffer(data));
484     // Wait a very short time for the message to be delivered.
485     // Note: Waiting only 10 ms is too short for Windows bots; they will
486     // flakily fail at a random frame.
487     WAIT(callee()->data_observer()->received_message_count() > message_count,
488          100);
489     if (callee()->data_observer()->received_message_count() == message_count) {
490       ASSERT_EQ(kMessageSizeThatIsNotDelivered, message_size);
491       failure_seen = true;
492       break;
493     }
494   }
495   ASSERT_TRUE(failure_seen);
496 }
497 
498 // Ensure that when the callee closes an SCTP data channel, the closing
499 // procedure results in the data channel being closed for the caller as well.
TEST_P(DataChannelIntegrationTest,CalleeClosesSctpDataChannel)500 TEST_P(DataChannelIntegrationTest, CalleeClosesSctpDataChannel) {
501   // Same procedure as above test.
502   ASSERT_TRUE(CreatePeerConnectionWrappers());
503   ConnectFakeSignaling();
504   caller()->CreateDataChannel();
505   caller()->AddAudioVideoTracks();
506   callee()->AddAudioVideoTracks();
507   caller()->CreateAndSetAndSignalOffer();
508   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
509   ASSERT_NE(nullptr, caller()->data_channel());
510   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
511   ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
512   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
513 
514   // Close the data channel on the callee side, and wait for it to reach the
515   // "closed" state on both sides.
516   callee()->data_channel()->Close();
517   EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
518   EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
519 }
520 
TEST_P(DataChannelIntegrationTest,SctpDataChannelConfigSentToOtherSide)521 TEST_P(DataChannelIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
522   ASSERT_TRUE(CreatePeerConnectionWrappers());
523   ConnectFakeSignaling();
524   webrtc::DataChannelInit init;
525   init.id = 53;
526   init.maxRetransmits = 52;
527   caller()->CreateDataChannel("data-channel", &init);
528   caller()->AddAudioVideoTracks();
529   callee()->AddAudioVideoTracks();
530   caller()->CreateAndSetAndSignalOffer();
531   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
532   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
533   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
534   // Since "negotiated" is false, the "id" parameter should be ignored.
535   EXPECT_NE(init.id, callee()->data_channel()->id());
536   EXPECT_EQ("data-channel", callee()->data_channel()->label());
537   EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
538   EXPECT_FALSE(callee()->data_channel()->negotiated());
539 }
540 
541 // Test usrsctp's ability to process unordered data stream, where data actually
542 // arrives out of order using simulated delays. Previously there have been some
543 // bugs in this area.
TEST_P(DataChannelIntegrationTest,StressTestUnorderedSctpDataChannel)544 TEST_P(DataChannelIntegrationTest, StressTestUnorderedSctpDataChannel) {
545   // Introduce random network delays.
546   // Otherwise it's not a true "unordered" test.
547   virtual_socket_server()->set_delay_mean(20);
548   virtual_socket_server()->set_delay_stddev(5);
549   virtual_socket_server()->UpdateDelayDistribution();
550   // Normal procedure, but with unordered data channel config.
551   ASSERT_TRUE(CreatePeerConnectionWrappers());
552   ConnectFakeSignaling();
553   webrtc::DataChannelInit init;
554   init.ordered = false;
555   caller()->CreateDataChannel(&init);
556   caller()->CreateAndSetAndSignalOffer();
557   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
558   ASSERT_NE(nullptr, caller()->data_channel());
559   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
560   ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
561   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
562 
563   static constexpr int kNumMessages = 100;
564   // Deliberately chosen to be larger than the MTU so messages get fragmented.
565   static constexpr size_t kMaxMessageSize = 4096;
566   // Create and send random messages.
567   std::vector<std::string> sent_messages;
568   for (int i = 0; i < kNumMessages; ++i) {
569     size_t length =
570         (rand() % kMaxMessageSize) + 1;  // NOLINT (rand_r instead of rand)
571     std::string message;
572     ASSERT_TRUE(rtc::CreateRandomString(length, &message));
573     caller()->data_channel()->Send(DataBuffer(message));
574     callee()->data_channel()->Send(DataBuffer(message));
575     sent_messages.push_back(message);
576   }
577 
578   // Wait for all messages to be received.
579   EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
580                  caller()->data_observer()->received_message_count(),
581                  kDefaultTimeout);
582   EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
583                  callee()->data_observer()->received_message_count(),
584                  kDefaultTimeout);
585 
586   // Sort and compare to make sure none of the messages were corrupted.
587   std::vector<std::string> caller_received_messages =
588       caller()->data_observer()->messages();
589   std::vector<std::string> callee_received_messages =
590       callee()->data_observer()->messages();
591   absl::c_sort(sent_messages);
592   absl::c_sort(caller_received_messages);
593   absl::c_sort(callee_received_messages);
594   EXPECT_EQ(sent_messages, caller_received_messages);
595   EXPECT_EQ(sent_messages, callee_received_messages);
596 }
597 
598 // This test sets up a call between two parties with audio, and video. When
599 // audio and video are setup and flowing, an SCTP data channel is negotiated.
TEST_P(DataChannelIntegrationTest,AddSctpDataChannelInSubsequentOffer)600 TEST_P(DataChannelIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
601   ASSERT_TRUE(CreatePeerConnectionWrappers());
602   ConnectFakeSignaling();
603   // Do initial offer/answer with audio/video.
604   caller()->AddAudioVideoTracks();
605   callee()->AddAudioVideoTracks();
606   caller()->CreateAndSetAndSignalOffer();
607   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
608   // Create data channel and do new offer and answer.
609   caller()->CreateDataChannel();
610   caller()->CreateAndSetAndSignalOffer();
611   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
612   // Caller data channel should already exist (it created one). Callee data
613   // channel may not exist yet, since negotiation happens in-band, not in SDP.
614   ASSERT_NE(nullptr, caller()->data_channel());
615   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
616   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
617   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
618   // Ensure data can be sent in both directions.
619   std::string data = "hello world";
620   caller()->data_channel()->Send(DataBuffer(data));
621   EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
622                  kDefaultTimeout);
623   callee()->data_channel()->Send(DataBuffer(data));
624   EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
625                  kDefaultTimeout);
626 }
627 
628 // Set up a connection initially just using SCTP data channels, later upgrading
629 // to audio/video, ensuring frames are received end-to-end. Effectively the
630 // inverse of the test above.
631 // This was broken in M57; see https://crbug.com/711243
TEST_P(DataChannelIntegrationTest,SctpDataChannelToAudioVideoUpgrade)632 TEST_P(DataChannelIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
633   ASSERT_TRUE(CreatePeerConnectionWrappers());
634   ConnectFakeSignaling();
635   // Do initial offer/answer with just data channel.
636   caller()->CreateDataChannel();
637   caller()->CreateAndSetAndSignalOffer();
638   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
639   // Wait until data can be sent over the data channel.
640   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
641   ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
642   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
643 
644   // Do subsequent offer/answer with two-way audio and video. Audio and video
645   // should end up bundled on the DTLS/ICE transport already used for data.
646   caller()->AddAudioVideoTracks();
647   callee()->AddAudioVideoTracks();
648   caller()->CreateAndSetAndSignalOffer();
649   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
650   MediaExpectations media_expectations;
651   media_expectations.ExpectBidirectionalAudioAndVideo();
652   ASSERT_TRUE(ExpectNewFrames(media_expectations));
653 }
654 
MakeSpecCompliantSctpOffer(cricket::SessionDescription * desc)655 static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
656   cricket::SctpDataContentDescription* dcd_offer =
657       GetFirstSctpDataContentDescription(desc);
658   // See https://crbug.com/webrtc/11211 - this function is a no-op
659   ASSERT_TRUE(dcd_offer);
660   dcd_offer->set_use_sctpmap(false);
661   dcd_offer->set_protocol("UDP/DTLS/SCTP");
662 }
663 
664 // Test that the data channel works when a spec-compliant SCTP m= section is
665 // offered (using "a=sctp-port" instead of "a=sctpmap", and using
666 // "UDP/DTLS/SCTP" as the protocol).
TEST_P(DataChannelIntegrationTest,DataChannelWorksWhenSpecCompliantSctpOfferReceived)667 TEST_P(DataChannelIntegrationTest,
668        DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
669   ASSERT_TRUE(CreatePeerConnectionWrappers());
670   ConnectFakeSignaling();
671   caller()->CreateDataChannel();
672   caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
673   caller()->CreateAndSetAndSignalOffer();
674   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
675   ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
676   EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
677   EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
678 
679   // Ensure data can be sent in both directions.
680   std::string data = "hello world";
681   caller()->data_channel()->Send(DataBuffer(data));
682   EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
683                  kDefaultTimeout);
684   callee()->data_channel()->Send(DataBuffer(data));
685   EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
686                  kDefaultTimeout);
687 }
688 
689 #endif  // WEBRTC_HAVE_SCTP
690 
691 // Test that after closing PeerConnections, they stop sending any packets (ICE,
692 // DTLS, RTP...).
TEST_P(DataChannelIntegrationTest,ClosingConnectionStopsPacketFlow)693 TEST_P(DataChannelIntegrationTest, ClosingConnectionStopsPacketFlow) {
694   // Set up audio/video/data, wait for some frames to be received.
695   ASSERT_TRUE(CreatePeerConnectionWrappers());
696   ConnectFakeSignaling();
697   caller()->AddAudioVideoTracks();
698 #ifdef WEBRTC_HAVE_SCTP
699   caller()->CreateDataChannel();
700 #endif
701   caller()->CreateAndSetAndSignalOffer();
702   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
703   MediaExpectations media_expectations;
704   media_expectations.CalleeExpectsSomeAudioAndVideo();
705   ASSERT_TRUE(ExpectNewFrames(media_expectations));
706   // Close PeerConnections.
707   ClosePeerConnections();
708   // Pump messages for a second, and ensure no new packets end up sent.
709   uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
710   WAIT(false, 1000);
711   uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
712   EXPECT_EQ(sent_packets_a, sent_packets_b);
713 }
714 
715 // Test that transport stats are generated by the RTCStatsCollector for a
716 // connection that only involves data channels. This is a regression test for
717 // crbug.com/826972.
718 #ifdef WEBRTC_HAVE_SCTP
TEST_P(DataChannelIntegrationTest,TransportStatsReportedForDataChannelOnlyConnection)719 TEST_P(DataChannelIntegrationTest,
720        TransportStatsReportedForDataChannelOnlyConnection) {
721   ASSERT_TRUE(CreatePeerConnectionWrappers());
722   ConnectFakeSignaling();
723   caller()->CreateDataChannel();
724 
725   caller()->CreateAndSetAndSignalOffer();
726   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
727   ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
728 
729   auto caller_report = caller()->NewGetStats();
730   EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
731   auto callee_report = callee()->NewGetStats();
732   EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
733 }
734 
735 INSTANTIATE_TEST_SUITE_P(DataChannelIntegrationTest,
736                          DataChannelIntegrationTest,
737                          Values(SdpSemantics::kPlanB,
738                                 SdpSemantics::kUnifiedPlan));
739 
740 INSTANTIATE_TEST_SUITE_P(DataChannelIntegrationTest,
741                          DataChannelIntegrationTestWithFakeClock,
742                          Values(SdpSemantics::kPlanB,
743                                 SdpSemantics::kUnifiedPlan));
744 
TEST_F(DataChannelIntegrationTestUnifiedPlan,EndToEndCallWithBundledSctpDataChannel)745 TEST_F(DataChannelIntegrationTestUnifiedPlan,
746        EndToEndCallWithBundledSctpDataChannel) {
747   ASSERT_TRUE(CreatePeerConnectionWrappers());
748   ConnectFakeSignaling();
749   caller()->CreateDataChannel();
750   caller()->AddAudioVideoTracks();
751   callee()->AddAudioVideoTracks();
752   caller()->CreateAndSetAndSignalOffer();
753   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
754   network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
755     ASSERT_EQ_WAIT(SctpTransportState::kConnected,
756                    caller()->pc()->GetSctpTransport()->Information().state(),
757                    kDefaultTimeout);
758   });
759   ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
760   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
761 }
762 
TEST_F(DataChannelIntegrationTestUnifiedPlan,EndToEndCallWithDataChannelOnlyConnects)763 TEST_F(DataChannelIntegrationTestUnifiedPlan,
764        EndToEndCallWithDataChannelOnlyConnects) {
765   ASSERT_TRUE(CreatePeerConnectionWrappers());
766   ConnectFakeSignaling();
767   caller()->CreateDataChannel();
768   caller()->CreateAndSetAndSignalOffer();
769   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
770   ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
771   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
772   ASSERT_TRUE(caller()->data_observer()->IsOpen());
773 }
774 
TEST_F(DataChannelIntegrationTestUnifiedPlan,DataChannelClosesWhenClosed)775 TEST_F(DataChannelIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
776   ASSERT_TRUE(CreatePeerConnectionWrappers());
777   ConnectFakeSignaling();
778   caller()->CreateDataChannel();
779   caller()->CreateAndSetAndSignalOffer();
780   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
781   ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
782   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
783   caller()->data_channel()->Close();
784   ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
785 }
786 
TEST_F(DataChannelIntegrationTestUnifiedPlan,DataChannelClosesWhenClosedReverse)787 TEST_F(DataChannelIntegrationTestUnifiedPlan,
788        DataChannelClosesWhenClosedReverse) {
789   ASSERT_TRUE(CreatePeerConnectionWrappers());
790   ConnectFakeSignaling();
791   caller()->CreateDataChannel();
792   caller()->CreateAndSetAndSignalOffer();
793   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
794   ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
795   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
796   callee()->data_channel()->Close();
797   ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
798 }
799 
TEST_F(DataChannelIntegrationTestUnifiedPlan,DataChannelClosesWhenPeerConnectionClosed)800 TEST_F(DataChannelIntegrationTestUnifiedPlan,
801        DataChannelClosesWhenPeerConnectionClosed) {
802   ASSERT_TRUE(CreatePeerConnectionWrappers());
803   ConnectFakeSignaling();
804   caller()->CreateDataChannel();
805   caller()->CreateAndSetAndSignalOffer();
806   ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
807   ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
808   ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
809   caller()->pc()->Close();
810   ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
811 }
812 
813 #endif  // WEBRTC_HAVE_SCTP
814 
815 }  // namespace
816 
817 }  // namespace webrtc
818