3 * Copyright 2004 Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #include "webrtc/p2p/base/basicpacketsocketfactory.h"
29 #include "webrtc/p2p/base/portproxy.h"
30 #include "webrtc/p2p/base/relayport.h"
31 #include "webrtc/p2p/base/stunport.h"
32 #include "webrtc/p2p/base/tcpport.h"
33 #include "webrtc/p2p/base/testrelayserver.h"
34 #include "webrtc/p2p/base/teststunserver.h"
35 #include "webrtc/p2p/base/testturnserver.h"
36 #include "webrtc/p2p/base/transport.h"
37 #include "webrtc/p2p/base/turnport.h"
38 #include "webrtc/base/crc32.h"
39 #include "webrtc/base/gunit.h"
40 #include "webrtc/base/helpers.h"
41 #include "webrtc/base/logging.h"
42 #include "webrtc/base/natserver.h"
43 #include "webrtc/base/natsocketfactory.h"
44 #include "webrtc/base/physicalsocketserver.h"
45 #include "webrtc/base/scoped_ptr.h"
46 #include "webrtc/base/socketaddress.h"
47 #include "webrtc/base/ssladapter.h"
48 #include "webrtc/base/stringutils.h"
49 #include "webrtc/base/thread.h"
50 #include "webrtc/base/virtualsocketserver.h"
52 using rtc::AsyncPacketSocket;
53 using rtc::ByteBuffer;
55 using rtc::NAT_OPEN_CONE;
56 using rtc::NAT_ADDR_RESTRICTED;
57 using rtc::NAT_PORT_RESTRICTED;
58 using rtc::NAT_SYMMETRIC;
59 using rtc::PacketSocketFactory;
60 using rtc::scoped_ptr;
62 using rtc::SocketAddress;
63 using namespace cricket;
65 static const int kTimeout = 1000;
66 static const SocketAddress kLocalAddr1("192.168.1.2", 0);
67 static const SocketAddress kLocalAddr2("192.168.1.3", 0);
68 static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_PORT);
69 static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_PORT);
70 static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
71 static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
72 static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
73 static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
74 static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
75 static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
76 static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
77 static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
78 static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
79 static const RelayCredentials kRelayCredentials("test", "test");
81 // TODO: Update these when RFC5245 is completely supported.
82 // Magic value of 30 is from RFC3484, for IPv4 addresses.
83 static const uint32 kDefaultPrflxPriority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
84 30 << 8 | (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
85 static const int STUN_ERROR_BAD_REQUEST_AS_GICE =
86 STUN_ERROR_BAD_REQUEST / 256 * 100 + STUN_ERROR_BAD_REQUEST % 256;
87 static const int STUN_ERROR_UNAUTHORIZED_AS_GICE =
88 STUN_ERROR_UNAUTHORIZED / 256 * 100 + STUN_ERROR_UNAUTHORIZED % 256;
89 static const int STUN_ERROR_SERVER_ERROR_AS_GICE =
90 STUN_ERROR_SERVER_ERROR / 256 * 100 + STUN_ERROR_SERVER_ERROR % 256;
92 static const int kTiebreaker1 = 11111;
93 static const int kTiebreaker2 = 22222;
95 static Candidate GetCandidate(Port* port) {
96 assert(port->Candidates().size() == 1);
97 return port->Candidates()[0];
100 static SocketAddress GetAddress(Port* port) {
101 return GetCandidate(port).address();
104 static IceMessage* CopyStunMessage(const IceMessage* src) {
105 IceMessage* dst = new IceMessage();
112 static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
113 buf->Resize(0); // clear out any existing buffer contents
114 return msg->Write(buf);
117 // Stub port class for testing STUN generation and processing.
118 class TestPort : public Port {
120 TestPort(rtc::Thread* thread, const std::string& type,
121 rtc::PacketSocketFactory* factory, rtc::Network* network,
122 const rtc::IPAddress& ip, int min_port, int max_port,
123 const std::string& username_fragment, const std::string& password)
124 : Port(thread, type, factory, network, ip,
125 min_port, max_port, username_fragment, password) {
129 // Expose GetStunMessage so that we can test it.
130 using cricket::Port::GetStunMessage;
132 // The last StunMessage that was sent on this Port.
133 // TODO: Make these const; requires changes to SendXXXXResponse.
134 ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
135 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
136 int last_stun_error_code() {
138 if (last_stun_msg_) {
139 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
141 code = error_attr->code();
147 virtual void PrepareAddress() {
148 rtc::SocketAddress addr(ip(), min_port());
149 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", Type(),
150 ICE_TYPE_PREFERENCE_HOST, 0, true);
153 // Exposed for testing candidate building.
154 void AddCandidateAddress(const rtc::SocketAddress& addr) {
155 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", Type(),
156 type_preference_, 0, false);
158 void AddCandidateAddress(const rtc::SocketAddress& addr,
159 const rtc::SocketAddress& base_address,
160 const std::string& type,
163 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", type,
164 type_preference, 0, final);
167 virtual Connection* CreateConnection(const Candidate& remote_candidate,
168 CandidateOrigin origin) {
169 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
171 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
172 // in STUN binding requests.
173 conn->set_use_candidate_attr(true);
177 const void* data, size_t size, const rtc::SocketAddress& addr,
178 const rtc::PacketOptions& options, bool payload) {
180 IceMessage* msg = new IceMessage;
181 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
182 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
183 if (!msg->Read(buf)) {
188 buf->SetReadPosition(pos);
189 last_stun_buf_.reset(buf);
190 last_stun_msg_.reset(msg);
192 return static_cast<int>(size);
194 virtual int SetOption(rtc::Socket::Option opt, int value) {
197 virtual int GetOption(rtc::Socket::Option opt, int* value) {
200 virtual int GetError() {
204 last_stun_buf_.reset();
205 last_stun_msg_.reset();
207 void set_type_preference(int type_preference) {
208 type_preference_ = type_preference;
212 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
213 rtc::scoped_ptr<IceMessage> last_stun_msg_;
214 int type_preference_;
217 class TestChannel : public sigslot::has_slots<> {
219 // Takes ownership of |p1| (but not |p2|).
220 TestChannel(Port* p1, Port* p2)
221 : ice_mode_(ICEMODE_FULL), src_(p1), dst_(p2), complete_count_(0),
222 conn_(NULL), remote_request_(), nominated_(false) {
223 src_->SignalPortComplete.connect(
224 this, &TestChannel::OnPortComplete);
225 src_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
226 src_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
229 int complete_count() { return complete_count_; }
230 Connection* conn() { return conn_; }
231 const SocketAddress& remote_address() { return remote_address_; }
232 const std::string remote_fragment() { return remote_frag_; }
235 src_->PrepareAddress();
237 void CreateConnection() {
238 conn_ = src_->CreateConnection(GetCandidate(dst_), Port::ORIGIN_MESSAGE);
239 IceMode remote_ice_mode =
240 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
241 conn_->set_remote_ice_mode(remote_ice_mode);
242 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
243 conn_->SignalStateChange.connect(
244 this, &TestChannel::OnConnectionStateChange);
246 void OnConnectionStateChange(Connection* conn) {
247 if (conn->write_state() == Connection::STATE_WRITABLE) {
248 conn->set_use_candidate_attr(true);
252 void AcceptConnection() {
253 ASSERT_TRUE(remote_request_.get() != NULL);
254 Candidate c = GetCandidate(dst_);
255 c.set_address(remote_address_);
256 conn_ = src_->CreateConnection(c, Port::ORIGIN_MESSAGE);
257 src_->SendBindingResponse(remote_request_.get(), remote_address_);
258 remote_request_.reset();
263 void Ping(uint32 now) {
267 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
271 void OnPortComplete(Port* port) {
274 void SetIceMode(IceMode ice_mode) {
275 ice_mode_ = ice_mode;
278 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
280 IceMessage* msg, const std::string& rf,
281 bool /*port_muxed*/) {
282 ASSERT_EQ(src_.get(), port);
283 if (!remote_address_.IsNil()) {
284 ASSERT_EQ(remote_address_, addr);
286 // MI and PRIORITY attribute should be present in ping requests when port
287 // is in ICEPROTO_RFC5245 mode.
288 const cricket::StunUInt32Attribute* priority_attr =
289 msg->GetUInt32(STUN_ATTR_PRIORITY);
290 const cricket::StunByteStringAttribute* mi_attr =
291 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
292 const cricket::StunUInt32Attribute* fingerprint_attr =
293 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
294 if (src_->IceProtocol() == cricket::ICEPROTO_RFC5245) {
295 EXPECT_TRUE(priority_attr != NULL);
296 EXPECT_TRUE(mi_attr != NULL);
297 EXPECT_TRUE(fingerprint_attr != NULL);
299 EXPECT_TRUE(priority_attr == NULL);
300 EXPECT_TRUE(mi_attr == NULL);
301 EXPECT_TRUE(fingerprint_attr == NULL);
303 remote_address_ = addr;
304 remote_request_.reset(CopyStunMessage(msg));
308 void OnDestroyed(Connection* conn) {
309 ASSERT_EQ(conn_, conn);
313 void OnSrcPortDestroyed(PortInterface* port) {
314 Port* destroyed_src = src_.release();
315 ASSERT_EQ(destroyed_src, port);
318 bool nominated() const { return nominated_; }
322 rtc::scoped_ptr<Port> src_;
327 SocketAddress remote_address_;
328 rtc::scoped_ptr<StunMessage> remote_request_;
329 std::string remote_frag_;
333 class PortTest : public testing::Test, public sigslot::has_slots<> {
336 : main_(rtc::Thread::Current()),
337 pss_(new rtc::PhysicalSocketServer),
338 ss_(new rtc::VirtualSocketServer(pss_.get())),
339 ss_scope_(ss_.get()),
340 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
341 socket_factory_(rtc::Thread::Current()),
342 nat_factory1_(ss_.get(), kNatAddr1),
343 nat_factory2_(ss_.get(), kNatAddr2),
344 nat_socket_factory1_(&nat_factory1_),
345 nat_socket_factory2_(&nat_factory2_),
346 stun_server_(TestStunServer::Create(main_, kStunAddr)),
347 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
348 relay_server_(main_, kRelayUdpIntAddr, kRelayUdpExtAddr,
349 kRelayTcpIntAddr, kRelayTcpExtAddr,
350 kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
351 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
352 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
353 ice_protocol_(cricket::ICEPROTO_GOOGLE),
354 role_conflict_(false),
356 network_.AddIP(rtc::IPAddress(INADDR_ANY));
360 void TestLocalToLocal() {
361 Port* port1 = CreateUdpPort(kLocalAddr1);
362 Port* port2 = CreateUdpPort(kLocalAddr2);
363 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
365 void TestLocalToStun(NATType ntype) {
366 Port* port1 = CreateUdpPort(kLocalAddr1);
367 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
368 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
369 TestConnectivity("udp", port1, StunName(ntype), port2,
370 ntype == NAT_OPEN_CONE, true,
371 ntype != NAT_SYMMETRIC, true);
373 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
374 Port* port1 = CreateUdpPort(kLocalAddr1);
375 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
376 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
377 rtype == RELAY_GTURN, true, true, true);
379 void TestStunToLocal(NATType ntype) {
380 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
381 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
382 Port* port2 = CreateUdpPort(kLocalAddr2);
383 TestConnectivity(StunName(ntype), port1, "udp", port2,
384 true, ntype != NAT_SYMMETRIC, true, true);
386 void TestStunToStun(NATType ntype1, NATType ntype2) {
387 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
388 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
389 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
390 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
391 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
392 ntype2 == NAT_OPEN_CONE,
393 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
394 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
396 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
397 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
398 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
399 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
400 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
401 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
403 void TestTcpToTcp() {
404 Port* port1 = CreateTcpPort(kLocalAddr1);
405 Port* port2 = CreateTcpPort(kLocalAddr2);
406 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
408 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
409 Port* port1 = CreateTcpPort(kLocalAddr1);
410 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
411 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
412 rtype == RELAY_GTURN, false, true, true);
414 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
415 Port* port1 = CreateTcpPort(kLocalAddr1);
416 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
417 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
418 rtype == RELAY_GTURN, false, true, true);
421 // helpers for above functions
422 UDPPort* CreateUdpPort(const SocketAddress& addr) {
423 return CreateUdpPort(addr, &socket_factory_);
425 UDPPort* CreateUdpPort(const SocketAddress& addr,
426 PacketSocketFactory* socket_factory) {
427 UDPPort* port = UDPPort::Create(main_, socket_factory, &network_,
428 addr.ipaddr(), 0, 0, username_, password_);
429 port->SetIceProtocolType(ice_protocol_);
432 TCPPort* CreateTcpPort(const SocketAddress& addr) {
433 TCPPort* port = CreateTcpPort(addr, &socket_factory_);
434 port->SetIceProtocolType(ice_protocol_);
437 TCPPort* CreateTcpPort(const SocketAddress& addr,
438 PacketSocketFactory* socket_factory) {
439 TCPPort* port = TCPPort::Create(main_, socket_factory, &network_,
440 addr.ipaddr(), 0, 0, username_, password_,
442 port->SetIceProtocolType(ice_protocol_);
445 StunPort* CreateStunPort(const SocketAddress& addr,
446 rtc::PacketSocketFactory* factory) {
447 ServerAddresses stun_servers;
448 stun_servers.insert(kStunAddr);
449 StunPort* port = StunPort::Create(main_, factory, &network_,
451 username_, password_, stun_servers);
452 port->SetIceProtocolType(ice_protocol_);
455 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
456 ProtocolType int_proto, ProtocolType ext_proto) {
457 if (rtype == RELAY_TURN) {
458 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
460 return CreateGturnPort(addr, int_proto, ext_proto);
463 TurnPort* CreateTurnPort(const SocketAddress& addr,
464 PacketSocketFactory* socket_factory,
465 ProtocolType int_proto, ProtocolType ext_proto) {
466 return CreateTurnPort(addr, socket_factory,
467 int_proto, ext_proto, kTurnUdpIntAddr);
469 TurnPort* CreateTurnPort(const SocketAddress& addr,
470 PacketSocketFactory* socket_factory,
471 ProtocolType int_proto, ProtocolType ext_proto,
472 const rtc::SocketAddress& server_addr) {
473 TurnPort* port = TurnPort::Create(main_, socket_factory, &network_,
475 username_, password_, ProtocolAddress(
476 server_addr, PROTO_UDP),
477 kRelayCredentials, 0);
478 port->SetIceProtocolType(ice_protocol_);
481 RelayPort* CreateGturnPort(const SocketAddress& addr,
482 ProtocolType int_proto, ProtocolType ext_proto) {
483 RelayPort* port = CreateGturnPort(addr);
484 SocketAddress addrs[] =
485 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
486 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
489 RelayPort* CreateGturnPort(const SocketAddress& addr) {
490 RelayPort* port = RelayPort::Create(main_, &socket_factory_, &network_,
492 username_, password_);
493 // TODO: Add an external address for ext_proto, so that the
494 // other side can connect to this port using a non-UDP protocol.
495 port->SetIceProtocolType(ice_protocol_);
498 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
500 return new rtc::NATServer(type, ss_.get(), addr, ss_.get(), addr);
502 static const char* StunName(NATType type) {
504 case NAT_OPEN_CONE: return "stun(open cone)";
505 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
506 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
507 case NAT_SYMMETRIC: return "stun(symmetric)";
508 default: return "stun(?)";
511 static const char* RelayName(RelayType type, ProtocolType proto) {
512 if (type == RELAY_TURN) {
514 case PROTO_UDP: return "turn(udp)";
515 case PROTO_TCP: return "turn(tcp)";
516 case PROTO_SSLTCP: return "turn(ssltcp)";
517 default: return "turn(?)";
521 case PROTO_UDP: return "gturn(udp)";
522 case PROTO_TCP: return "gturn(tcp)";
523 case PROTO_SSLTCP: return "gturn(ssltcp)";
524 default: return "gturn(?)";
529 void TestCrossFamilyPorts(int type);
531 // This does all the work and then deletes |port1| and |port2|.
532 void TestConnectivity(const char* name1, Port* port1,
533 const char* name2, Port* port2,
534 bool accept, bool same_addr1,
535 bool same_addr2, bool possible);
537 // This connects and disconnects the provided channels in the same sequence as
538 // TestConnectivity with all options set to |true|. It does not delete either
540 void ConnectAndDisconnectChannels(TestChannel* ch1, TestChannel* ch2);
542 void SetIceProtocolType(cricket::IceProtocolType protocol) {
543 ice_protocol_ = protocol;
546 IceMessage* CreateStunMessage(int type) {
547 IceMessage* msg = new IceMessage();
549 msg->SetTransactionID("TESTTESTTEST");
552 IceMessage* CreateStunMessageWithUsername(int type,
553 const std::string& username) {
554 IceMessage* msg = CreateStunMessage(type);
556 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
559 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
560 const std::string& username,
561 const std::string& password) {
562 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
563 addr.ipaddr(), 0, 0, username, password);
564 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
567 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
568 const std::string& username,
569 const std::string& password,
570 cricket::IceProtocolType type,
571 cricket::IceRole role,
573 TestPort* port = CreateTestPort(addr, username, password);
574 port->SetIceProtocolType(type);
575 port->SetIceRole(role);
576 port->SetIceTiebreaker(tiebreaker);
580 void OnRoleConflict(PortInterface* port) {
581 role_conflict_ = true;
583 bool role_conflict() const { return role_conflict_; }
585 void ConnectToSignalDestroyed(PortInterface* port) {
586 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
589 void OnDestroyed(PortInterface* port) {
592 bool destroyed() const { return destroyed_; }
594 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
595 return &nat_socket_factory1_;
600 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
601 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
602 rtc::SocketServerScope ss_scope_;
603 rtc::Network network_;
604 rtc::BasicPacketSocketFactory socket_factory_;
605 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
606 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
607 rtc::NATSocketFactory nat_factory1_;
608 rtc::NATSocketFactory nat_factory2_;
609 rtc::BasicPacketSocketFactory nat_socket_factory1_;
610 rtc::BasicPacketSocketFactory nat_socket_factory2_;
611 scoped_ptr<TestStunServer> stun_server_;
612 TestTurnServer turn_server_;
613 TestRelayServer relay_server_;
614 std::string username_;
615 std::string password_;
616 cricket::IceProtocolType ice_protocol_;
621 void PortTest::TestConnectivity(const char* name1, Port* port1,
622 const char* name2, Port* port2,
623 bool accept, bool same_addr1,
624 bool same_addr2, bool possible) {
625 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
626 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
627 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
629 // Set up channels and ensure both ports will be deleted.
630 TestChannel ch1(port1, port2);
631 TestChannel ch2(port2, port1);
632 EXPECT_EQ(0, ch1.complete_count());
633 EXPECT_EQ(0, ch2.complete_count());
635 // Acquire addresses.
638 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
639 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
641 // Send a ping from src to dst. This may or may not make it.
642 ch1.CreateConnection();
643 ASSERT_TRUE(ch1.conn() != NULL);
644 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
646 WAIT(!ch2.remote_address().IsNil(), kTimeout);
649 // We are able to send a ping from src to dst. This is the case when
650 // sending to UDP ports and cone NATs.
651 EXPECT_TRUE(ch1.remote_address().IsNil());
652 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
654 // Ensure the ping came from the same address used for src.
655 // This is the case unless the source NAT was symmetric.
656 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
657 EXPECT_TRUE(same_addr2);
659 // Send a ping from dst to src.
660 ch2.AcceptConnection();
661 ASSERT_TRUE(ch2.conn() != NULL);
663 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
666 // We can't send a ping from src to dst, so flip it around. This will happen
667 // when the destination NAT is addr/port restricted or symmetric.
668 EXPECT_TRUE(ch1.remote_address().IsNil());
669 EXPECT_TRUE(ch2.remote_address().IsNil());
671 // Send a ping from dst to src. Again, this may or may not make it.
672 ch2.CreateConnection();
673 ASSERT_TRUE(ch2.conn() != NULL);
675 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
677 if (same_addr1 && same_addr2) {
678 // The new ping got back to the source.
679 EXPECT_EQ(Connection::STATE_READABLE, ch1.conn()->read_state());
680 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
682 // First connection may not be writable if the first ping did not get
683 // through. So we will have to do another.
684 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
686 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
689 } else if (!same_addr1 && possible) {
690 // The new ping went to the candidate address, but that address was bad.
691 // This will happen when the source NAT is symmetric.
692 EXPECT_TRUE(ch1.remote_address().IsNil());
693 EXPECT_TRUE(ch2.remote_address().IsNil());
695 // However, since we have now sent a ping to the source IP, we should be
696 // able to get a ping from it. This gives us the real source address.
698 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
699 EXPECT_EQ(Connection::STATE_READ_INIT, ch2.conn()->read_state());
700 EXPECT_TRUE(ch1.remote_address().IsNil());
702 // Pick up the actual address and establish the connection.
703 ch2.AcceptConnection();
704 ASSERT_TRUE(ch2.conn() != NULL);
706 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
708 } else if (!same_addr2 && possible) {
709 // The new ping came in, but from an unexpected address. This will happen
710 // when the destination NAT is symmetric.
711 EXPECT_FALSE(ch1.remote_address().IsNil());
712 EXPECT_EQ(Connection::STATE_READ_INIT, ch1.conn()->read_state());
714 // Update our address and complete the connection.
715 ch1.AcceptConnection();
717 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
719 } else { // (!possible)
720 // There should be s no way for the pings to reach each other. Check it.
721 EXPECT_TRUE(ch1.remote_address().IsNil());
722 EXPECT_TRUE(ch2.remote_address().IsNil());
724 WAIT(!ch2.remote_address().IsNil(), kTimeout);
725 EXPECT_TRUE(ch1.remote_address().IsNil());
726 EXPECT_TRUE(ch2.remote_address().IsNil());
730 // Everything should be good, unless we know the situation is impossible.
731 ASSERT_TRUE(ch1.conn() != NULL);
732 ASSERT_TRUE(ch2.conn() != NULL);
734 EXPECT_EQ(Connection::STATE_READABLE, ch1.conn()->read_state());
735 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
736 EXPECT_EQ(Connection::STATE_READABLE, ch2.conn()->read_state());
737 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
739 EXPECT_NE(Connection::STATE_READABLE, ch1.conn()->read_state());
740 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
741 EXPECT_NE(Connection::STATE_READABLE, ch2.conn()->read_state());
742 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
745 // Tear down and ensure that goes smoothly.
748 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
749 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
752 void PortTest::ConnectAndDisconnectChannels(TestChannel* ch1,
754 // Acquire addresses.
758 // Send a ping from src to dst.
759 ch1->CreateConnection();
760 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
762 WAIT(!ch2->remote_address().IsNil(), kTimeout);
764 // Send a ping from dst to src.
765 ch2->AcceptConnection();
767 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
770 // Destroy the connections.
775 class FakePacketSocketFactory : public rtc::PacketSocketFactory {
777 FakePacketSocketFactory()
778 : next_udp_socket_(NULL),
779 next_server_tcp_socket_(NULL),
780 next_client_tcp_socket_(NULL) {
782 virtual ~FakePacketSocketFactory() { }
784 virtual AsyncPacketSocket* CreateUdpSocket(
785 const SocketAddress& address, int min_port, int max_port) {
786 EXPECT_TRUE(next_udp_socket_ != NULL);
787 AsyncPacketSocket* result = next_udp_socket_;
788 next_udp_socket_ = NULL;
792 virtual AsyncPacketSocket* CreateServerTcpSocket(
793 const SocketAddress& local_address, int min_port, int max_port,
795 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
796 AsyncPacketSocket* result = next_server_tcp_socket_;
797 next_server_tcp_socket_ = NULL;
801 // TODO: |proxy_info| and |user_agent| should be set
802 // per-factory and not when socket is created.
803 virtual AsyncPacketSocket* CreateClientTcpSocket(
804 const SocketAddress& local_address, const SocketAddress& remote_address,
805 const rtc::ProxyInfo& proxy_info,
806 const std::string& user_agent, int opts) {
807 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
808 AsyncPacketSocket* result = next_client_tcp_socket_;
809 next_client_tcp_socket_ = NULL;
813 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
814 next_udp_socket_ = next_udp_socket;
816 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
817 next_server_tcp_socket_ = next_server_tcp_socket;
819 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
820 next_client_tcp_socket_ = next_client_tcp_socket;
822 rtc::AsyncResolverInterface* CreateAsyncResolver() {
827 AsyncPacketSocket* next_udp_socket_;
828 AsyncPacketSocket* next_server_tcp_socket_;
829 AsyncPacketSocket* next_client_tcp_socket_;
832 class FakeAsyncPacketSocket : public AsyncPacketSocket {
834 // Returns current local address. Address may be set to NULL if the
835 // socket is not bound yet (GetState() returns STATE_BINDING).
836 virtual SocketAddress GetLocalAddress() const {
837 return SocketAddress();
840 // Returns remote address. Returns zeroes if this is not a client TCP socket.
841 virtual SocketAddress GetRemoteAddress() const {
842 return SocketAddress();
846 virtual int Send(const void *pv, size_t cb,
847 const rtc::PacketOptions& options) {
848 return static_cast<int>(cb);
850 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
851 const rtc::PacketOptions& options) {
852 return static_cast<int>(cb);
854 virtual int Close() {
858 virtual State GetState() const { return state_; }
859 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
860 virtual int SetOption(Socket::Option opt, int value) { return 0; }
861 virtual int GetError() const { return 0; }
862 virtual void SetError(int error) { }
864 void set_state(State state) { state_ = state; }
871 TEST_F(PortTest, TestLocalToLocal) {
875 TEST_F(PortTest, TestLocalToConeNat) {
876 TestLocalToStun(NAT_OPEN_CONE);
879 TEST_F(PortTest, TestLocalToARNat) {
880 TestLocalToStun(NAT_ADDR_RESTRICTED);
883 TEST_F(PortTest, TestLocalToPRNat) {
884 TestLocalToStun(NAT_PORT_RESTRICTED);
887 TEST_F(PortTest, TestLocalToSymNat) {
888 TestLocalToStun(NAT_SYMMETRIC);
891 // Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
892 TEST_F(PortTest, DISABLED_TestLocalToTurn) {
893 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
896 TEST_F(PortTest, TestLocalToGturn) {
897 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
900 TEST_F(PortTest, TestLocalToTcpGturn) {
901 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
904 TEST_F(PortTest, TestLocalToSslTcpGturn) {
905 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
909 TEST_F(PortTest, TestConeNatToLocal) {
910 TestStunToLocal(NAT_OPEN_CONE);
913 TEST_F(PortTest, TestConeNatToConeNat) {
914 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
917 TEST_F(PortTest, TestConeNatToARNat) {
918 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
921 TEST_F(PortTest, TestConeNatToPRNat) {
922 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
925 TEST_F(PortTest, TestConeNatToSymNat) {
926 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
929 TEST_F(PortTest, TestConeNatToTurn) {
930 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
933 TEST_F(PortTest, TestConeNatToGturn) {
934 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
937 TEST_F(PortTest, TestConeNatToTcpGturn) {
938 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
941 // Address-restricted NAT -> XXXX
942 TEST_F(PortTest, TestARNatToLocal) {
943 TestStunToLocal(NAT_ADDR_RESTRICTED);
946 TEST_F(PortTest, TestARNatToConeNat) {
947 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
950 TEST_F(PortTest, TestARNatToARNat) {
951 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
954 TEST_F(PortTest, TestARNatToPRNat) {
955 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
958 TEST_F(PortTest, TestARNatToSymNat) {
959 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
962 TEST_F(PortTest, TestARNatToTurn) {
963 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
966 TEST_F(PortTest, TestARNatToGturn) {
967 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
970 TEST_F(PortTest, TestARNATNatToTcpGturn) {
971 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
974 // Port-restricted NAT -> XXXX
975 TEST_F(PortTest, TestPRNatToLocal) {
976 TestStunToLocal(NAT_PORT_RESTRICTED);
979 TEST_F(PortTest, TestPRNatToConeNat) {
980 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
983 TEST_F(PortTest, TestPRNatToARNat) {
984 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
987 TEST_F(PortTest, TestPRNatToPRNat) {
988 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
991 TEST_F(PortTest, TestPRNatToSymNat) {
993 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
996 TEST_F(PortTest, TestPRNatToTurn) {
997 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1000 TEST_F(PortTest, TestPRNatToGturn) {
1001 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1004 TEST_F(PortTest, TestPRNatToTcpGturn) {
1005 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1008 // Symmetric NAT -> XXXX
1009 TEST_F(PortTest, TestSymNatToLocal) {
1010 TestStunToLocal(NAT_SYMMETRIC);
1013 TEST_F(PortTest, TestSymNatToConeNat) {
1014 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1017 TEST_F(PortTest, TestSymNatToARNat) {
1018 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1021 TEST_F(PortTest, TestSymNatToPRNat) {
1023 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1026 TEST_F(PortTest, TestSymNatToSymNat) {
1028 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1031 TEST_F(PortTest, TestSymNatToTurn) {
1032 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1035 TEST_F(PortTest, TestSymNatToGturn) {
1036 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1039 TEST_F(PortTest, TestSymNatToTcpGturn) {
1040 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1043 // Outbound TCP -> XXXX
1044 TEST_F(PortTest, TestTcpToTcp) {
1048 /* TODO: Enable these once testrelayserver can accept external TCP.
1049 TEST_F(PortTest, TestTcpToTcpRelay) {
1050 TestTcpToRelay(PROTO_TCP);
1053 TEST_F(PortTest, TestTcpToSslTcpRelay) {
1054 TestTcpToRelay(PROTO_SSLTCP);
1058 // Outbound SSLTCP -> XXXX
1059 /* TODO: Enable these once testrelayserver can accept external SSL.
1060 TEST_F(PortTest, TestSslTcpToTcpRelay) {
1061 TestSslTcpToRelay(PROTO_TCP);
1064 TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1065 TestSslTcpToRelay(PROTO_SSLTCP);
1069 // This test case verifies standard ICE features in STUN messages. Currently it
1070 // verifies Message Integrity attribute in STUN messages and username in STUN
1071 // binding request will have colon (":") between remote and local username.
1072 TEST_F(PortTest, TestLocalToLocalAsIce) {
1073 SetIceProtocolType(cricket::ICEPROTO_RFC5245);
1074 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1075 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1076 port1->SetIceTiebreaker(kTiebreaker1);
1077 ASSERT_EQ(cricket::ICEPROTO_RFC5245, port1->IceProtocol());
1078 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1079 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1080 port2->SetIceTiebreaker(kTiebreaker2);
1081 ASSERT_EQ(cricket::ICEPROTO_RFC5245, port2->IceProtocol());
1082 // Same parameters as TestLocalToLocal above.
1083 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1086 // This test is trying to validate a successful and failure scenario in a
1087 // loopback test when protocol is RFC5245. For success IceTiebreaker, username
1088 // should remain equal to the request generated by the port and role of port
1089 // must be in controlling.
1090 TEST_F(PortTest, TestLoopbackCallAsIce) {
1091 rtc::scoped_ptr<TestPort> lport(
1092 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1093 lport->SetIceProtocolType(ICEPROTO_RFC5245);
1094 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1095 lport->SetIceTiebreaker(kTiebreaker1);
1096 lport->PrepareAddress();
1097 ASSERT_FALSE(lport->Candidates().empty());
1098 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1099 Port::ORIGIN_MESSAGE);
1102 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1103 IceMessage* msg = lport->last_stun_msg();
1104 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1105 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1106 lport->last_stun_buf()->Length(),
1108 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1109 msg = lport->last_stun_msg();
1110 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1112 // If the tiebreaker value is different from port, we expect a error
1115 lport->AddCandidateAddress(kLocalAddr2);
1116 // Creating a different connection as |conn| is in STATE_READABLE.
1117 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1118 Port::ORIGIN_MESSAGE);
1121 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1122 msg = lport->last_stun_msg();
1123 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1124 rtc::scoped_ptr<IceMessage> modified_req(
1125 CreateStunMessage(STUN_BINDING_REQUEST));
1126 const StunByteStringAttribute* username_attr = msg->GetByteString(
1127 STUN_ATTR_USERNAME);
1128 modified_req->AddAttribute(new StunByteStringAttribute(
1129 STUN_ATTR_USERNAME, username_attr->GetString()));
1130 // To make sure we receive error response, adding tiebreaker less than
1131 // what's present in request.
1132 modified_req->AddAttribute(new StunUInt64Attribute(
1133 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1134 modified_req->AddMessageIntegrity("lpass");
1135 modified_req->AddFingerprint();
1138 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1139 WriteStunMessage(modified_req.get(), buf.get());
1140 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1141 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1142 msg = lport->last_stun_msg();
1143 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1146 // This test verifies role conflict signal is received when there is
1147 // conflict in the role. In this case both ports are in controlling and
1148 // |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1149 // value of tiebreaker, when it receives ping request from |rport| it will
1150 // send role conflict signal.
1151 TEST_F(PortTest, TestIceRoleConflict) {
1152 rtc::scoped_ptr<TestPort> lport(
1153 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1154 lport->SetIceProtocolType(ICEPROTO_RFC5245);
1155 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1156 lport->SetIceTiebreaker(kTiebreaker1);
1157 rtc::scoped_ptr<TestPort> rport(
1158 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1159 rport->SetIceProtocolType(ICEPROTO_RFC5245);
1160 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1161 rport->SetIceTiebreaker(kTiebreaker2);
1163 lport->PrepareAddress();
1164 rport->PrepareAddress();
1165 ASSERT_FALSE(lport->Candidates().empty());
1166 ASSERT_FALSE(rport->Candidates().empty());
1167 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1168 Port::ORIGIN_MESSAGE);
1169 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1170 Port::ORIGIN_MESSAGE);
1173 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1174 IceMessage* msg = rport->last_stun_msg();
1175 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1176 // Send rport binding request to lport.
1177 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1178 rport->last_stun_buf()->Length(),
1181 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1182 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1183 EXPECT_TRUE(role_conflict());
1186 TEST_F(PortTest, TestTcpNoDelay) {
1187 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
1188 int option_value = -1;
1189 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1191 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1192 ASSERT_EQ(1, option_value);
1196 TEST_F(PortTest, TestDelayedBindingUdp) {
1197 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1198 FakePacketSocketFactory socket_factory;
1200 socket_factory.set_next_udp_socket(socket);
1201 scoped_ptr<UDPPort> port(
1202 CreateUdpPort(kLocalAddr1, &socket_factory));
1204 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1205 port->PrepareAddress();
1207 EXPECT_EQ(0U, port->Candidates().size());
1208 socket->SignalAddressReady(socket, kLocalAddr2);
1210 EXPECT_EQ(1U, port->Candidates().size());
1213 TEST_F(PortTest, TestDelayedBindingTcp) {
1214 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1215 FakePacketSocketFactory socket_factory;
1217 socket_factory.set_next_server_tcp_socket(socket);
1218 scoped_ptr<TCPPort> port(
1219 CreateTcpPort(kLocalAddr1, &socket_factory));
1221 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1222 port->PrepareAddress();
1224 EXPECT_EQ(0U, port->Candidates().size());
1225 socket->SignalAddressReady(socket, kLocalAddr2);
1227 EXPECT_EQ(1U, port->Candidates().size());
1230 void PortTest::TestCrossFamilyPorts(int type) {
1231 FakePacketSocketFactory factory;
1232 scoped_ptr<Port> ports[4];
1233 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1234 SocketAddress("192.168.1.4", 0),
1235 SocketAddress("2001:db8::1", 0),
1236 SocketAddress("2001:db8::2", 0)};
1237 for (int i = 0; i < 4; i++) {
1238 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1239 if (type == SOCK_DGRAM) {
1240 factory.set_next_udp_socket(socket);
1241 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1242 } else if (type == SOCK_STREAM) {
1243 factory.set_next_server_tcp_socket(socket);
1244 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1246 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1247 socket->SignalAddressReady(socket, addresses[i]);
1248 ports[i]->PrepareAddress();
1251 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1252 if (type == SOCK_STREAM) {
1253 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1254 factory.set_next_client_tcp_socket(clientsocket);
1256 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1257 Port::ORIGIN_MESSAGE);
1258 EXPECT_TRUE(NULL == c);
1259 EXPECT_EQ(0U, ports[0]->connections().size());
1260 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1261 Port::ORIGIN_MESSAGE);
1262 EXPECT_FALSE(NULL == c);
1263 EXPECT_EQ(1U, ports[0]->connections().size());
1265 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1266 if (type == SOCK_STREAM) {
1267 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1268 factory.set_next_client_tcp_socket(clientsocket);
1270 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1271 Port::ORIGIN_MESSAGE);
1272 EXPECT_TRUE(NULL == c);
1273 EXPECT_EQ(0U, ports[2]->connections().size());
1274 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1275 Port::ORIGIN_MESSAGE);
1276 EXPECT_FALSE(NULL == c);
1277 EXPECT_EQ(1U, ports[2]->connections().size());
1280 TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1281 TestCrossFamilyPorts(SOCK_STREAM);
1284 TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1285 TestCrossFamilyPorts(SOCK_DGRAM);
1288 // This test verifies DSCP value set through SetOption interface can be
1289 // get through DefaultDscpValue.
1290 TEST_F(PortTest, TestDefaultDscpValue) {
1292 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1293 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1295 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1296 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1297 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1299 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1300 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1301 rtc::scoped_ptr<StunPort> stunport(
1302 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1303 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1305 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1306 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1307 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1308 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1309 // Socket is created in PrepareAddress.
1310 turnport1->PrepareAddress();
1311 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1313 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1314 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1315 // This will verify correct value returned without the socket.
1316 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1317 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1318 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1320 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1321 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1324 // Test sending STUN messages in GICE format.
1325 TEST_F(PortTest, TestSendStunMessageAsGice) {
1326 rtc::scoped_ptr<TestPort> lport(
1327 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1328 rtc::scoped_ptr<TestPort> rport(
1329 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1330 lport->SetIceProtocolType(ICEPROTO_GOOGLE);
1331 rport->SetIceProtocolType(ICEPROTO_GOOGLE);
1333 // Send a fake ping from lport to rport.
1334 lport->PrepareAddress();
1335 rport->PrepareAddress();
1336 ASSERT_FALSE(rport->Candidates().empty());
1337 Connection* conn = lport->CreateConnection(rport->Candidates()[0],
1338 Port::ORIGIN_MESSAGE);
1339 rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1342 // Check that it's a proper BINDING-REQUEST.
1343 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1344 IceMessage* msg = lport->last_stun_msg();
1345 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1346 EXPECT_FALSE(msg->IsLegacy());
1347 const StunByteStringAttribute* username_attr = msg->GetByteString(
1348 STUN_ATTR_USERNAME);
1349 ASSERT_TRUE(username_attr != NULL);
1350 EXPECT_EQ("rfraglfrag", username_attr->GetString());
1351 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) == NULL);
1352 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1353 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
1355 // Save a copy of the BINDING-REQUEST for use below.
1356 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1358 // Respond with a BINDING-RESPONSE.
1359 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1360 msg = rport->last_stun_msg();
1361 ASSERT_TRUE(msg != NULL);
1362 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1363 EXPECT_FALSE(msg->IsLegacy());
1364 username_attr = msg->GetByteString(STUN_ATTR_USERNAME);
1365 ASSERT_TRUE(username_attr != NULL); // GICE has a username in the response.
1366 EXPECT_EQ("rfraglfrag", username_attr->GetString());
1367 const StunAddressAttribute* addr_attr = msg->GetAddress(
1368 STUN_ATTR_MAPPED_ADDRESS);
1369 ASSERT_TRUE(addr_attr != NULL);
1370 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1371 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_XOR_MAPPED_ADDRESS) == NULL);
1372 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) == NULL);
1373 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1374 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
1376 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1377 // but we can do it here.
1378 rport->SendBindingErrorResponse(request.get(),
1379 rport->Candidates()[0].address(),
1380 STUN_ERROR_SERVER_ERROR,
1381 STUN_ERROR_REASON_SERVER_ERROR);
1382 msg = rport->last_stun_msg();
1383 ASSERT_TRUE(msg != NULL);
1384 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1385 EXPECT_FALSE(msg->IsLegacy());
1386 username_attr = msg->GetByteString(STUN_ATTR_USERNAME);
1387 ASSERT_TRUE(username_attr != NULL); // GICE has a username in the response.
1388 EXPECT_EQ("rfraglfrag", username_attr->GetString());
1389 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1390 ASSERT_TRUE(error_attr != NULL);
1391 // The GICE wire format for error codes is incorrect.
1392 EXPECT_EQ(STUN_ERROR_SERVER_ERROR_AS_GICE, error_attr->code());
1393 EXPECT_EQ(STUN_ERROR_SERVER_ERROR / 256, error_attr->eclass());
1394 EXPECT_EQ(STUN_ERROR_SERVER_ERROR % 256, error_attr->number());
1395 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1396 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1397 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) == NULL);
1398 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_FINGERPRINT) == NULL);
1401 // Test sending STUN messages in ICE format.
1402 TEST_F(PortTest, TestSendStunMessageAsIce) {
1403 rtc::scoped_ptr<TestPort> lport(
1404 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1405 rtc::scoped_ptr<TestPort> rport(
1406 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1407 lport->SetIceProtocolType(ICEPROTO_RFC5245);
1408 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1409 lport->SetIceTiebreaker(kTiebreaker1);
1410 rport->SetIceProtocolType(ICEPROTO_RFC5245);
1411 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1412 rport->SetIceTiebreaker(kTiebreaker2);
1414 // Send a fake ping from lport to rport.
1415 lport->PrepareAddress();
1416 rport->PrepareAddress();
1417 ASSERT_FALSE(rport->Candidates().empty());
1418 Connection* lconn = lport->CreateConnection(
1419 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1420 Connection* rconn = rport->CreateConnection(
1421 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1424 // Check that it's a proper BINDING-REQUEST.
1425 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1426 IceMessage* msg = lport->last_stun_msg();
1427 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1428 EXPECT_FALSE(msg->IsLegacy());
1429 const StunByteStringAttribute* username_attr =
1430 msg->GetByteString(STUN_ATTR_USERNAME);
1431 ASSERT_TRUE(username_attr != NULL);
1432 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1433 ASSERT_TRUE(priority_attr != NULL);
1434 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1435 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1436 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1437 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1438 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1440 const StunUInt64Attribute* ice_controlling_attr =
1441 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1442 ASSERT_TRUE(ice_controlling_attr != NULL);
1443 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1444 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1445 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1446 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1447 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1448 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1450 // Request should not include ping count.
1451 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1453 // Save a copy of the BINDING-REQUEST for use below.
1454 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1456 // Respond with a BINDING-RESPONSE.
1457 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1458 msg = rport->last_stun_msg();
1459 ASSERT_TRUE(msg != NULL);
1460 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1463 EXPECT_FALSE(msg->IsLegacy());
1464 const StunAddressAttribute* addr_attr = msg->GetAddress(
1465 STUN_ATTR_XOR_MAPPED_ADDRESS);
1466 ASSERT_TRUE(addr_attr != NULL);
1467 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1468 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1469 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1470 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1472 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1473 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1474 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1475 // No USERNAME or PRIORITY in ICE responses.
1476 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1477 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1478 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1479 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1480 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1481 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1483 // Response should not include ping count.
1484 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1486 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1487 // but we can do it here.
1488 rport->SendBindingErrorResponse(request.get(),
1489 lport->Candidates()[0].address(),
1490 STUN_ERROR_SERVER_ERROR,
1491 STUN_ERROR_REASON_SERVER_ERROR);
1492 msg = rport->last_stun_msg();
1493 ASSERT_TRUE(msg != NULL);
1494 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1495 EXPECT_FALSE(msg->IsLegacy());
1496 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1497 ASSERT_TRUE(error_attr != NULL);
1498 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1499 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1500 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1501 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1502 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1504 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1505 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1506 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1507 // No USERNAME with ICE.
1508 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1509 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1511 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1512 // and (incremented) RETRANSMIT_COUNT attributes.
1514 rport->set_send_retransmit_count_attribute(true);
1518 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1519 msg = rport->last_stun_msg();
1520 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1521 const StunUInt64Attribute* ice_controlled_attr =
1522 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1523 ASSERT_TRUE(ice_controlled_attr != NULL);
1524 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1525 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1527 // Request should include ping count.
1528 const StunUInt32Attribute* retransmit_attr =
1529 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1530 ASSERT_TRUE(retransmit_attr != NULL);
1531 EXPECT_EQ(2U, retransmit_attr->value());
1533 // Respond with a BINDING-RESPONSE.
1534 request.reset(CopyStunMessage(msg));
1535 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1536 msg = lport->last_stun_msg();
1538 // Response should include same ping count.
1539 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1540 ASSERT_TRUE(retransmit_attr != NULL);
1541 EXPECT_EQ(2U, retransmit_attr->value());
1544 TEST_F(PortTest, TestUseCandidateAttribute) {
1545 rtc::scoped_ptr<TestPort> lport(
1546 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1547 rtc::scoped_ptr<TestPort> rport(
1548 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1549 lport->SetIceProtocolType(ICEPROTO_RFC5245);
1550 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1551 lport->SetIceTiebreaker(kTiebreaker1);
1552 rport->SetIceProtocolType(ICEPROTO_RFC5245);
1553 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1554 rport->SetIceTiebreaker(kTiebreaker2);
1556 // Send a fake ping from lport to rport.
1557 lport->PrepareAddress();
1558 rport->PrepareAddress();
1559 ASSERT_FALSE(rport->Candidates().empty());
1560 Connection* lconn = lport->CreateConnection(
1561 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1563 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1564 IceMessage* msg = lport->last_stun_msg();
1565 const StunUInt64Attribute* ice_controlling_attr =
1566 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1567 ASSERT_TRUE(ice_controlling_attr != NULL);
1568 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1569 STUN_ATTR_USE_CANDIDATE);
1570 ASSERT_TRUE(use_candidate_attr != NULL);
1573 // Test handling STUN messages in GICE format.
1574 TEST_F(PortTest, TestHandleStunMessageAsGice) {
1575 // Our port will act as the "remote" port.
1576 rtc::scoped_ptr<TestPort> port(
1577 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1578 port->SetIceProtocolType(ICEPROTO_GOOGLE);
1580 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1581 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1582 rtc::SocketAddress addr(kLocalAddr1);
1583 std::string username;
1585 // BINDING-REQUEST from local to remote with valid GICE username and no M-I.
1586 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1588 WriteStunMessage(in_msg.get(), buf.get());
1589 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1590 out_msg.accept(), &username));
1591 EXPECT_TRUE(out_msg.get() != NULL); // Succeeds, since this is GICE.
1592 EXPECT_EQ("lfrag", username);
1594 // Add M-I; should be ignored and rest of message parsed normally.
1595 in_msg->AddMessageIntegrity("password");
1596 WriteStunMessage(in_msg.get(), buf.get());
1597 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1598 out_msg.accept(), &username));
1599 EXPECT_TRUE(out_msg.get() != NULL);
1600 EXPECT_EQ("lfrag", username);
1602 // BINDING-RESPONSE with username, as done in GICE. Should succeed.
1603 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_RESPONSE,
1605 in_msg->AddAttribute(
1606 new StunAddressAttribute(STUN_ATTR_MAPPED_ADDRESS, kLocalAddr2));
1607 WriteStunMessage(in_msg.get(), buf.get());
1608 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1609 out_msg.accept(), &username));
1610 EXPECT_TRUE(out_msg.get() != NULL);
1611 EXPECT_EQ("", username);
1613 // BINDING-RESPONSE without username. Should be tolerated as well.
1614 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1615 in_msg->AddAttribute(
1616 new StunAddressAttribute(STUN_ATTR_MAPPED_ADDRESS, kLocalAddr2));
1617 WriteStunMessage(in_msg.get(), buf.get());
1618 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1619 out_msg.accept(), &username));
1620 EXPECT_TRUE(out_msg.get() != NULL);
1621 EXPECT_EQ("", username);
1623 // BINDING-ERROR-RESPONSE with username and error code.
1624 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_ERROR_RESPONSE,
1626 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1627 STUN_ERROR_SERVER_ERROR_AS_GICE, STUN_ERROR_REASON_SERVER_ERROR));
1628 WriteStunMessage(in_msg.get(), buf.get());
1629 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1630 out_msg.accept(), &username));
1631 ASSERT_TRUE(out_msg.get() != NULL);
1632 EXPECT_EQ("", username);
1633 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1634 // GetStunMessage doesn't unmunge the GICE error code (happens downstream).
1635 EXPECT_EQ(STUN_ERROR_SERVER_ERROR_AS_GICE, out_msg->GetErrorCode()->code());
1636 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1637 out_msg->GetErrorCode()->reason());
1640 // Test handling STUN messages in ICE format.
1641 TEST_F(PortTest, TestHandleStunMessageAsIce) {
1642 // Our port will act as the "remote" port.
1643 rtc::scoped_ptr<TestPort> port(
1644 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1645 port->SetIceProtocolType(ICEPROTO_RFC5245);
1647 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1648 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1649 rtc::SocketAddress addr(kLocalAddr1);
1650 std::string username;
1652 // BINDING-REQUEST from local to remote with valid ICE username,
1653 // MESSAGE-INTEGRITY, and FINGERPRINT.
1654 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1656 in_msg->AddMessageIntegrity("rpass");
1657 in_msg->AddFingerprint();
1658 WriteStunMessage(in_msg.get(), buf.get());
1659 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1660 out_msg.accept(), &username));
1661 EXPECT_TRUE(out_msg.get() != NULL);
1662 EXPECT_EQ("lfrag", username);
1664 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1665 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1666 in_msg->AddAttribute(
1667 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1668 in_msg->AddMessageIntegrity("rpass");
1669 in_msg->AddFingerprint();
1670 WriteStunMessage(in_msg.get(), buf.get());
1671 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1672 out_msg.accept(), &username));
1673 EXPECT_TRUE(out_msg.get() != NULL);
1674 EXPECT_EQ("", username);
1676 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1677 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1678 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1679 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1680 in_msg->AddFingerprint();
1681 WriteStunMessage(in_msg.get(), buf.get());
1682 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1683 out_msg.accept(), &username));
1684 EXPECT_TRUE(out_msg.get() != NULL);
1685 EXPECT_EQ("", username);
1686 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1687 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1688 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1689 out_msg->GetErrorCode()->reason());
1692 // This test verifies port can handle ICE messages in Hybrid mode and switches
1693 // ICEPROTO_RFC5245 mode after successfully handling the message.
1694 TEST_F(PortTest, TestHandleStunMessageAsIceInHybridMode) {
1695 // Our port will act as the "remote" port.
1696 rtc::scoped_ptr<TestPort> port(
1697 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1698 port->SetIceProtocolType(ICEPROTO_HYBRID);
1700 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1701 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1702 rtc::SocketAddress addr(kLocalAddr1);
1703 std::string username;
1705 // BINDING-REQUEST from local to remote with valid ICE username,
1706 // MESSAGE-INTEGRITY, and FINGERPRINT.
1707 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1709 in_msg->AddMessageIntegrity("rpass");
1710 in_msg->AddFingerprint();
1711 WriteStunMessage(in_msg.get(), buf.get());
1712 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1713 out_msg.accept(), &username));
1714 EXPECT_TRUE(out_msg.get() != NULL);
1715 EXPECT_EQ("lfrag", username);
1716 EXPECT_EQ(ICEPROTO_RFC5245, port->IceProtocol());
1719 // This test verifies port can handle GICE messages in Hybrid mode and switches
1720 // ICEPROTO_GOOGLE mode after successfully handling the message.
1721 TEST_F(PortTest, TestHandleStunMessageAsGiceInHybridMode) {
1722 // Our port will act as the "remote" port.
1723 rtc::scoped_ptr<TestPort> port(
1724 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1725 port->SetIceProtocolType(ICEPROTO_HYBRID);
1727 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1728 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1729 rtc::SocketAddress addr(kLocalAddr1);
1730 std::string username;
1732 // BINDING-REQUEST from local to remote with valid GICE username and no M-I.
1733 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1735 WriteStunMessage(in_msg.get(), buf.get());
1736 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1737 out_msg.accept(), &username));
1738 EXPECT_TRUE(out_msg.get() != NULL); // Succeeds, since this is GICE.
1739 EXPECT_EQ("lfrag", username);
1740 EXPECT_EQ(ICEPROTO_GOOGLE, port->IceProtocol());
1743 // Verify port is not switched out of RFC5245 mode if GICE message is received
1745 TEST_F(PortTest, TestHandleStunMessageAsGiceInIceMode) {
1746 // Our port will act as the "remote" port.
1747 rtc::scoped_ptr<TestPort> port(
1748 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1749 port->SetIceProtocolType(ICEPROTO_RFC5245);
1751 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1752 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1753 rtc::SocketAddress addr(kLocalAddr1);
1754 std::string username;
1756 // BINDING-REQUEST from local to remote with valid GICE username and no M-I.
1757 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1759 WriteStunMessage(in_msg.get(), buf.get());
1760 // Should fail as there is no MI and fingerprint.
1761 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1762 out_msg.accept(), &username));
1763 EXPECT_EQ(ICEPROTO_RFC5245, port->IceProtocol());
1767 // Tests handling of GICE binding requests with missing or incorrect usernames.
1768 TEST_F(PortTest, TestHandleStunMessageAsGiceBadUsername) {
1769 rtc::scoped_ptr<TestPort> port(
1770 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1771 port->SetIceProtocolType(ICEPROTO_GOOGLE);
1773 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1774 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1775 rtc::SocketAddress addr(kLocalAddr1);
1776 std::string username;
1778 // BINDING-REQUEST with no username.
1779 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1780 WriteStunMessage(in_msg.get(), buf.get());
1781 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1782 out_msg.accept(), &username));
1783 EXPECT_TRUE(out_msg.get() == NULL);
1784 EXPECT_EQ("", username);
1785 EXPECT_EQ(STUN_ERROR_BAD_REQUEST_AS_GICE, port->last_stun_error_code());
1787 // BINDING-REQUEST with empty username.
1788 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1789 WriteStunMessage(in_msg.get(), buf.get());
1790 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1791 out_msg.accept(), &username));
1792 EXPECT_TRUE(out_msg.get() == NULL);
1793 EXPECT_EQ("", username);
1794 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1796 // BINDING-REQUEST with too-short username.
1797 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "lfra"));
1798 WriteStunMessage(in_msg.get(), buf.get());
1799 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1800 out_msg.accept(), &username));
1801 EXPECT_TRUE(out_msg.get() == NULL);
1802 EXPECT_EQ("", username);
1803 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1805 // BINDING-REQUEST with reversed username.
1806 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1808 WriteStunMessage(in_msg.get(), buf.get());
1809 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1810 out_msg.accept(), &username));
1811 EXPECT_TRUE(out_msg.get() == NULL);
1812 EXPECT_EQ("", username);
1813 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1815 // BINDING-REQUEST with garbage username.
1816 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1818 WriteStunMessage(in_msg.get(), buf.get());
1819 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1820 out_msg.accept(), &username));
1821 EXPECT_TRUE(out_msg.get() == NULL);
1822 EXPECT_EQ("", username);
1823 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED_AS_GICE, port->last_stun_error_code());
1826 // Tests handling of ICE binding requests with missing or incorrect usernames.
1827 TEST_F(PortTest, TestHandleStunMessageAsIceBadUsername) {
1828 rtc::scoped_ptr<TestPort> port(
1829 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1830 port->SetIceProtocolType(ICEPROTO_RFC5245);
1832 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1833 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1834 rtc::SocketAddress addr(kLocalAddr1);
1835 std::string username;
1837 // BINDING-REQUEST with no username.
1838 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1839 in_msg->AddMessageIntegrity("rpass");
1840 in_msg->AddFingerprint();
1841 WriteStunMessage(in_msg.get(), buf.get());
1842 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1843 out_msg.accept(), &username));
1844 EXPECT_TRUE(out_msg.get() == NULL);
1845 EXPECT_EQ("", username);
1846 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1848 // BINDING-REQUEST with empty username.
1849 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1850 in_msg->AddMessageIntegrity("rpass");
1851 in_msg->AddFingerprint();
1852 WriteStunMessage(in_msg.get(), buf.get());
1853 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1854 out_msg.accept(), &username));
1855 EXPECT_TRUE(out_msg.get() == NULL);
1856 EXPECT_EQ("", username);
1857 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1859 // BINDING-REQUEST with too-short username.
1860 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1861 in_msg->AddMessageIntegrity("rpass");
1862 in_msg->AddFingerprint();
1863 WriteStunMessage(in_msg.get(), buf.get());
1864 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1865 out_msg.accept(), &username));
1866 EXPECT_TRUE(out_msg.get() == NULL);
1867 EXPECT_EQ("", username);
1868 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1870 // BINDING-REQUEST with reversed username.
1871 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1873 in_msg->AddMessageIntegrity("rpass");
1874 in_msg->AddFingerprint();
1875 WriteStunMessage(in_msg.get(), buf.get());
1876 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1877 out_msg.accept(), &username));
1878 EXPECT_TRUE(out_msg.get() == NULL);
1879 EXPECT_EQ("", username);
1880 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1882 // BINDING-REQUEST with garbage username.
1883 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1885 in_msg->AddMessageIntegrity("rpass");
1886 in_msg->AddFingerprint();
1887 WriteStunMessage(in_msg.get(), buf.get());
1888 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1889 out_msg.accept(), &username));
1890 EXPECT_TRUE(out_msg.get() == NULL);
1891 EXPECT_EQ("", username);
1892 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1895 // Test handling STUN messages (as ICE) with missing or malformed M-I.
1896 TEST_F(PortTest, TestHandleStunMessageAsIceBadMessageIntegrity) {
1897 // Our port will act as the "remote" port.
1898 rtc::scoped_ptr<TestPort> port(
1899 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1900 port->SetIceProtocolType(ICEPROTO_RFC5245);
1902 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1903 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1904 rtc::SocketAddress addr(kLocalAddr1);
1905 std::string username;
1907 // BINDING-REQUEST from local to remote with valid ICE username and
1908 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1909 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1911 in_msg->AddFingerprint();
1912 WriteStunMessage(in_msg.get(), buf.get());
1913 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1914 out_msg.accept(), &username));
1915 EXPECT_TRUE(out_msg.get() == NULL);
1916 EXPECT_EQ("", username);
1917 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1919 // BINDING-REQUEST from local to remote with valid ICE username and
1920 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1921 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1923 in_msg->AddMessageIntegrity("invalid");
1924 in_msg->AddFingerprint();
1925 WriteStunMessage(in_msg.get(), buf.get());
1926 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1927 out_msg.accept(), &username));
1928 EXPECT_TRUE(out_msg.get() == NULL);
1929 EXPECT_EQ("", username);
1930 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1932 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1933 // by the Connection, not the Port, since they require the remote username.
1934 // Change this test to pass in data via Connection::OnReadPacket instead.
1937 // Test handling STUN messages (as ICE) with missing or malformed FINGERPRINT.
1938 TEST_F(PortTest, TestHandleStunMessageAsIceBadFingerprint) {
1939 // Our port will act as the "remote" port.
1940 rtc::scoped_ptr<TestPort> port(
1941 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1942 port->SetIceProtocolType(ICEPROTO_RFC5245);
1944 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1945 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1946 rtc::SocketAddress addr(kLocalAddr1);
1947 std::string username;
1949 // BINDING-REQUEST from local to remote with valid ICE username and
1950 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1951 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1953 in_msg->AddMessageIntegrity("rpass");
1954 WriteStunMessage(in_msg.get(), buf.get());
1955 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1956 out_msg.accept(), &username));
1957 EXPECT_EQ(0, port->last_stun_error_code());
1959 // Now, add a fingerprint, but munge the message so it's not valid.
1960 in_msg->AddFingerprint();
1961 in_msg->SetTransactionID("TESTTESTBADD");
1962 WriteStunMessage(in_msg.get(), buf.get());
1963 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1964 out_msg.accept(), &username));
1965 EXPECT_EQ(0, port->last_stun_error_code());
1967 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1968 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1969 in_msg->AddAttribute(
1970 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1971 in_msg->AddMessageIntegrity("rpass");
1972 WriteStunMessage(in_msg.get(), buf.get());
1973 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1974 out_msg.accept(), &username));
1975 EXPECT_EQ(0, port->last_stun_error_code());
1977 // Now, add a fingerprint, but munge the message so it's not valid.
1978 in_msg->AddFingerprint();
1979 in_msg->SetTransactionID("TESTTESTBADD");
1980 WriteStunMessage(in_msg.get(), buf.get());
1981 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1982 out_msg.accept(), &username));
1983 EXPECT_EQ(0, port->last_stun_error_code());
1985 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1986 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1987 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1988 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1989 in_msg->AddMessageIntegrity("rpass");
1990 WriteStunMessage(in_msg.get(), buf.get());
1991 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1992 out_msg.accept(), &username));
1993 EXPECT_EQ(0, port->last_stun_error_code());
1995 // Now, add a fingerprint, but munge the message so it's not valid.
1996 in_msg->AddFingerprint();
1997 in_msg->SetTransactionID("TESTTESTBADD");
1998 WriteStunMessage(in_msg.get(), buf.get());
1999 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
2000 out_msg.accept(), &username));
2001 EXPECT_EQ(0, port->last_stun_error_code());
2004 // Test handling of STUN binding indication messages (as ICE). STUN binding
2005 // indications are allowed only to the connection which is in read mode.
2006 TEST_F(PortTest, TestHandleStunBindingIndication) {
2007 rtc::scoped_ptr<TestPort> lport(
2008 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
2009 lport->SetIceProtocolType(ICEPROTO_RFC5245);
2010 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2011 lport->SetIceTiebreaker(kTiebreaker1);
2013 // Verifying encoding and decoding STUN indication message.
2014 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
2015 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
2016 rtc::SocketAddress addr(kLocalAddr1);
2017 std::string username;
2019 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
2020 in_msg->AddFingerprint();
2021 WriteStunMessage(in_msg.get(), buf.get());
2022 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
2023 out_msg.accept(), &username));
2024 EXPECT_TRUE(out_msg.get() != NULL);
2025 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2026 EXPECT_EQ("", username);
2028 // Verify connection can handle STUN indication and updates
2029 // last_ping_received.
2030 rtc::scoped_ptr<TestPort> rport(
2031 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2032 rport->SetIceProtocolType(ICEPROTO_RFC5245);
2033 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2034 rport->SetIceTiebreaker(kTiebreaker2);
2036 lport->PrepareAddress();
2037 rport->PrepareAddress();
2038 ASSERT_FALSE(lport->Candidates().empty());
2039 ASSERT_FALSE(rport->Candidates().empty());
2041 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2042 Port::ORIGIN_MESSAGE);
2043 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2044 Port::ORIGIN_MESSAGE);
2047 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2048 IceMessage* msg = rport->last_stun_msg();
2049 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2050 // Send rport binding request to lport.
2051 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
2052 rport->last_stun_buf()->Length(),
2054 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2055 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
2056 uint32 last_ping_received1 = lconn->last_ping_received();
2058 // Adding a delay of 100ms.
2059 rtc::Thread::Current()->ProcessMessages(100);
2060 // Pinging lconn using stun indication message.
2061 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
2062 uint32 last_ping_received2 = lconn->last_ping_received();
2063 EXPECT_GT(last_ping_received2, last_ping_received1);
2066 TEST_F(PortTest, TestComputeCandidatePriority) {
2067 rtc::scoped_ptr<TestPort> port(
2068 CreateTestPort(kLocalAddr1, "name", "pass"));
2069 port->set_type_preference(90);
2070 port->set_component(177);
2071 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2072 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2073 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2074 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2075 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2076 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2077 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2078 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2079 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2080 // These should all be:
2081 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
2082 uint32 expected_priority_v4 = 1509957199U;
2083 uint32 expected_priority_v6 = 1509959759U;
2084 uint32 expected_priority_ula = 1509962319U;
2085 uint32 expected_priority_v4mapped = expected_priority_v4;
2086 uint32 expected_priority_v4compat = 1509949775U;
2087 uint32 expected_priority_6to4 = 1509954639U;
2088 uint32 expected_priority_teredo = 1509952079U;
2089 uint32 expected_priority_sitelocal = 1509949775U;
2090 uint32 expected_priority_6bone = 1509949775U;
2091 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2092 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2093 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2094 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2095 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2096 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2097 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2098 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2099 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2102 TEST_F(PortTest, TestPortProxyProperties) {
2103 rtc::scoped_ptr<TestPort> port(
2104 CreateTestPort(kLocalAddr1, "name", "pass"));
2105 port->SetIceRole(cricket::ICEROLE_CONTROLLING);
2106 port->SetIceTiebreaker(kTiebreaker1);
2108 // Create a proxy port.
2109 rtc::scoped_ptr<PortProxy> proxy(new PortProxy());
2110 proxy->set_impl(port.get());
2111 EXPECT_EQ(port->Type(), proxy->Type());
2112 EXPECT_EQ(port->Network(), proxy->Network());
2113 EXPECT_EQ(port->GetIceRole(), proxy->GetIceRole());
2114 EXPECT_EQ(port->IceTiebreaker(), proxy->IceTiebreaker());
2117 // In the case of shared socket, one port may be shared by local and stun.
2118 // Test that candidates with different types will have different foundation.
2119 TEST_F(PortTest, TestFoundation) {
2120 rtc::scoped_ptr<TestPort> testport(
2121 CreateTestPort(kLocalAddr1, "name", "pass"));
2122 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2124 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2125 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2127 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2128 EXPECT_NE(testport->Candidates()[0].foundation(),
2129 testport->Candidates()[1].foundation());
2132 // This test verifies the foundation of different types of ICE candidates.
2133 TEST_F(PortTest, TestCandidateFoundation) {
2134 rtc::scoped_ptr<rtc::NATServer> nat_server(
2135 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2136 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2137 udpport1->PrepareAddress();
2138 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2139 udpport2->PrepareAddress();
2140 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2141 udpport2->Candidates()[0].foundation());
2142 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2143 tcpport1->PrepareAddress();
2144 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2145 tcpport2->PrepareAddress();
2146 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2147 tcpport2->Candidates()[0].foundation());
2148 rtc::scoped_ptr<Port> stunport(
2149 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2150 stunport->PrepareAddress();
2151 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2152 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2153 stunport->Candidates()[0].foundation());
2154 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2155 stunport->Candidates()[0].foundation());
2156 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2157 stunport->Candidates()[0].foundation());
2158 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2159 stunport->Candidates()[0].foundation());
2160 // Verify GTURN candidate foundation.
2161 rtc::scoped_ptr<RelayPort> relayport(
2162 CreateGturnPort(kLocalAddr1));
2163 relayport->AddServerAddress(
2164 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2165 relayport->PrepareAddress();
2166 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2167 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2168 relayport->Candidates()[0].foundation());
2169 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2170 relayport->Candidates()[0].foundation());
2171 // Verifying TURN candidate foundation.
2172 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2173 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2174 turnport1->PrepareAddress();
2175 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2176 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2177 turnport1->Candidates()[0].foundation());
2178 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2179 turnport1->Candidates()[0].foundation());
2180 EXPECT_NE(stunport->Candidates()[0].foundation(),
2181 turnport1->Candidates()[0].foundation());
2182 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2183 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2184 turnport2->PrepareAddress();
2185 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2186 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2187 turnport2->Candidates()[0].foundation());
2189 // Running a second turn server, to get different base IP address.
2190 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2191 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2192 TestTurnServer turn_server2(
2193 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2194 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2195 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2197 turnport3->PrepareAddress();
2198 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2199 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2200 turnport2->Candidates()[0].foundation());
2203 // This test verifies the related addresses of different types of
2205 TEST_F(PortTest, TestCandidateRelatedAddress) {
2206 rtc::scoped_ptr<rtc::NATServer> nat_server(
2207 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2208 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2209 udpport->PrepareAddress();
2210 // For UDPPort, related address will be empty.
2211 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2212 // Testing related address for stun candidates.
2213 // For stun candidate related address must be equal to the base
2215 rtc::scoped_ptr<StunPort> stunport(
2216 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2217 stunport->PrepareAddress();
2218 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2219 // Check STUN candidate address.
2220 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2221 kNatAddr1.ipaddr());
2222 // Check STUN candidate related address.
2223 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2224 stunport->GetLocalAddress());
2225 // Verifying the related address for the GTURN candidates.
2226 // NOTE: In case of GTURN related address will be equal to the mapped
2227 // address, but address(mapped) will not be XOR.
2228 rtc::scoped_ptr<RelayPort> relayport(
2229 CreateGturnPort(kLocalAddr1));
2230 relayport->AddServerAddress(
2231 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2232 relayport->PrepareAddress();
2233 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2234 // For Gturn related address is set to "0.0.0.0:0"
2235 EXPECT_EQ(rtc::SocketAddress(),
2236 relayport->Candidates()[0].related_address());
2237 // Verifying the related address for TURN candidate.
2238 // For TURN related address must be equal to the mapped address.
2239 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2240 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2241 turnport->PrepareAddress();
2242 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2243 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2244 turnport->Candidates()[0].address().ipaddr());
2245 EXPECT_EQ(kNatAddr1.ipaddr(),
2246 turnport->Candidates()[0].related_address().ipaddr());
2249 // Test priority value overflow handling when preference is set to 3.
2250 TEST_F(PortTest, TestCandidatePreference) {
2251 cricket::Candidate cand1;
2252 cand1.set_preference(3);
2253 cricket::Candidate cand2;
2254 cand2.set_preference(1);
2255 EXPECT_TRUE(cand1.preference() > cand2.preference());
2258 // Test the Connection priority is calculated correctly.
2259 TEST_F(PortTest, TestConnectionPriority) {
2260 rtc::scoped_ptr<TestPort> lport(
2261 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2262 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2263 rtc::scoped_ptr<TestPort> rport(
2264 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2265 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2266 lport->set_component(123);
2267 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2268 rport->set_component(23);
2269 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2271 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2272 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2275 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2276 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2277 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2278 Connection* lconn = lport->CreateConnection(
2279 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2281 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2283 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2286 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2287 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2288 Connection* rconn = rport->CreateConnection(
2289 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2291 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2293 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2297 TEST_F(PortTest, TestWritableState) {
2298 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2299 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2302 TestChannel ch1(port1, port2);
2303 TestChannel ch2(port2, port1);
2305 // Acquire addresses.
2308 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2309 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2311 // Send a ping from src to dst.
2312 ch1.CreateConnection();
2313 ASSERT_TRUE(ch1.conn() != NULL);
2314 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2315 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2317 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2319 // Data should be unsendable until the connection is accepted.
2320 char data[] = "abcd";
2321 int data_size = ARRAY_SIZE(data);
2322 rtc::PacketOptions options;
2323 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2325 // Accept the connection to return the binding response, transition to
2326 // writable, and allow data to be sent.
2327 ch2.AcceptConnection();
2328 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2330 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2332 // Ask the connection to update state as if enough time has passed to lose
2333 // full writability and 5 pings went unresponded to. We'll accomplish the
2334 // latter by sending pings but not pumping messages.
2335 for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2338 uint32 unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
2339 ch1.conn()->UpdateState(unreliable_timeout_delay);
2340 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2342 // Data should be able to be sent in this state.
2343 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2345 // And now allow the other side to process the pings and send binding
2347 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2350 // Wait long enough for a full timeout (past however long we've already
2352 for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2353 ch1.Ping(unreliable_timeout_delay + i);
2355 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2357 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2359 // Now that the connection has completely timed out, data send should fail.
2360 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2366 TEST_F(PortTest, TestTimeoutForNeverWritable) {
2367 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2368 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2371 TestChannel ch1(port1, port2);
2372 TestChannel ch2(port2, port1);
2374 // Acquire addresses.
2378 ch1.CreateConnection();
2379 ASSERT_TRUE(ch1.conn() != NULL);
2380 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2382 // Attempt to go directly to write timeout.
2383 for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2386 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2387 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2390 // This test verifies the connection setup between ICEMODE_FULL
2391 // and ICEMODE_LITE.
2392 // In this test |ch1| behaves like FULL mode client and we have created
2393 // port which responds to the ping message just like LITE client.
2394 TEST_F(PortTest, TestIceLiteConnectivity) {
2395 TestPort* ice_full_port = CreateTestPort(
2396 kLocalAddr1, "lfrag", "lpass", cricket::ICEPROTO_RFC5245,
2397 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2399 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
2400 kLocalAddr2, "rfrag", "rpass", cricket::ICEPROTO_RFC5245,
2401 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2402 // Setup TestChannel. This behaves like FULL mode client.
2403 TestChannel ch1(ice_full_port, ice_lite_port.get());
2404 ch1.SetIceMode(ICEMODE_FULL);
2406 // Start gathering candidates.
2408 ice_lite_port->PrepareAddress();
2410 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2411 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2413 ch1.CreateConnection();
2414 ASSERT_TRUE(ch1.conn() != NULL);
2415 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2417 // Send ping from full mode client.
2418 // This ping must not have USE_CANDIDATE_ATTR.
2421 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2423 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2424 IceMessage* msg = ice_full_port->last_stun_msg();
2425 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2427 // Respond with a BINDING-RESPONSE from litemode client.
2428 // NOTE: Ideally we should't create connection at this stage from lite
2429 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2430 // But we need a connection to send a response message.
2431 ice_lite_port->CreateConnection(
2432 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2433 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2434 ice_lite_port->SendBindingResponse(
2435 request.get(), ice_full_port->Candidates()[0].address());
2437 // Feeding the respone message from litemode to the full mode connection.
2438 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2439 ice_lite_port->last_stun_buf()->Length(),
2441 // Verifying full mode connection becomes writable from the response.
2442 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2444 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2446 // Clear existing stun messsages. Otherwise we will process old stun
2447 // message right after we send ping.
2448 ice_full_port->Reset();
2449 // Send ping. This must have USE_CANDIDATE_ATTR.
2451 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2452 msg = ice_full_port->last_stun_msg();
2453 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2457 // This test case verifies that the CONTROLLING port does not time out.
2458 TEST_F(PortTest, TestControllingNoTimeout) {
2459 SetIceProtocolType(cricket::ICEPROTO_RFC5245);
2460 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2461 ConnectToSignalDestroyed(port1);
2462 port1->set_timeout_delay(10); // milliseconds
2463 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2464 port1->SetIceTiebreaker(kTiebreaker1);
2466 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2467 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2468 port2->SetIceTiebreaker(kTiebreaker2);
2470 // Set up channels and ensure both ports will be deleted.
2471 TestChannel ch1(port1, port2);
2472 TestChannel ch2(port2, port1);
2474 // Simulate a connection that succeeds, and then is destroyed.
2475 ConnectAndDisconnectChannels(&ch1, &ch2);
2477 // After the connection is destroyed, the port should not be destroyed.
2478 rtc::Thread::Current()->ProcessMessages(kTimeout);
2479 EXPECT_FALSE(destroyed());
2482 // This test case verifies that the CONTROLLED port does time out, but only
2483 // after connectivity is lost.
2484 TEST_F(PortTest, TestControlledTimeout) {
2485 SetIceProtocolType(cricket::ICEPROTO_RFC5245);
2486 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2487 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2488 port1->SetIceTiebreaker(kTiebreaker1);
2490 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2491 ConnectToSignalDestroyed(port2);
2492 port2->set_timeout_delay(10); // milliseconds
2493 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2494 port2->SetIceTiebreaker(kTiebreaker2);
2496 // The connection must not be destroyed before a connection is attempted.
2497 EXPECT_FALSE(destroyed());
2499 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2500 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2502 // Set up channels and ensure both ports will be deleted.
2503 TestChannel ch1(port1, port2);
2504 TestChannel ch2(port2, port1);
2506 // Simulate a connection that succeeds, and then is destroyed.
2507 ConnectAndDisconnectChannels(&ch1, &ch2);
2509 // The controlled port should be destroyed after 10 milliseconds.
2510 EXPECT_TRUE_WAIT(destroyed(), kTimeout);