1 /* 2 * libjingle SCTP 3 * Copyright 2013 Google Inc 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright notice, 9 * this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright notice, 11 * this list of conditions and the following disclaimer in the documentation 12 * and/or other materials provided with the distribution. 13 * 3. The name of the author may not be used to endorse or promote products 14 * derived from this software without specific prior written permission. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 */ 27 28 #include <errno.h> 29 #include <stdarg.h> 30 #include <stdio.h> 31 #include <string> 32 #include <vector> 33 34 #include "talk/media/base/constants.h" 35 #include "talk/media/base/mediachannel.h" 36 #include "talk/media/sctp/sctpdataengine.h" 37 #include "webrtc/base/bind.h" 38 #include "webrtc/base/buffer.h" 39 #include "webrtc/base/criticalsection.h" 40 #include "webrtc/base/gunit.h" 41 #include "webrtc/base/helpers.h" 42 #include "webrtc/base/messagehandler.h" 43 #include "webrtc/base/messagequeue.h" 44 #include "webrtc/base/scoped_ptr.h" 45 #include "webrtc/base/ssladapter.h" 46 #include "webrtc/base/thread.h" 47 48 #ifdef HAVE_NSS_SSL_H 49 // TODO(thorcarpenter): Remove after webrtc switches over to BoringSSL. 50 #include "webrtc/base/nssstreamadapter.h" 51 #endif // HAVE_NSS_SSL_H 52 53 enum { 54 MSG_PACKET = 1, 55 }; 56 57 // Fake NetworkInterface that sends/receives sctp packets. The one in 58 // talk/media/base/fakenetworkinterface.h only works with rtp/rtcp. 59 class SctpFakeNetworkInterface : public cricket::MediaChannel::NetworkInterface, 60 public rtc::MessageHandler { 61 public: 62 explicit SctpFakeNetworkInterface(rtc::Thread* thread) 63 : thread_(thread), 64 dest_(NULL) { 65 } 66 67 void SetDestination(cricket::DataMediaChannel* dest) { dest_ = dest; } 68 69 protected: 70 // Called to send raw packet down the wire (e.g. SCTP an packet). 71 virtual bool SendPacket(rtc::Buffer* packet, 72 rtc::DiffServCodePoint dscp) { 73 LOG(LS_VERBOSE) << "SctpFakeNetworkInterface::SendPacket"; 74 75 // TODO(ldixon): Can/should we use Buffer.TransferTo here? 76 // Note: this assignment does a deep copy of data from packet. 77 rtc::Buffer* buffer = new rtc::Buffer(packet->data(), packet->length()); 78 thread_->Post(this, MSG_PACKET, rtc::WrapMessageData(buffer)); 79 LOG(LS_VERBOSE) << "SctpFakeNetworkInterface::SendPacket, Posted message."; 80 return true; 81 } 82 83 // Called when a raw packet has been recieved. This passes the data to the 84 // code that will interpret the packet. e.g. to get the content payload from 85 // an SCTP packet. 86 virtual void OnMessage(rtc::Message* msg) { 87 LOG(LS_VERBOSE) << "SctpFakeNetworkInterface::OnMessage"; 88 rtc::scoped_ptr<rtc::Buffer> buffer( 89 static_cast<rtc::TypedMessageData<rtc::Buffer*>*>( 90 msg->pdata)->data()); 91 if (dest_) { 92 dest_->OnPacketReceived(buffer.get(), rtc::PacketTime()); 93 } 94 delete msg->pdata; 95 } 96 97 // Unsupported functions required to exist by NetworkInterface. 98 // TODO(ldixon): Refactor parent NetworkInterface class so these are not 99 // required. They are RTC specific and should be in an appropriate subclass. 100 virtual bool SendRtcp(rtc::Buffer* packet, 101 rtc::DiffServCodePoint dscp) { 102 LOG(LS_WARNING) << "Unsupported: SctpFakeNetworkInterface::SendRtcp."; 103 return false; 104 } 105 virtual int SetOption(SocketType type, rtc::Socket::Option opt, 106 int option) { 107 LOG(LS_WARNING) << "Unsupported: SctpFakeNetworkInterface::SetOption."; 108 return 0; 109 } 110 virtual void SetDefaultDSCPCode(rtc::DiffServCodePoint dscp) { 111 LOG(LS_WARNING) << "Unsupported: SctpFakeNetworkInterface::SetOption."; 112 } 113 114 private: 115 // Not owned by this class. 116 rtc::Thread* thread_; 117 cricket::DataMediaChannel* dest_; 118 }; 119 120 // This is essentially a buffer to hold recieved data. It stores only the last 121 // received data. Calling OnDataReceived twice overwrites old data with the 122 // newer one. 123 // TODO(ldixon): Implement constraints, and allow new data to be added to old 124 // instead of replacing it. 125 class SctpFakeDataReceiver : public sigslot::has_slots<> { 126 public: 127 SctpFakeDataReceiver() : received_(false) {} 128 129 void Clear() { 130 received_ = false; 131 last_data_ = ""; 132 last_params_ = cricket::ReceiveDataParams(); 133 } 134 135 virtual void OnDataReceived(const cricket::ReceiveDataParams& params, 136 const char* data, size_t length) { 137 received_ = true; 138 last_data_ = std::string(data, length); 139 last_params_ = params; 140 } 141 142 bool received() const { return received_; } 143 std::string last_data() const { return last_data_; } 144 cricket::ReceiveDataParams last_params() const { return last_params_; } 145 146 private: 147 bool received_; 148 std::string last_data_; 149 cricket::ReceiveDataParams last_params_; 150 }; 151 152 class SignalReadyToSendObserver : public sigslot::has_slots<> { 153 public: 154 SignalReadyToSendObserver() : signaled_(false), writable_(false) {} 155 156 void OnSignaled(bool writable) { 157 signaled_ = true; 158 writable_ = writable; 159 } 160 161 bool IsSignaled(bool writable) { 162 return signaled_ && (writable_ == writable); 163 } 164 165 private: 166 bool signaled_; 167 bool writable_; 168 }; 169 170 class SignalChannelClosedObserver : public sigslot::has_slots<> { 171 public: 172 SignalChannelClosedObserver() {} 173 void BindSelf(cricket::SctpDataMediaChannel* channel) { 174 channel->SignalStreamClosedRemotely.connect( 175 this, &SignalChannelClosedObserver::OnStreamClosed); 176 } 177 void OnStreamClosed(uint32 stream) { 178 streams_.push_back(stream); 179 } 180 181 int StreamCloseCount(uint32 stream) { 182 return std::count(streams_.begin(), streams_.end(), stream); 183 } 184 185 bool WasStreamClosed(uint32 stream) { 186 return std::find(streams_.begin(), streams_.end(), stream) 187 != streams_.end(); 188 } 189 190 private: 191 std::vector<uint32> streams_; 192 }; 193 194 class SignalChannelClosedReopener : public sigslot::has_slots<> { 195 public: 196 SignalChannelClosedReopener(cricket::SctpDataMediaChannel* channel, 197 cricket::SctpDataMediaChannel* peer) 198 : channel_(channel), peer_(peer) {} 199 200 void OnStreamClosed(int stream) { 201 cricket::StreamParams p(cricket::StreamParams::CreateLegacy(stream)); 202 channel_->AddSendStream(p); 203 channel_->AddRecvStream(p); 204 peer_->AddSendStream(p); 205 peer_->AddRecvStream(p); 206 streams_.push_back(stream); 207 } 208 209 int StreamCloseCount(int stream) { 210 return std::count(streams_.begin(), streams_.end(), stream); 211 } 212 213 private: 214 cricket::SctpDataMediaChannel* channel_; 215 cricket::SctpDataMediaChannel* peer_; 216 std::vector<int> streams_; 217 }; 218 219 // SCTP Data Engine testing framework. 220 class SctpDataMediaChannelTest : public testing::Test, 221 public sigslot::has_slots<> { 222 protected: 223 // usrsctp uses the NSS random number generator on non-Android platforms, 224 // so we need to initialize SSL. 225 static void SetUpTestCase() { 226 #ifdef HAVE_NSS_SSL_H 227 // TODO(thorcarpenter): Remove after webrtc switches over to BoringSSL. 228 if (!rtc::NSSContext::InitializeSSL(NULL)) { 229 LOG(LS_WARNING) << "Unabled to initialize NSS."; 230 } 231 #endif // HAVE_NSS_SSL_H 232 rtc::InitializeSSL(); 233 } 234 235 static void TearDownTestCase() { 236 rtc::CleanupSSL(); 237 } 238 239 virtual void SetUp() { 240 engine_.reset(new cricket::SctpDataEngine()); 241 } 242 243 void SetupConnectedChannels() { 244 net1_.reset(new SctpFakeNetworkInterface(rtc::Thread::Current())); 245 net2_.reset(new SctpFakeNetworkInterface(rtc::Thread::Current())); 246 recv1_.reset(new SctpFakeDataReceiver()); 247 recv2_.reset(new SctpFakeDataReceiver()); 248 chan1_.reset(CreateChannel(net1_.get(), recv1_.get())); 249 chan1_->set_debug_name("chan1/connector"); 250 chan2_.reset(CreateChannel(net2_.get(), recv2_.get())); 251 chan2_->set_debug_name("chan2/listener"); 252 // Setup two connected channels ready to send and receive. 253 net1_->SetDestination(chan2_.get()); 254 net2_->SetDestination(chan1_.get()); 255 256 LOG(LS_VERBOSE) << "Channel setup ----------------------------- "; 257 AddStream(1); 258 AddStream(2); 259 260 LOG(LS_VERBOSE) << "Connect the channels -----------------------------"; 261 // chan1 wants to setup a data connection. 262 chan1_->SetReceive(true); 263 // chan1 will have sent chan2 a request to setup a data connection. After 264 // chan2 accepts the offer, chan2 connects to chan1 with the following. 265 chan2_->SetReceive(true); 266 chan2_->SetSend(true); 267 // Makes sure that network packets are delivered and simulates a 268 // deterministic and realistic small timing delay between the SetSend calls. 269 ProcessMessagesUntilIdle(); 270 271 // chan1 and chan2 are now connected so chan1 enables sending to complete 272 // the creation of the connection. 273 chan1_->SetSend(true); 274 } 275 276 virtual void TearDown() { 277 channel1()->SetSend(false); 278 channel2()->SetSend(false); 279 280 // Process messages until idle to prevent a sent packet from being dropped 281 // and causing memory leaks (not being deleted by the receiver). 282 ProcessMessagesUntilIdle(); 283 } 284 285 void AddStream(int ssrc) { 286 cricket::StreamParams p(cricket::StreamParams::CreateLegacy(ssrc)); 287 chan1_->AddSendStream(p); 288 chan1_->AddRecvStream(p); 289 chan2_->AddSendStream(p); 290 chan2_->AddRecvStream(p); 291 } 292 293 cricket::SctpDataMediaChannel* CreateChannel( 294 SctpFakeNetworkInterface* net, SctpFakeDataReceiver* recv) { 295 cricket::SctpDataMediaChannel* channel = 296 static_cast<cricket::SctpDataMediaChannel*>(engine_->CreateChannel( 297 cricket::DCT_SCTP)); 298 channel->SetInterface(net); 299 // When data is received, pass it to the SctpFakeDataReceiver. 300 channel->SignalDataReceived.connect( 301 recv, &SctpFakeDataReceiver::OnDataReceived); 302 return channel; 303 } 304 305 bool SendData(cricket::SctpDataMediaChannel* chan, uint32 ssrc, 306 const std::string& msg, 307 cricket::SendDataResult* result) { 308 cricket::SendDataParams params; 309 params.ssrc = ssrc; 310 311 return chan->SendData(params, rtc::Buffer( 312 &msg[0], msg.length()), result); 313 } 314 315 bool ReceivedData(const SctpFakeDataReceiver* recv, uint32 ssrc, 316 const std::string& msg ) { 317 return (recv->received() && 318 recv->last_params().ssrc == ssrc && 319 recv->last_data() == msg); 320 } 321 322 bool ProcessMessagesUntilIdle() { 323 rtc::Thread* thread = rtc::Thread::Current(); 324 while (!thread->empty()) { 325 rtc::Message msg; 326 if (thread->Get(&msg, rtc::kForever)) { 327 thread->Dispatch(&msg); 328 } 329 } 330 return !thread->IsQuitting(); 331 } 332 333 cricket::SctpDataMediaChannel* channel1() { return chan1_.get(); } 334 cricket::SctpDataMediaChannel* channel2() { return chan2_.get(); } 335 SctpFakeDataReceiver* receiver1() { return recv1_.get(); } 336 SctpFakeDataReceiver* receiver2() { return recv2_.get(); } 337 338 private: 339 rtc::scoped_ptr<cricket::SctpDataEngine> engine_; 340 rtc::scoped_ptr<SctpFakeNetworkInterface> net1_; 341 rtc::scoped_ptr<SctpFakeNetworkInterface> net2_; 342 rtc::scoped_ptr<SctpFakeDataReceiver> recv1_; 343 rtc::scoped_ptr<SctpFakeDataReceiver> recv2_; 344 rtc::scoped_ptr<cricket::SctpDataMediaChannel> chan1_; 345 rtc::scoped_ptr<cricket::SctpDataMediaChannel> chan2_; 346 }; 347 348 // Verifies that SignalReadyToSend is fired. 349 TEST_F(SctpDataMediaChannelTest, SignalReadyToSend) { 350 SetupConnectedChannels(); 351 352 SignalReadyToSendObserver signal_observer_1; 353 SignalReadyToSendObserver signal_observer_2; 354 355 channel1()->SignalReadyToSend.connect(&signal_observer_1, 356 &SignalReadyToSendObserver::OnSignaled); 357 channel2()->SignalReadyToSend.connect(&signal_observer_2, 358 &SignalReadyToSendObserver::OnSignaled); 359 360 cricket::SendDataResult result; 361 ASSERT_TRUE(SendData(channel1(), 1, "hello?", &result)); 362 EXPECT_EQ(cricket::SDR_SUCCESS, result); 363 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hello?"), 1000); 364 ASSERT_TRUE(SendData(channel2(), 2, "hi chan1", &result)); 365 EXPECT_EQ(cricket::SDR_SUCCESS, result); 366 EXPECT_TRUE_WAIT(ReceivedData(receiver1(), 2, "hi chan1"), 1000); 367 368 EXPECT_TRUE_WAIT(signal_observer_1.IsSignaled(true), 1000); 369 EXPECT_TRUE_WAIT(signal_observer_2.IsSignaled(true), 1000); 370 } 371 372 TEST_F(SctpDataMediaChannelTest, SendData) { 373 SetupConnectedChannels(); 374 375 cricket::SendDataResult result; 376 LOG(LS_VERBOSE) << "chan1 sending: 'hello?' -----------------------------"; 377 ASSERT_TRUE(SendData(channel1(), 1, "hello?", &result)); 378 EXPECT_EQ(cricket::SDR_SUCCESS, result); 379 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hello?"), 1000); 380 LOG(LS_VERBOSE) << "recv2.received=" << receiver2()->received() 381 << ", recv2.last_params.ssrc=" 382 << receiver2()->last_params().ssrc 383 << ", recv2.last_params.timestamp=" 384 << receiver2()->last_params().ssrc 385 << ", recv2.last_params.seq_num=" 386 << receiver2()->last_params().seq_num 387 << ", recv2.last_data=" << receiver2()->last_data(); 388 389 LOG(LS_VERBOSE) << "chan2 sending: 'hi chan1' -----------------------------"; 390 ASSERT_TRUE(SendData(channel2(), 2, "hi chan1", &result)); 391 EXPECT_EQ(cricket::SDR_SUCCESS, result); 392 EXPECT_TRUE_WAIT(ReceivedData(receiver1(), 2, "hi chan1"), 1000); 393 LOG(LS_VERBOSE) << "recv1.received=" << receiver1()->received() 394 << ", recv1.last_params.ssrc=" 395 << receiver1()->last_params().ssrc 396 << ", recv1.last_params.timestamp=" 397 << receiver1()->last_params().ssrc 398 << ", recv1.last_params.seq_num=" 399 << receiver1()->last_params().seq_num 400 << ", recv1.last_data=" << receiver1()->last_data(); 401 } 402 403 // Sends a lot of large messages at once and verifies SDR_BLOCK is returned. 404 TEST_F(SctpDataMediaChannelTest, SendDataBlocked) { 405 SetupConnectedChannels(); 406 407 cricket::SendDataResult result; 408 cricket::SendDataParams params; 409 params.ssrc = 1; 410 411 std::vector<char> buffer(1024 * 64, 0); 412 413 for (size_t i = 0; i < 100; ++i) { 414 channel1()->SendData( 415 params, rtc::Buffer(&buffer[0], buffer.size()), &result); 416 if (result == cricket::SDR_BLOCK) 417 break; 418 } 419 420 EXPECT_EQ(cricket::SDR_BLOCK, result); 421 } 422 423 TEST_F(SctpDataMediaChannelTest, ClosesRemoteStream) { 424 SetupConnectedChannels(); 425 SignalChannelClosedObserver chan_1_sig_receiver, chan_2_sig_receiver; 426 chan_1_sig_receiver.BindSelf(channel1()); 427 chan_2_sig_receiver.BindSelf(channel2()); 428 429 cricket::SendDataResult result; 430 ASSERT_TRUE(SendData(channel1(), 1, "hello?", &result)); 431 EXPECT_EQ(cricket::SDR_SUCCESS, result); 432 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hello?"), 1000); 433 ASSERT_TRUE(SendData(channel2(), 2, "hi chan1", &result)); 434 EXPECT_EQ(cricket::SDR_SUCCESS, result); 435 EXPECT_TRUE_WAIT(ReceivedData(receiver1(), 2, "hi chan1"), 1000); 436 437 // Close channel 1. Channel 2 should notify us. 438 channel1()->RemoveSendStream(1); 439 EXPECT_TRUE_WAIT(chan_2_sig_receiver.WasStreamClosed(1), 1000); 440 } 441 442 TEST_F(SctpDataMediaChannelTest, ClosesTwoRemoteStreams) { 443 SetupConnectedChannels(); 444 AddStream(3); 445 SignalChannelClosedObserver chan_1_sig_receiver, chan_2_sig_receiver; 446 chan_1_sig_receiver.BindSelf(channel1()); 447 chan_2_sig_receiver.BindSelf(channel2()); 448 449 cricket::SendDataResult result; 450 ASSERT_TRUE(SendData(channel1(), 1, "hello?", &result)); 451 EXPECT_EQ(cricket::SDR_SUCCESS, result); 452 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hello?"), 1000); 453 ASSERT_TRUE(SendData(channel2(), 2, "hi chan1", &result)); 454 EXPECT_EQ(cricket::SDR_SUCCESS, result); 455 EXPECT_TRUE_WAIT(ReceivedData(receiver1(), 2, "hi chan1"), 1000); 456 457 // Close two streams on one side. 458 channel2()->RemoveSendStream(2); 459 channel2()->RemoveSendStream(3); 460 EXPECT_TRUE_WAIT(chan_1_sig_receiver.WasStreamClosed(2), 1000); 461 EXPECT_TRUE_WAIT(chan_1_sig_receiver.WasStreamClosed(3), 1000); 462 } 463 464 TEST_F(SctpDataMediaChannelTest, ClosesStreamsOnBothSides) { 465 SetupConnectedChannels(); 466 AddStream(3); 467 AddStream(4); 468 SignalChannelClosedObserver chan_1_sig_receiver, chan_2_sig_receiver; 469 chan_1_sig_receiver.BindSelf(channel1()); 470 chan_2_sig_receiver.BindSelf(channel2()); 471 472 cricket::SendDataResult result; 473 ASSERT_TRUE(SendData(channel1(), 1, "hello?", &result)); 474 EXPECT_EQ(cricket::SDR_SUCCESS, result); 475 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hello?"), 1000); 476 ASSERT_TRUE(SendData(channel2(), 2, "hi chan1", &result)); 477 EXPECT_EQ(cricket::SDR_SUCCESS, result); 478 EXPECT_TRUE_WAIT(ReceivedData(receiver1(), 2, "hi chan1"), 1000); 479 480 // Close one stream on channel1(), while closing three streams on 481 // channel2(). They will conflict (only one side can close anything at a 482 // time, apparently). Test the resolution of the conflict. 483 channel1()->RemoveSendStream(1); 484 485 channel2()->RemoveSendStream(2); 486 channel2()->RemoveSendStream(3); 487 channel2()->RemoveSendStream(4); 488 EXPECT_TRUE_WAIT(chan_2_sig_receiver.WasStreamClosed(1), 1000); 489 EXPECT_TRUE_WAIT(chan_1_sig_receiver.WasStreamClosed(2), 1000); 490 EXPECT_TRUE_WAIT(chan_1_sig_receiver.WasStreamClosed(3), 1000); 491 EXPECT_TRUE_WAIT(chan_1_sig_receiver.WasStreamClosed(4), 1000); 492 } 493 494 TEST_F(SctpDataMediaChannelTest, ReusesAStream) { 495 // Shut down channel 1, then open it up again for reuse. 496 SetupConnectedChannels(); 497 cricket::SendDataResult result; 498 SignalChannelClosedObserver chan_2_sig_receiver; 499 chan_2_sig_receiver.BindSelf(channel2()); 500 501 ASSERT_TRUE(SendData(channel1(), 1, "hello?", &result)); 502 EXPECT_EQ(cricket::SDR_SUCCESS, result); 503 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hello?"), 1000); 504 505 channel1()->RemoveSendStream(1); 506 EXPECT_TRUE_WAIT(chan_2_sig_receiver.WasStreamClosed(1), 1000); 507 // Channel 1 is gone now. 508 509 // Create a new channel 1. 510 AddStream(1); 511 ASSERT_TRUE(SendData(channel1(), 1, "hi?", &result)); 512 EXPECT_EQ(cricket::SDR_SUCCESS, result); 513 EXPECT_TRUE_WAIT(ReceivedData(receiver2(), 1, "hi?"), 1000); 514 channel1()->RemoveSendStream(1); 515 EXPECT_TRUE_WAIT(chan_2_sig_receiver.StreamCloseCount(1) == 2, 1000); 516 } 517