blob: 261da0aeaefc4f9c79b27682c164aaa829ee93f9 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/basicpacketsocketfactory.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012#include "webrtc/p2p/base/relayport.h"
13#include "webrtc/p2p/base/stunport.h"
14#include "webrtc/p2p/base/tcpport.h"
15#include "webrtc/p2p/base/testrelayserver.h"
16#include "webrtc/p2p/base/teststunserver.h"
17#include "webrtc/p2p/base/testturnserver.h"
18#include "webrtc/p2p/base/transport.h"
19#include "webrtc/p2p/base/turnport.h"
tfarina5237aaf2015-11-10 23:44:30 -080020#include "webrtc/base/arraysize.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000021#include "webrtc/base/crc32.h"
22#include "webrtc/base/gunit.h"
23#include "webrtc/base/helpers.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/natserver.h"
26#include "webrtc/base/natsocketfactory.h"
27#include "webrtc/base/physicalsocketserver.h"
28#include "webrtc/base/scoped_ptr.h"
29#include "webrtc/base/socketaddress.h"
30#include "webrtc/base/ssladapter.h"
31#include "webrtc/base/stringutils.h"
32#include "webrtc/base/thread.h"
33#include "webrtc/base/virtualsocketserver.h"
34
35using rtc::AsyncPacketSocket;
36using rtc::ByteBuffer;
37using rtc::NATType;
38using rtc::NAT_OPEN_CONE;
39using rtc::NAT_ADDR_RESTRICTED;
40using rtc::NAT_PORT_RESTRICTED;
41using rtc::NAT_SYMMETRIC;
42using rtc::PacketSocketFactory;
43using rtc::scoped_ptr;
44using rtc::Socket;
45using rtc::SocketAddress;
46using namespace cricket;
47
48static const int kTimeout = 1000;
49static const SocketAddress kLocalAddr1("192.168.1.2", 0);
50static const SocketAddress kLocalAddr2("192.168.1.3", 0);
deadbeefc5d0d952015-07-16 10:22:21 -070051static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
52static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_UDP_PORT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
54static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
55static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
56static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
57static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
58static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
59static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
60static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
61static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
62static const RelayCredentials kRelayCredentials("test", "test");
63
64// TODO: Update these when RFC5245 is completely supported.
65// Magic value of 30 is from RFC3484, for IPv4 addresses.
Peter Boström0c4e06b2015-10-07 12:23:21 +020066static const uint32_t kDefaultPrflxPriority =
67 ICE_TYPE_PREFERENCE_PRFLX << 24 | 30 << 8 |
68 (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000069
70static const int kTiebreaker1 = 11111;
71static const int kTiebreaker2 = 22222;
72
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070073static const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
74
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000075static Candidate GetCandidate(Port* port) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -070076 assert(port->Candidates().size() >= 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000077 return port->Candidates()[0];
78}
79
80static SocketAddress GetAddress(Port* port) {
81 return GetCandidate(port).address();
82}
83
84static IceMessage* CopyStunMessage(const IceMessage* src) {
85 IceMessage* dst = new IceMessage();
86 ByteBuffer buf;
87 src->Write(&buf);
88 dst->Read(&buf);
89 return dst;
90}
91
92static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
93 buf->Resize(0); // clear out any existing buffer contents
94 return msg->Write(buf);
95}
96
97// Stub port class for testing STUN generation and processing.
98class TestPort : public Port {
99 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000100 TestPort(rtc::Thread* thread,
101 const std::string& type,
102 rtc::PacketSocketFactory* factory,
103 rtc::Network* network,
104 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200105 uint16_t min_port,
106 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000107 const std::string& username_fragment,
108 const std::string& password)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200109 : Port(thread,
110 type,
111 factory,
112 network,
113 ip,
114 min_port,
115 max_port,
116 username_fragment,
117 password) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000118 ~TestPort() {}
119
120 // Expose GetStunMessage so that we can test it.
121 using cricket::Port::GetStunMessage;
122
123 // The last StunMessage that was sent on this Port.
124 // TODO: Make these const; requires changes to SendXXXXResponse.
125 ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
126 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
127 int last_stun_error_code() {
128 int code = 0;
129 if (last_stun_msg_) {
130 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
131 if (error_attr) {
132 code = error_attr->code();
133 }
134 }
135 return code;
136 }
137
138 virtual void PrepareAddress() {
139 rtc::SocketAddress addr(ip(), min_port());
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700140 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141 ICE_TYPE_PREFERENCE_HOST, 0, true);
142 }
143
144 // Exposed for testing candidate building.
145 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700146 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147 type_preference_, 0, false);
148 }
149 void AddCandidateAddress(const rtc::SocketAddress& addr,
150 const rtc::SocketAddress& base_address,
151 const std::string& type,
152 int type_preference,
153 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700154 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000155 type_preference, 0, final);
156 }
157
158 virtual Connection* CreateConnection(const Candidate& remote_candidate,
159 CandidateOrigin origin) {
160 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
161 AddConnection(conn);
162 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
163 // in STUN binding requests.
164 conn->set_use_candidate_attr(true);
165 return conn;
166 }
167 virtual int SendTo(
168 const void* data, size_t size, const rtc::SocketAddress& addr,
169 const rtc::PacketOptions& options, bool payload) {
170 if (!payload) {
171 IceMessage* msg = new IceMessage;
172 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
173 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
174 if (!msg->Read(buf)) {
175 delete msg;
176 delete buf;
177 return -1;
178 }
179 buf->SetReadPosition(pos);
180 last_stun_buf_.reset(buf);
181 last_stun_msg_.reset(msg);
182 }
183 return static_cast<int>(size);
184 }
185 virtual int SetOption(rtc::Socket::Option opt, int value) {
186 return 0;
187 }
188 virtual int GetOption(rtc::Socket::Option opt, int* value) {
189 return -1;
190 }
191 virtual int GetError() {
192 return 0;
193 }
194 void Reset() {
195 last_stun_buf_.reset();
196 last_stun_msg_.reset();
197 }
198 void set_type_preference(int type_preference) {
199 type_preference_ = type_preference;
200 }
201
202 private:
203 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
204 rtc::scoped_ptr<IceMessage> last_stun_msg_;
205 int type_preference_;
206};
207
208class TestChannel : public sigslot::has_slots<> {
209 public:
210 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700211 TestChannel(Port* p1)
212 : ice_mode_(ICEMODE_FULL),
213 port_(p1),
214 complete_count_(0),
215 conn_(NULL),
216 remote_request_(),
217 nominated_(false) {
218 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
219 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
220 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 }
222
223 int complete_count() { return complete_count_; }
224 Connection* conn() { return conn_; }
225 const SocketAddress& remote_address() { return remote_address_; }
226 const std::string remote_fragment() { return remote_frag_; }
227
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700228 void Start() { port_->PrepareAddress(); }
229 void CreateConnection(const Candidate& remote_candidate) {
230 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000231 IceMode remote_ice_mode =
232 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
233 conn_->set_remote_ice_mode(remote_ice_mode);
234 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
235 conn_->SignalStateChange.connect(
236 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700237 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700238 conn_->SignalReadyToSend.connect(this,
239 &TestChannel::OnConnectionReadyToSend);
240 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241 }
242 void OnConnectionStateChange(Connection* conn) {
243 if (conn->write_state() == Connection::STATE_WRITABLE) {
244 conn->set_use_candidate_attr(true);
245 nominated_ = true;
246 }
247 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700248 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700250 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000251 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700252 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700253 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700254 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 remote_request_.reset();
256 }
257 void Ping() {
258 Ping(0);
259 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200260 void Ping(uint32_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700262 if (conn_) {
263 conn_->Destroy();
264 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 }
266
267 void OnPortComplete(Port* port) {
268 complete_count_++;
269 }
270 void SetIceMode(IceMode ice_mode) {
271 ice_mode_ = ice_mode;
272 }
273
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700274 int SendData(const char* data, size_t len) {
275 rtc::PacketOptions options;
276 return conn_->Send(data, len, options);
277 }
278
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
280 ProtocolType proto,
281 IceMessage* msg, const std::string& rf,
282 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700283 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000284 if (!remote_address_.IsNil()) {
285 ASSERT_EQ(remote_address_, addr);
286 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 const cricket::StunUInt32Attribute* priority_attr =
288 msg->GetUInt32(STUN_ATTR_PRIORITY);
289 const cricket::StunByteStringAttribute* mi_attr =
290 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
291 const cricket::StunUInt32Attribute* fingerprint_attr =
292 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700293 EXPECT_TRUE(priority_attr != NULL);
294 EXPECT_TRUE(mi_attr != NULL);
295 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 remote_address_ = addr;
297 remote_request_.reset(CopyStunMessage(msg));
298 remote_frag_ = rf;
299 }
300
301 void OnDestroyed(Connection* conn) {
302 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700303 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700305 // When the connection is destroyed, also clear these fields so future
306 // connections are possible.
307 remote_request_.reset();
308 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000309 }
310
311 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700312 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 ASSERT_EQ(destroyed_src, port);
314 }
315
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700316 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700317
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 bool nominated() const { return nominated_; }
319
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700320 void set_connection_ready_to_send(bool ready) {
321 connection_ready_to_send_ = ready;
322 }
323 bool connection_ready_to_send() const {
324 return connection_ready_to_send_;
325 }
326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700328 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
329 void OnConnectionReadyToSend(Connection* conn) {
330 ASSERT_EQ(conn, conn_);
331 connection_ready_to_send_ = true;
332 }
333
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000334 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700335 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336
337 int complete_count_;
338 Connection* conn_;
339 SocketAddress remote_address_;
340 rtc::scoped_ptr<StunMessage> remote_request_;
341 std::string remote_frag_;
342 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700343 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344};
345
346class PortTest : public testing::Test, public sigslot::has_slots<> {
347 public:
348 PortTest()
349 : main_(rtc::Thread::Current()),
350 pss_(new rtc::PhysicalSocketServer),
351 ss_(new rtc::VirtualSocketServer(pss_.get())),
352 ss_scope_(ss_.get()),
353 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
354 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700355 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
356 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000357 nat_socket_factory1_(&nat_factory1_),
358 nat_socket_factory2_(&nat_factory2_),
359 stun_server_(TestStunServer::Create(main_, kStunAddr)),
360 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700361 relay_server_(main_,
362 kRelayUdpIntAddr,
363 kRelayUdpExtAddr,
364 kRelayTcpIntAddr,
365 kRelayTcpExtAddr,
366 kRelaySslTcpIntAddr,
367 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
369 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370 role_conflict_(false),
371 destroyed_(false) {
372 network_.AddIP(rtc::IPAddress(INADDR_ANY));
373 }
374
375 protected:
376 void TestLocalToLocal() {
377 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700378 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700380 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000381 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
382 }
383 void TestLocalToStun(NATType ntype) {
384 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700385 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000386 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
387 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700388 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000389 TestConnectivity("udp", port1, StunName(ntype), port2,
390 ntype == NAT_OPEN_CONE, true,
391 ntype != NAT_SYMMETRIC, true);
392 }
393 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
394 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700395 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700397 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
399 rtype == RELAY_GTURN, true, true, true);
400 }
401 void TestStunToLocal(NATType ntype) {
402 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
403 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700404 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000405 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700406 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 TestConnectivity(StunName(ntype), port1, "udp", port2,
408 true, ntype != NAT_SYMMETRIC, true, true);
409 }
410 void TestStunToStun(NATType ntype1, NATType ntype2) {
411 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
412 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700413 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
415 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700416 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000417 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
418 ntype2 == NAT_OPEN_CONE,
419 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
420 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
421 }
422 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
423 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
424 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700425 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000426 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700427 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000428 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
429 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
430 }
431 void TestTcpToTcp() {
432 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700433 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000434 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700435 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000436 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
437 }
438 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
439 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700440 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000441 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700442 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
444 rtype == RELAY_GTURN, false, true, true);
445 }
446 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
447 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700448 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700450 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
452 rtype == RELAY_GTURN, false, true, true);
453 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000454 // helpers for above functions
455 UDPPort* CreateUdpPort(const SocketAddress& addr) {
456 return CreateUdpPort(addr, &socket_factory_);
457 }
458 UDPPort* CreateUdpPort(const SocketAddress& addr,
459 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800460 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
461 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462 }
463 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700464 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465 }
466 TCPPort* CreateTcpPort(const SocketAddress& addr,
467 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700468 return TCPPort::Create(main_, socket_factory, &network_,
469 addr.ipaddr(), 0, 0, username_, password_,
470 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 }
472 StunPort* CreateStunPort(const SocketAddress& addr,
473 rtc::PacketSocketFactory* factory) {
474 ServerAddresses stun_servers;
475 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700476 return StunPort::Create(main_, factory, &network_,
477 addr.ipaddr(), 0, 0,
478 username_, password_, stun_servers,
479 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 }
481 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
482 ProtocolType int_proto, ProtocolType ext_proto) {
483 if (rtype == RELAY_TURN) {
484 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
485 } else {
486 return CreateGturnPort(addr, int_proto, ext_proto);
487 }
488 }
489 TurnPort* CreateTurnPort(const SocketAddress& addr,
490 PacketSocketFactory* socket_factory,
491 ProtocolType int_proto, ProtocolType ext_proto) {
492 return CreateTurnPort(addr, socket_factory,
493 int_proto, ext_proto, kTurnUdpIntAddr);
494 }
495 TurnPort* CreateTurnPort(const SocketAddress& addr,
496 PacketSocketFactory* socket_factory,
497 ProtocolType int_proto, ProtocolType ext_proto,
498 const rtc::SocketAddress& server_addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700499 return TurnPort::Create(main_, socket_factory, &network_,
500 addr.ipaddr(), 0, 0,
501 username_, password_, ProtocolAddress(
502 server_addr, PROTO_UDP),
503 kRelayCredentials, 0,
504 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505 }
506 RelayPort* CreateGturnPort(const SocketAddress& addr,
507 ProtocolType int_proto, ProtocolType ext_proto) {
508 RelayPort* port = CreateGturnPort(addr);
509 SocketAddress addrs[] =
510 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
511 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
512 return port;
513 }
514 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700515 // TODO(pthatcher): Remove GTURN.
516 return RelayPort::Create(main_, &socket_factory_, &network_,
517 addr.ipaddr(), 0, 0,
518 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000519 // TODO: Add an external address for ext_proto, so that the
520 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000521 }
522 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
523 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700524 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000525 }
526 static const char* StunName(NATType type) {
527 switch (type) {
528 case NAT_OPEN_CONE: return "stun(open cone)";
529 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
530 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
531 case NAT_SYMMETRIC: return "stun(symmetric)";
532 default: return "stun(?)";
533 }
534 }
535 static const char* RelayName(RelayType type, ProtocolType proto) {
536 if (type == RELAY_TURN) {
537 switch (proto) {
538 case PROTO_UDP: return "turn(udp)";
539 case PROTO_TCP: return "turn(tcp)";
540 case PROTO_SSLTCP: return "turn(ssltcp)";
541 default: return "turn(?)";
542 }
543 } else {
544 switch (proto) {
545 case PROTO_UDP: return "gturn(udp)";
546 case PROTO_TCP: return "gturn(tcp)";
547 case PROTO_SSLTCP: return "gturn(ssltcp)";
548 default: return "gturn(?)";
549 }
550 }
551 }
552
553 void TestCrossFamilyPorts(int type);
554
Peter Thatcherb8b01432015-07-07 16:45:53 -0700555 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
556
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000557 // This does all the work and then deletes |port1| and |port2|.
558 void TestConnectivity(const char* name1, Port* port1,
559 const char* name2, Port* port2,
560 bool accept, bool same_addr1,
561 bool same_addr2, bool possible);
562
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700563 // This connects the provided channels which have already started. |ch1|
564 // should have its Connection created (either through CreateConnection() or
565 // TCP reconnecting mechanism before entering this function.
566 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
567 ASSERT_TRUE(ch1->conn());
568 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
569 ch1->Ping();
570 WAIT(!ch2->remote_address().IsNil(), kTimeout);
571
572 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700573 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700574 ch2->Ping();
575 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
576 kTimeout);
577 }
578
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000579 // This connects and disconnects the provided channels in the same sequence as
580 // TestConnectivity with all options set to |true|. It does not delete either
581 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700582 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
583 // Acquire addresses.
584 ch1->Start();
585 ch2->Start();
586
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700587 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700588 ConnectStartedChannels(ch1, ch2);
589
590 // Destroy the connections.
591 ch1->Stop();
592 ch2->Stop();
593 }
594
595 // This disconnects both end's Connection and make sure ch2 ready for new
596 // connection.
597 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700598 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
599 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
600 ASSERT_TRUE(
601 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
602 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700603
604 // Wait for both OnClose are delivered.
605 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
606 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
607
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700608 // Ensure redundant SignalClose events on TcpConnection won't break tcp
609 // reconnection. Chromium will fire SignalClose for all outstanding IPC
610 // packets during reconnection.
611 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
612 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
613
614 // Speed up destroying ch2's connection such that the test is ready to
615 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700616 ch2->conn()->Destroy();
617 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
618 }
619
620 void TestTcpReconnect(bool ping_after_disconnected,
621 bool send_after_disconnected) {
622 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700623 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700624 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700625 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700626
627 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
628 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
629
630 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700631 TestChannel ch1(port1);
632 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700633 EXPECT_EQ(0, ch1.complete_count());
634 EXPECT_EQ(0, ch2.complete_count());
635
636 ch1.Start();
637 ch2.Start();
638 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
639 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
640
641 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700642 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700643 ConnectStartedChannels(&ch1, &ch2);
644
645 // Shorten the timeout period.
646 const int kTcpReconnectTimeout = kTimeout;
647 static_cast<TCPConnection*>(ch1.conn())
648 ->set_reconnection_timeout(kTcpReconnectTimeout);
649 static_cast<TCPConnection*>(ch2.conn())
650 ->set_reconnection_timeout(kTcpReconnectTimeout);
651
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700652 EXPECT_FALSE(ch1.connection_ready_to_send());
653 EXPECT_FALSE(ch2.connection_ready_to_send());
654
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700655 // Once connected, disconnect them.
656 DisconnectTcpTestChannels(&ch1, &ch2);
657
658 if (send_after_disconnected || ping_after_disconnected) {
659 if (send_after_disconnected) {
660 // First SendData after disconnect should fail but will trigger
661 // reconnect.
662 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
663 }
664
665 if (ping_after_disconnected) {
666 // Ping should trigger reconnect.
667 ch1.Ping();
668 }
669
670 // Wait for channel's outgoing TCPConnection connected.
671 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
672
673 // Verify that we could still connect channels.
674 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700675 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
676 kTcpReconnectTimeout);
677 // Channel2 is the passive one so a new connection is created during
678 // reconnect. This new connection should never have issued EWOULDBLOCK
679 // hence the connection_ready_to_send() should be false.
680 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700681 } else {
682 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700683 // Since the reconnection never happens, the connections should have been
684 // destroyed after the timeout.
685 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
686 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700687 }
688
689 // Tear down and ensure that goes smoothly.
690 ch1.Stop();
691 ch2.Stop();
692 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
693 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
694 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000696 IceMessage* CreateStunMessage(int type) {
697 IceMessage* msg = new IceMessage();
698 msg->SetType(type);
699 msg->SetTransactionID("TESTTESTTEST");
700 return msg;
701 }
702 IceMessage* CreateStunMessageWithUsername(int type,
703 const std::string& username) {
704 IceMessage* msg = CreateStunMessage(type);
705 msg->AddAttribute(
706 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
707 return msg;
708 }
709 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
710 const std::string& username,
711 const std::string& password) {
712 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
713 addr.ipaddr(), 0, 0, username, password);
714 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
715 return port;
716 }
717 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
718 const std::string& username,
719 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000720 cricket::IceRole role,
721 int tiebreaker) {
722 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723 port->SetIceRole(role);
724 port->SetIceTiebreaker(tiebreaker);
725 return port;
726 }
727
728 void OnRoleConflict(PortInterface* port) {
729 role_conflict_ = true;
730 }
731 bool role_conflict() const { return role_conflict_; }
732
733 void ConnectToSignalDestroyed(PortInterface* port) {
734 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
735 }
736
737 void OnDestroyed(PortInterface* port) {
738 destroyed_ = true;
739 }
740 bool destroyed() const { return destroyed_; }
741
742 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
743 return &nat_socket_factory1_;
744 }
745
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700746 protected:
747 rtc::VirtualSocketServer* vss() { return ss_.get(); }
748
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000749 private:
750 rtc::Thread* main_;
751 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
752 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
753 rtc::SocketServerScope ss_scope_;
754 rtc::Network network_;
755 rtc::BasicPacketSocketFactory socket_factory_;
756 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
757 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
758 rtc::NATSocketFactory nat_factory1_;
759 rtc::NATSocketFactory nat_factory2_;
760 rtc::BasicPacketSocketFactory nat_socket_factory1_;
761 rtc::BasicPacketSocketFactory nat_socket_factory2_;
762 scoped_ptr<TestStunServer> stun_server_;
763 TestTurnServer turn_server_;
764 TestRelayServer relay_server_;
765 std::string username_;
766 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000767 bool role_conflict_;
768 bool destroyed_;
769};
770
771void PortTest::TestConnectivity(const char* name1, Port* port1,
772 const char* name2, Port* port2,
773 bool accept, bool same_addr1,
774 bool same_addr2, bool possible) {
775 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
776 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
777 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
778
779 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700780 TestChannel ch1(port1);
781 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782 EXPECT_EQ(0, ch1.complete_count());
783 EXPECT_EQ(0, ch2.complete_count());
784
785 // Acquire addresses.
786 ch1.Start();
787 ch2.Start();
788 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
789 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
790
791 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700792 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000793 ASSERT_TRUE(ch1.conn() != NULL);
794 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
795 ch1.Ping();
796 WAIT(!ch2.remote_address().IsNil(), kTimeout);
797
798 if (accept) {
799 // We are able to send a ping from src to dst. This is the case when
800 // sending to UDP ports and cone NATs.
801 EXPECT_TRUE(ch1.remote_address().IsNil());
802 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
803
804 // Ensure the ping came from the same address used for src.
805 // This is the case unless the source NAT was symmetric.
806 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
807 EXPECT_TRUE(same_addr2);
808
809 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700810 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000811 ASSERT_TRUE(ch2.conn() != NULL);
812 ch2.Ping();
813 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
814 kTimeout);
815 } else {
816 // We can't send a ping from src to dst, so flip it around. This will happen
817 // when the destination NAT is addr/port restricted or symmetric.
818 EXPECT_TRUE(ch1.remote_address().IsNil());
819 EXPECT_TRUE(ch2.remote_address().IsNil());
820
821 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700822 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000823 ASSERT_TRUE(ch2.conn() != NULL);
824 ch2.Ping();
825 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
826
827 if (same_addr1 && same_addr2) {
828 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700829 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000830 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
831
832 // First connection may not be writable if the first ping did not get
833 // through. So we will have to do another.
834 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
835 ch1.Ping();
836 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
837 kTimeout);
838 }
839 } else if (!same_addr1 && possible) {
840 // The new ping went to the candidate address, but that address was bad.
841 // This will happen when the source NAT is symmetric.
842 EXPECT_TRUE(ch1.remote_address().IsNil());
843 EXPECT_TRUE(ch2.remote_address().IsNil());
844
845 // However, since we have now sent a ping to the source IP, we should be
846 // able to get a ping from it. This gives us the real source address.
847 ch1.Ping();
848 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700849 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850 EXPECT_TRUE(ch1.remote_address().IsNil());
851
852 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700853 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854 ASSERT_TRUE(ch2.conn() != NULL);
855 ch2.Ping();
856 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
857 kTimeout);
858 } else if (!same_addr2 && possible) {
859 // The new ping came in, but from an unexpected address. This will happen
860 // when the destination NAT is symmetric.
861 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700862 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863
864 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700865 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 ch1.Ping();
867 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
868 kTimeout);
869 } else { // (!possible)
870 // There should be s no way for the pings to reach each other. Check it.
871 EXPECT_TRUE(ch1.remote_address().IsNil());
872 EXPECT_TRUE(ch2.remote_address().IsNil());
873 ch1.Ping();
874 WAIT(!ch2.remote_address().IsNil(), kTimeout);
875 EXPECT_TRUE(ch1.remote_address().IsNil());
876 EXPECT_TRUE(ch2.remote_address().IsNil());
877 }
878 }
879
880 // Everything should be good, unless we know the situation is impossible.
881 ASSERT_TRUE(ch1.conn() != NULL);
882 ASSERT_TRUE(ch2.conn() != NULL);
883 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700884 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700886 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
888 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700889 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000890 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700891 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
893 }
894
895 // Tear down and ensure that goes smoothly.
896 ch1.Stop();
897 ch2.Stop();
898 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
899 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
900}
901
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902class FakePacketSocketFactory : public rtc::PacketSocketFactory {
903 public:
904 FakePacketSocketFactory()
905 : next_udp_socket_(NULL),
906 next_server_tcp_socket_(NULL),
907 next_client_tcp_socket_(NULL) {
908 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000909 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000911 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200912 uint16_t min_port,
913 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 EXPECT_TRUE(next_udp_socket_ != NULL);
915 AsyncPacketSocket* result = next_udp_socket_;
916 next_udp_socket_ = NULL;
917 return result;
918 }
919
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000920 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200921 uint16_t min_port,
922 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000923 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
925 AsyncPacketSocket* result = next_server_tcp_socket_;
926 next_server_tcp_socket_ = NULL;
927 return result;
928 }
929
930 // TODO: |proxy_info| and |user_agent| should be set
931 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000932 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
933 const SocketAddress& remote_address,
934 const rtc::ProxyInfo& proxy_info,
935 const std::string& user_agent,
936 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
938 AsyncPacketSocket* result = next_client_tcp_socket_;
939 next_client_tcp_socket_ = NULL;
940 return result;
941 }
942
943 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
944 next_udp_socket_ = next_udp_socket;
945 }
946 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
947 next_server_tcp_socket_ = next_server_tcp_socket;
948 }
949 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
950 next_client_tcp_socket_ = next_client_tcp_socket;
951 }
952 rtc::AsyncResolverInterface* CreateAsyncResolver() {
953 return NULL;
954 }
955
956 private:
957 AsyncPacketSocket* next_udp_socket_;
958 AsyncPacketSocket* next_server_tcp_socket_;
959 AsyncPacketSocket* next_client_tcp_socket_;
960};
961
962class FakeAsyncPacketSocket : public AsyncPacketSocket {
963 public:
964 // Returns current local address. Address may be set to NULL if the
965 // socket is not bound yet (GetState() returns STATE_BINDING).
966 virtual SocketAddress GetLocalAddress() const {
967 return SocketAddress();
968 }
969
970 // Returns remote address. Returns zeroes if this is not a client TCP socket.
971 virtual SocketAddress GetRemoteAddress() const {
972 return SocketAddress();
973 }
974
975 // Send a packet.
976 virtual int Send(const void *pv, size_t cb,
977 const rtc::PacketOptions& options) {
978 return static_cast<int>(cb);
979 }
980 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
981 const rtc::PacketOptions& options) {
982 return static_cast<int>(cb);
983 }
984 virtual int Close() {
985 return 0;
986 }
987
988 virtual State GetState() const { return state_; }
989 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
990 virtual int SetOption(Socket::Option opt, int value) { return 0; }
991 virtual int GetError() const { return 0; }
992 virtual void SetError(int error) { }
993
994 void set_state(State state) { state_ = state; }
995
996 private:
997 State state_;
998};
999
1000// Local -> XXXX
1001TEST_F(PortTest, TestLocalToLocal) {
1002 TestLocalToLocal();
1003}
1004
1005TEST_F(PortTest, TestLocalToConeNat) {
1006 TestLocalToStun(NAT_OPEN_CONE);
1007}
1008
1009TEST_F(PortTest, TestLocalToARNat) {
1010 TestLocalToStun(NAT_ADDR_RESTRICTED);
1011}
1012
1013TEST_F(PortTest, TestLocalToPRNat) {
1014 TestLocalToStun(NAT_PORT_RESTRICTED);
1015}
1016
1017TEST_F(PortTest, TestLocalToSymNat) {
1018 TestLocalToStun(NAT_SYMMETRIC);
1019}
1020
1021// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1022TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1023 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1024}
1025
1026TEST_F(PortTest, TestLocalToGturn) {
1027 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1028}
1029
1030TEST_F(PortTest, TestLocalToTcpGturn) {
1031 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1032}
1033
1034TEST_F(PortTest, TestLocalToSslTcpGturn) {
1035 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1036}
1037
1038// Cone NAT -> XXXX
1039TEST_F(PortTest, TestConeNatToLocal) {
1040 TestStunToLocal(NAT_OPEN_CONE);
1041}
1042
1043TEST_F(PortTest, TestConeNatToConeNat) {
1044 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1045}
1046
1047TEST_F(PortTest, TestConeNatToARNat) {
1048 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1049}
1050
1051TEST_F(PortTest, TestConeNatToPRNat) {
1052 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1053}
1054
1055TEST_F(PortTest, TestConeNatToSymNat) {
1056 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1057}
1058
1059TEST_F(PortTest, TestConeNatToTurn) {
1060 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1061}
1062
1063TEST_F(PortTest, TestConeNatToGturn) {
1064 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1065}
1066
1067TEST_F(PortTest, TestConeNatToTcpGturn) {
1068 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1069}
1070
1071// Address-restricted NAT -> XXXX
1072TEST_F(PortTest, TestARNatToLocal) {
1073 TestStunToLocal(NAT_ADDR_RESTRICTED);
1074}
1075
1076TEST_F(PortTest, TestARNatToConeNat) {
1077 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1078}
1079
1080TEST_F(PortTest, TestARNatToARNat) {
1081 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1082}
1083
1084TEST_F(PortTest, TestARNatToPRNat) {
1085 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1086}
1087
1088TEST_F(PortTest, TestARNatToSymNat) {
1089 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1090}
1091
1092TEST_F(PortTest, TestARNatToTurn) {
1093 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1094}
1095
1096TEST_F(PortTest, TestARNatToGturn) {
1097 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1098}
1099
1100TEST_F(PortTest, TestARNATNatToTcpGturn) {
1101 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1102}
1103
1104// Port-restricted NAT -> XXXX
1105TEST_F(PortTest, TestPRNatToLocal) {
1106 TestStunToLocal(NAT_PORT_RESTRICTED);
1107}
1108
1109TEST_F(PortTest, TestPRNatToConeNat) {
1110 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1111}
1112
1113TEST_F(PortTest, TestPRNatToARNat) {
1114 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1115}
1116
1117TEST_F(PortTest, TestPRNatToPRNat) {
1118 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1119}
1120
1121TEST_F(PortTest, TestPRNatToSymNat) {
1122 // Will "fail"
1123 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1124}
1125
1126TEST_F(PortTest, TestPRNatToTurn) {
1127 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1128}
1129
1130TEST_F(PortTest, TestPRNatToGturn) {
1131 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1132}
1133
1134TEST_F(PortTest, TestPRNatToTcpGturn) {
1135 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1136}
1137
1138// Symmetric NAT -> XXXX
1139TEST_F(PortTest, TestSymNatToLocal) {
1140 TestStunToLocal(NAT_SYMMETRIC);
1141}
1142
1143TEST_F(PortTest, TestSymNatToConeNat) {
1144 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1145}
1146
1147TEST_F(PortTest, TestSymNatToARNat) {
1148 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1149}
1150
1151TEST_F(PortTest, TestSymNatToPRNat) {
1152 // Will "fail"
1153 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1154}
1155
1156TEST_F(PortTest, TestSymNatToSymNat) {
1157 // Will "fail"
1158 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1159}
1160
1161TEST_F(PortTest, TestSymNatToTurn) {
1162 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1163}
1164
1165TEST_F(PortTest, TestSymNatToGturn) {
1166 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1167}
1168
1169TEST_F(PortTest, TestSymNatToTcpGturn) {
1170 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1171}
1172
1173// Outbound TCP -> XXXX
1174TEST_F(PortTest, TestTcpToTcp) {
1175 TestTcpToTcp();
1176}
1177
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001178TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1179 TestTcpReconnect(false /* ping */, true /* send */);
1180}
1181
1182TEST_F(PortTest, TestTcpReconnectOnPing) {
1183 TestTcpReconnect(true /* ping */, false /* send */);
1184}
1185
1186TEST_F(PortTest, TestTcpReconnectTimeout) {
1187 TestTcpReconnect(false /* ping */, false /* send */);
1188}
1189
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001190// Test when TcpConnection never connects, the OnClose() will be called to
1191// destroy the connection.
1192TEST_F(PortTest, TestTcpNeverConnect) {
1193 Port* port1 = CreateTcpPort(kLocalAddr1);
1194 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1195 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1196
1197 // Set up a channel and ensure the port will be deleted.
1198 TestChannel ch1(port1);
1199 EXPECT_EQ(0, ch1.complete_count());
1200
1201 ch1.Start();
1202 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1203
1204 rtc::scoped_ptr<rtc::AsyncSocket> server(
1205 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1206 // Bind but not listen.
1207 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1208
1209 Candidate c = GetCandidate(port1);
1210 c.set_address(server->GetLocalAddress());
1211
1212 ch1.CreateConnection(c);
1213 EXPECT_TRUE(ch1.conn());
1214 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1215}
1216
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217/* TODO: Enable these once testrelayserver can accept external TCP.
1218TEST_F(PortTest, TestTcpToTcpRelay) {
1219 TestTcpToRelay(PROTO_TCP);
1220}
1221
1222TEST_F(PortTest, TestTcpToSslTcpRelay) {
1223 TestTcpToRelay(PROTO_SSLTCP);
1224}
1225*/
1226
1227// Outbound SSLTCP -> XXXX
1228/* TODO: Enable these once testrelayserver can accept external SSL.
1229TEST_F(PortTest, TestSslTcpToTcpRelay) {
1230 TestSslTcpToRelay(PROTO_TCP);
1231}
1232
1233TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1234 TestSslTcpToRelay(PROTO_SSLTCP);
1235}
1236*/
1237
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001238// Test that a connection will be dead and deleted if
1239// i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1240// since it was created, or
1241// ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1242// milliseconds since last receiving.
1243TEST_F(PortTest, TestConnectionDead) {
1244 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1245 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1246 TestChannel ch1(port1);
1247 TestChannel ch2(port2);
1248 // Acquire address.
1249 ch1.Start();
1250 ch2.Start();
1251 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1252 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
1253
1254 uint32_t before_created = rtc::Time();
1255 ch1.CreateConnection(GetCandidate(port2));
1256 uint32_t after_created = rtc::Time();
1257 Connection* conn = ch1.conn();
1258 ASSERT(conn != nullptr);
1259 // If the connection has never received anything, it will be dead after
1260 // MIN_CONNECTION_LIFETIME
1261 conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1262 rtc::Thread::Current()->ProcessMessages(100);
1263 EXPECT_TRUE(ch1.conn() != nullptr);
1264 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1265 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1266
1267 // Create a connection again and receive a ping.
1268 ch1.CreateConnection(GetCandidate(port2));
1269 conn = ch1.conn();
1270 ASSERT(conn != nullptr);
1271 uint32_t before_last_receiving = rtc::Time();
1272 conn->ReceivedPing();
1273 uint32_t after_last_receiving = rtc::Time();
1274 // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1275 conn->UpdateState(
1276 before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1277 rtc::Thread::Current()->ProcessMessages(100);
1278 EXPECT_TRUE(ch1.conn() != nullptr);
1279 conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1280 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1281}
1282
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001283// This test case verifies standard ICE features in STUN messages. Currently it
1284// verifies Message Integrity attribute in STUN messages and username in STUN
1285// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001286TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001287 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1288 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1289 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001290 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1291 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1292 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001293 // Same parameters as TestLocalToLocal above.
1294 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1295}
1296
1297// This test is trying to validate a successful and failure scenario in a
1298// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1299// should remain equal to the request generated by the port and role of port
1300// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001301TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001302 rtc::scoped_ptr<TestPort> lport(
1303 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001304 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1305 lport->SetIceTiebreaker(kTiebreaker1);
1306 lport->PrepareAddress();
1307 ASSERT_FALSE(lport->Candidates().empty());
1308 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1309 Port::ORIGIN_MESSAGE);
1310 conn->Ping(0);
1311
1312 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1313 IceMessage* msg = lport->last_stun_msg();
1314 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1315 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1316 lport->last_stun_buf()->Length(),
1317 rtc::PacketTime());
1318 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1319 msg = lport->last_stun_msg();
1320 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1321
1322 // If the tiebreaker value is different from port, we expect a error
1323 // response.
1324 lport->Reset();
1325 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001326 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001327 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1328 Port::ORIGIN_MESSAGE);
1329 conn1->Ping(0);
1330
1331 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1332 msg = lport->last_stun_msg();
1333 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1334 rtc::scoped_ptr<IceMessage> modified_req(
1335 CreateStunMessage(STUN_BINDING_REQUEST));
1336 const StunByteStringAttribute* username_attr = msg->GetByteString(
1337 STUN_ATTR_USERNAME);
1338 modified_req->AddAttribute(new StunByteStringAttribute(
1339 STUN_ATTR_USERNAME, username_attr->GetString()));
1340 // To make sure we receive error response, adding tiebreaker less than
1341 // what's present in request.
1342 modified_req->AddAttribute(new StunUInt64Attribute(
1343 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1344 modified_req->AddMessageIntegrity("lpass");
1345 modified_req->AddFingerprint();
1346
1347 lport->Reset();
1348 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1349 WriteStunMessage(modified_req.get(), buf.get());
1350 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1351 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1352 msg = lport->last_stun_msg();
1353 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1354}
1355
1356// This test verifies role conflict signal is received when there is
1357// conflict in the role. In this case both ports are in controlling and
1358// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1359// value of tiebreaker, when it receives ping request from |rport| it will
1360// send role conflict signal.
1361TEST_F(PortTest, TestIceRoleConflict) {
1362 rtc::scoped_ptr<TestPort> lport(
1363 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001364 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1365 lport->SetIceTiebreaker(kTiebreaker1);
1366 rtc::scoped_ptr<TestPort> rport(
1367 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001368 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1369 rport->SetIceTiebreaker(kTiebreaker2);
1370
1371 lport->PrepareAddress();
1372 rport->PrepareAddress();
1373 ASSERT_FALSE(lport->Candidates().empty());
1374 ASSERT_FALSE(rport->Candidates().empty());
1375 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1376 Port::ORIGIN_MESSAGE);
1377 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1378 Port::ORIGIN_MESSAGE);
1379 rconn->Ping(0);
1380
1381 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1382 IceMessage* msg = rport->last_stun_msg();
1383 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1384 // Send rport binding request to lport.
1385 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1386 rport->last_stun_buf()->Length(),
1387 rtc::PacketTime());
1388
1389 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1390 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1391 EXPECT_TRUE(role_conflict());
1392}
1393
1394TEST_F(PortTest, TestTcpNoDelay) {
1395 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001396 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397 int option_value = -1;
1398 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1399 &option_value);
1400 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1401 ASSERT_EQ(1, option_value);
1402 delete port1;
1403}
1404
1405TEST_F(PortTest, TestDelayedBindingUdp) {
1406 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1407 FakePacketSocketFactory socket_factory;
1408
1409 socket_factory.set_next_udp_socket(socket);
1410 scoped_ptr<UDPPort> port(
1411 CreateUdpPort(kLocalAddr1, &socket_factory));
1412
1413 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1414 port->PrepareAddress();
1415
1416 EXPECT_EQ(0U, port->Candidates().size());
1417 socket->SignalAddressReady(socket, kLocalAddr2);
1418
1419 EXPECT_EQ(1U, port->Candidates().size());
1420}
1421
1422TEST_F(PortTest, TestDelayedBindingTcp) {
1423 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1424 FakePacketSocketFactory socket_factory;
1425
1426 socket_factory.set_next_server_tcp_socket(socket);
1427 scoped_ptr<TCPPort> port(
1428 CreateTcpPort(kLocalAddr1, &socket_factory));
1429
1430 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1431 port->PrepareAddress();
1432
1433 EXPECT_EQ(0U, port->Candidates().size());
1434 socket->SignalAddressReady(socket, kLocalAddr2);
1435
1436 EXPECT_EQ(1U, port->Candidates().size());
1437}
1438
1439void PortTest::TestCrossFamilyPorts(int type) {
1440 FakePacketSocketFactory factory;
1441 scoped_ptr<Port> ports[4];
1442 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1443 SocketAddress("192.168.1.4", 0),
1444 SocketAddress("2001:db8::1", 0),
1445 SocketAddress("2001:db8::2", 0)};
1446 for (int i = 0; i < 4; i++) {
1447 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1448 if (type == SOCK_DGRAM) {
1449 factory.set_next_udp_socket(socket);
1450 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1451 } else if (type == SOCK_STREAM) {
1452 factory.set_next_server_tcp_socket(socket);
1453 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1454 }
1455 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1456 socket->SignalAddressReady(socket, addresses[i]);
1457 ports[i]->PrepareAddress();
1458 }
1459
1460 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1461 if (type == SOCK_STREAM) {
1462 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1463 factory.set_next_client_tcp_socket(clientsocket);
1464 }
1465 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1466 Port::ORIGIN_MESSAGE);
1467 EXPECT_TRUE(NULL == c);
1468 EXPECT_EQ(0U, ports[0]->connections().size());
1469 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1470 Port::ORIGIN_MESSAGE);
1471 EXPECT_FALSE(NULL == c);
1472 EXPECT_EQ(1U, ports[0]->connections().size());
1473
1474 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1475 if (type == SOCK_STREAM) {
1476 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1477 factory.set_next_client_tcp_socket(clientsocket);
1478 }
1479 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1480 Port::ORIGIN_MESSAGE);
1481 EXPECT_TRUE(NULL == c);
1482 EXPECT_EQ(0U, ports[2]->connections().size());
1483 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1484 Port::ORIGIN_MESSAGE);
1485 EXPECT_FALSE(NULL == c);
1486 EXPECT_EQ(1U, ports[2]->connections().size());
1487}
1488
1489TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1490 TestCrossFamilyPorts(SOCK_STREAM);
1491}
1492
1493TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1494 TestCrossFamilyPorts(SOCK_DGRAM);
1495}
1496
Peter Thatcherb8b01432015-07-07 16:45:53 -07001497void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1498 Connection* c = p1->CreateConnection(GetCandidate(p2),
1499 Port::ORIGIN_MESSAGE);
1500 if (can_connect) {
1501 EXPECT_FALSE(NULL == c);
1502 EXPECT_EQ(1U, p1->connections().size());
1503 } else {
1504 EXPECT_TRUE(NULL == c);
1505 EXPECT_EQ(0U, p1->connections().size());
1506 }
1507}
1508
1509TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1510 FakePacketSocketFactory factory;
1511 scoped_ptr<Port> ports[4];
1512 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1513 SocketAddress("fe80::1", 0),
1514 SocketAddress("fe80::2", 0),
1515 SocketAddress("::1", 0)};
1516 for (int i = 0; i < 4; i++) {
1517 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1518 factory.set_next_udp_socket(socket);
1519 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1520 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1521 socket->SignalAddressReady(socket, addresses[i]);
1522 ports[i]->PrepareAddress();
1523 }
1524
1525 Port* standard = ports[0].get();
1526 Port* link_local1 = ports[1].get();
1527 Port* link_local2 = ports[2].get();
1528 Port* localhost = ports[3].get();
1529
1530 ExpectPortsCanConnect(false, link_local1, standard);
1531 ExpectPortsCanConnect(false, standard, link_local1);
1532 ExpectPortsCanConnect(false, link_local1, localhost);
1533 ExpectPortsCanConnect(false, localhost, link_local1);
1534
1535 ExpectPortsCanConnect(true, link_local1, link_local2);
1536 ExpectPortsCanConnect(true, localhost, standard);
1537 ExpectPortsCanConnect(true, standard, localhost);
1538}
1539
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001540// This test verifies DSCP value set through SetOption interface can be
1541// get through DefaultDscpValue.
1542TEST_F(PortTest, TestDefaultDscpValue) {
1543 int dscp;
1544 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1545 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1546 rtc::DSCP_CS6));
1547 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1548 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1549 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1550 rtc::DSCP_AF31));
1551 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1552 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1553 rtc::scoped_ptr<StunPort> stunport(
1554 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1555 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1556 rtc::DSCP_AF41));
1557 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1558 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1559 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1560 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1561 // Socket is created in PrepareAddress.
1562 turnport1->PrepareAddress();
1563 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1564 rtc::DSCP_CS7));
1565 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1566 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1567 // This will verify correct value returned without the socket.
1568 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1569 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1570 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1571 rtc::DSCP_CS6));
1572 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1573 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1574}
1575
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001576// Test sending STUN messages.
1577TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001578 rtc::scoped_ptr<TestPort> lport(
1579 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1580 rtc::scoped_ptr<TestPort> rport(
1581 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001582 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1583 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001584 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1585 rport->SetIceTiebreaker(kTiebreaker2);
1586
1587 // Send a fake ping from lport to rport.
1588 lport->PrepareAddress();
1589 rport->PrepareAddress();
1590 ASSERT_FALSE(rport->Candidates().empty());
1591 Connection* lconn = lport->CreateConnection(
1592 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1593 Connection* rconn = rport->CreateConnection(
1594 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1595 lconn->Ping(0);
1596
1597 // Check that it's a proper BINDING-REQUEST.
1598 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1599 IceMessage* msg = lport->last_stun_msg();
1600 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1601 EXPECT_FALSE(msg->IsLegacy());
1602 const StunByteStringAttribute* username_attr =
1603 msg->GetByteString(STUN_ATTR_USERNAME);
1604 ASSERT_TRUE(username_attr != NULL);
1605 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1606 ASSERT_TRUE(priority_attr != NULL);
1607 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1608 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1609 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1610 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1611 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1612 "rpass"));
1613 const StunUInt64Attribute* ice_controlling_attr =
1614 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1615 ASSERT_TRUE(ice_controlling_attr != NULL);
1616 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1617 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1618 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1619 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1620 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1621 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1622
1623 // Request should not include ping count.
1624 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1625
1626 // Save a copy of the BINDING-REQUEST for use below.
1627 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1628
1629 // Respond with a BINDING-RESPONSE.
1630 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1631 msg = rport->last_stun_msg();
1632 ASSERT_TRUE(msg != NULL);
1633 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1634
1635
1636 EXPECT_FALSE(msg->IsLegacy());
1637 const StunAddressAttribute* addr_attr = msg->GetAddress(
1638 STUN_ATTR_XOR_MAPPED_ADDRESS);
1639 ASSERT_TRUE(addr_attr != NULL);
1640 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1641 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1642 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1643 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1644 "rpass"));
1645 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1646 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1647 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1648 // No USERNAME or PRIORITY in ICE responses.
1649 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1650 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1651 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1652 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1653 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1654 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1655
1656 // Response should not include ping count.
1657 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1658
1659 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1660 // but we can do it here.
1661 rport->SendBindingErrorResponse(request.get(),
1662 lport->Candidates()[0].address(),
1663 STUN_ERROR_SERVER_ERROR,
1664 STUN_ERROR_REASON_SERVER_ERROR);
1665 msg = rport->last_stun_msg();
1666 ASSERT_TRUE(msg != NULL);
1667 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1668 EXPECT_FALSE(msg->IsLegacy());
1669 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1670 ASSERT_TRUE(error_attr != NULL);
1671 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1672 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1673 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1674 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1675 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1676 "rpass"));
1677 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1678 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1679 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1680 // No USERNAME with ICE.
1681 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1682 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1683
1684 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1685 // and (incremented) RETRANSMIT_COUNT attributes.
1686 rport->Reset();
1687 rport->set_send_retransmit_count_attribute(true);
1688 rconn->Ping(0);
1689 rconn->Ping(0);
1690 rconn->Ping(0);
1691 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1692 msg = rport->last_stun_msg();
1693 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1694 const StunUInt64Attribute* ice_controlled_attr =
1695 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1696 ASSERT_TRUE(ice_controlled_attr != NULL);
1697 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1698 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1699
1700 // Request should include ping count.
1701 const StunUInt32Attribute* retransmit_attr =
1702 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1703 ASSERT_TRUE(retransmit_attr != NULL);
1704 EXPECT_EQ(2U, retransmit_attr->value());
1705
1706 // Respond with a BINDING-RESPONSE.
1707 request.reset(CopyStunMessage(msg));
1708 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1709 msg = lport->last_stun_msg();
1710
1711 // Response should include same ping count.
1712 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1713 ASSERT_TRUE(retransmit_attr != NULL);
1714 EXPECT_EQ(2U, retransmit_attr->value());
1715}
1716
1717TEST_F(PortTest, TestUseCandidateAttribute) {
1718 rtc::scoped_ptr<TestPort> lport(
1719 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1720 rtc::scoped_ptr<TestPort> rport(
1721 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001722 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1723 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001724 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1725 rport->SetIceTiebreaker(kTiebreaker2);
1726
1727 // Send a fake ping from lport to rport.
1728 lport->PrepareAddress();
1729 rport->PrepareAddress();
1730 ASSERT_FALSE(rport->Candidates().empty());
1731 Connection* lconn = lport->CreateConnection(
1732 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1733 lconn->Ping(0);
1734 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1735 IceMessage* msg = lport->last_stun_msg();
1736 const StunUInt64Attribute* ice_controlling_attr =
1737 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1738 ASSERT_TRUE(ice_controlling_attr != NULL);
1739 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1740 STUN_ATTR_USE_CANDIDATE);
1741 ASSERT_TRUE(use_candidate_attr != NULL);
1742}
1743
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001744// Test handling STUN messages.
1745TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001746 // Our port will act as the "remote" port.
1747 rtc::scoped_ptr<TestPort> port(
1748 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001749
1750 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1751 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1752 rtc::SocketAddress addr(kLocalAddr1);
1753 std::string username;
1754
1755 // BINDING-REQUEST from local to remote with valid ICE username,
1756 // MESSAGE-INTEGRITY, and FINGERPRINT.
1757 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1758 "rfrag:lfrag"));
1759 in_msg->AddMessageIntegrity("rpass");
1760 in_msg->AddFingerprint();
1761 WriteStunMessage(in_msg.get(), buf.get());
1762 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1763 out_msg.accept(), &username));
1764 EXPECT_TRUE(out_msg.get() != NULL);
1765 EXPECT_EQ("lfrag", username);
1766
1767 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1768 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1769 in_msg->AddAttribute(
1770 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1771 in_msg->AddMessageIntegrity("rpass");
1772 in_msg->AddFingerprint();
1773 WriteStunMessage(in_msg.get(), buf.get());
1774 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1775 out_msg.accept(), &username));
1776 EXPECT_TRUE(out_msg.get() != NULL);
1777 EXPECT_EQ("", username);
1778
1779 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1780 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1781 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1782 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1783 in_msg->AddFingerprint();
1784 WriteStunMessage(in_msg.get(), buf.get());
1785 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1786 out_msg.accept(), &username));
1787 EXPECT_TRUE(out_msg.get() != NULL);
1788 EXPECT_EQ("", username);
1789 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1790 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1791 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1792 out_msg->GetErrorCode()->reason());
1793}
1794
guoweisd12140a2015-09-10 13:32:11 -07001795// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001796TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001797 rtc::scoped_ptr<TestPort> port(
1798 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001799
1800 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1801 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1802 rtc::SocketAddress addr(kLocalAddr1);
1803 std::string username;
1804
1805 // BINDING-REQUEST with no username.
1806 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1807 in_msg->AddMessageIntegrity("rpass");
1808 in_msg->AddFingerprint();
1809 WriteStunMessage(in_msg.get(), buf.get());
1810 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1811 out_msg.accept(), &username));
1812 EXPECT_TRUE(out_msg.get() == NULL);
1813 EXPECT_EQ("", username);
1814 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1815
1816 // BINDING-REQUEST with empty username.
1817 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1818 in_msg->AddMessageIntegrity("rpass");
1819 in_msg->AddFingerprint();
1820 WriteStunMessage(in_msg.get(), buf.get());
1821 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1822 out_msg.accept(), &username));
1823 EXPECT_TRUE(out_msg.get() == NULL);
1824 EXPECT_EQ("", username);
1825 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1826
1827 // BINDING-REQUEST with too-short username.
1828 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1829 in_msg->AddMessageIntegrity("rpass");
1830 in_msg->AddFingerprint();
1831 WriteStunMessage(in_msg.get(), buf.get());
1832 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1833 out_msg.accept(), &username));
1834 EXPECT_TRUE(out_msg.get() == NULL);
1835 EXPECT_EQ("", username);
1836 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1837
1838 // BINDING-REQUEST with reversed username.
1839 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1840 "lfrag:rfrag"));
1841 in_msg->AddMessageIntegrity("rpass");
1842 in_msg->AddFingerprint();
1843 WriteStunMessage(in_msg.get(), buf.get());
1844 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1845 out_msg.accept(), &username));
1846 EXPECT_TRUE(out_msg.get() == NULL);
1847 EXPECT_EQ("", username);
1848 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1849
1850 // BINDING-REQUEST with garbage username.
1851 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1852 "abcd:efgh"));
1853 in_msg->AddMessageIntegrity("rpass");
1854 in_msg->AddFingerprint();
1855 WriteStunMessage(in_msg.get(), buf.get());
1856 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1857 out_msg.accept(), &username));
1858 EXPECT_TRUE(out_msg.get() == NULL);
1859 EXPECT_EQ("", username);
1860 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1861}
1862
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001863// Test handling STUN messages with missing or malformed M-I.
1864TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001865 // Our port will act as the "remote" port.
1866 rtc::scoped_ptr<TestPort> port(
1867 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001868
1869 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1870 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1871 rtc::SocketAddress addr(kLocalAddr1);
1872 std::string username;
1873
1874 // BINDING-REQUEST from local to remote with valid ICE username and
1875 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1876 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1877 "rfrag:lfrag"));
1878 in_msg->AddFingerprint();
1879 WriteStunMessage(in_msg.get(), buf.get());
1880 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1881 out_msg.accept(), &username));
1882 EXPECT_TRUE(out_msg.get() == NULL);
1883 EXPECT_EQ("", username);
1884 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1885
1886 // BINDING-REQUEST from local to remote with valid ICE username and
1887 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1888 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1889 "rfrag:lfrag"));
1890 in_msg->AddMessageIntegrity("invalid");
1891 in_msg->AddFingerprint();
1892 WriteStunMessage(in_msg.get(), buf.get());
1893 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1894 out_msg.accept(), &username));
1895 EXPECT_TRUE(out_msg.get() == NULL);
1896 EXPECT_EQ("", username);
1897 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1898
1899 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1900 // by the Connection, not the Port, since they require the remote username.
1901 // Change this test to pass in data via Connection::OnReadPacket instead.
1902}
1903
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001904// Test handling STUN messages with missing or malformed FINGERPRINT.
1905TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001906 // Our port will act as the "remote" port.
1907 rtc::scoped_ptr<TestPort> port(
1908 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001909
1910 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1911 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1912 rtc::SocketAddress addr(kLocalAddr1);
1913 std::string username;
1914
1915 // BINDING-REQUEST from local to remote with valid ICE username and
1916 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1917 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1918 "rfrag:lfrag"));
1919 in_msg->AddMessageIntegrity("rpass");
1920 WriteStunMessage(in_msg.get(), buf.get());
1921 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1922 out_msg.accept(), &username));
1923 EXPECT_EQ(0, port->last_stun_error_code());
1924
1925 // Now, add a fingerprint, but munge the message so it's not valid.
1926 in_msg->AddFingerprint();
1927 in_msg->SetTransactionID("TESTTESTBADD");
1928 WriteStunMessage(in_msg.get(), buf.get());
1929 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1930 out_msg.accept(), &username));
1931 EXPECT_EQ(0, port->last_stun_error_code());
1932
1933 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1934 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1935 in_msg->AddAttribute(
1936 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1937 in_msg->AddMessageIntegrity("rpass");
1938 WriteStunMessage(in_msg.get(), buf.get());
1939 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1940 out_msg.accept(), &username));
1941 EXPECT_EQ(0, port->last_stun_error_code());
1942
1943 // Now, add a fingerprint, but munge the message so it's not valid.
1944 in_msg->AddFingerprint();
1945 in_msg->SetTransactionID("TESTTESTBADD");
1946 WriteStunMessage(in_msg.get(), buf.get());
1947 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1948 out_msg.accept(), &username));
1949 EXPECT_EQ(0, port->last_stun_error_code());
1950
1951 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1952 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1953 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1954 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1955 in_msg->AddMessageIntegrity("rpass");
1956 WriteStunMessage(in_msg.get(), buf.get());
1957 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1958 out_msg.accept(), &username));
1959 EXPECT_EQ(0, port->last_stun_error_code());
1960
1961 // Now, add a fingerprint, but munge the message so it's not valid.
1962 in_msg->AddFingerprint();
1963 in_msg->SetTransactionID("TESTTESTBADD");
1964 WriteStunMessage(in_msg.get(), buf.get());
1965 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1966 out_msg.accept(), &username));
1967 EXPECT_EQ(0, port->last_stun_error_code());
1968}
1969
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001970// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001971// indications are allowed only to the connection which is in read mode.
1972TEST_F(PortTest, TestHandleStunBindingIndication) {
1973 rtc::scoped_ptr<TestPort> lport(
1974 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001975 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1976 lport->SetIceTiebreaker(kTiebreaker1);
1977
1978 // Verifying encoding and decoding STUN indication message.
1979 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1980 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1981 rtc::SocketAddress addr(kLocalAddr1);
1982 std::string username;
1983
1984 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
1985 in_msg->AddFingerprint();
1986 WriteStunMessage(in_msg.get(), buf.get());
1987 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
1988 out_msg.accept(), &username));
1989 EXPECT_TRUE(out_msg.get() != NULL);
1990 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
1991 EXPECT_EQ("", username);
1992
1993 // Verify connection can handle STUN indication and updates
1994 // last_ping_received.
1995 rtc::scoped_ptr<TestPort> rport(
1996 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001997 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1998 rport->SetIceTiebreaker(kTiebreaker2);
1999
2000 lport->PrepareAddress();
2001 rport->PrepareAddress();
2002 ASSERT_FALSE(lport->Candidates().empty());
2003 ASSERT_FALSE(rport->Candidates().empty());
2004
2005 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2006 Port::ORIGIN_MESSAGE);
2007 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2008 Port::ORIGIN_MESSAGE);
2009 rconn->Ping(0);
2010
2011 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2012 IceMessage* msg = rport->last_stun_msg();
2013 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2014 // Send rport binding request to lport.
2015 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
2016 rport->last_stun_buf()->Length(),
2017 rtc::PacketTime());
2018 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2019 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
Peter Boström0c4e06b2015-10-07 12:23:21 +02002020 uint32_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002021
2022 // Adding a delay of 100ms.
2023 rtc::Thread::Current()->ProcessMessages(100);
2024 // Pinging lconn using stun indication message.
2025 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
Peter Boström0c4e06b2015-10-07 12:23:21 +02002026 uint32_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002027 EXPECT_GT(last_ping_received2, last_ping_received1);
2028}
2029
2030TEST_F(PortTest, TestComputeCandidatePriority) {
2031 rtc::scoped_ptr<TestPort> port(
2032 CreateTestPort(kLocalAddr1, "name", "pass"));
2033 port->set_type_preference(90);
2034 port->set_component(177);
2035 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2036 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2037 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2038 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2039 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2040 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2041 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2042 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2043 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2044 // These should all be:
2045 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002046 uint32_t expected_priority_v4 = 1509957199U;
2047 uint32_t expected_priority_v6 = 1509959759U;
2048 uint32_t expected_priority_ula = 1509962319U;
2049 uint32_t expected_priority_v4mapped = expected_priority_v4;
2050 uint32_t expected_priority_v4compat = 1509949775U;
2051 uint32_t expected_priority_6to4 = 1509954639U;
2052 uint32_t expected_priority_teredo = 1509952079U;
2053 uint32_t expected_priority_sitelocal = 1509949775U;
2054 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002055 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2056 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2057 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2058 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2059 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2060 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2061 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2062 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2063 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2064}
2065
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002066// In the case of shared socket, one port may be shared by local and stun.
2067// Test that candidates with different types will have different foundation.
2068TEST_F(PortTest, TestFoundation) {
2069 rtc::scoped_ptr<TestPort> testport(
2070 CreateTestPort(kLocalAddr1, "name", "pass"));
2071 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2072 LOCAL_PORT_TYPE,
2073 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2074 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2075 STUN_PORT_TYPE,
2076 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2077 EXPECT_NE(testport->Candidates()[0].foundation(),
2078 testport->Candidates()[1].foundation());
2079}
2080
2081// This test verifies the foundation of different types of ICE candidates.
2082TEST_F(PortTest, TestCandidateFoundation) {
2083 rtc::scoped_ptr<rtc::NATServer> nat_server(
2084 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2085 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2086 udpport1->PrepareAddress();
2087 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2088 udpport2->PrepareAddress();
2089 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2090 udpport2->Candidates()[0].foundation());
2091 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2092 tcpport1->PrepareAddress();
2093 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2094 tcpport2->PrepareAddress();
2095 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2096 tcpport2->Candidates()[0].foundation());
2097 rtc::scoped_ptr<Port> stunport(
2098 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2099 stunport->PrepareAddress();
2100 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2101 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2102 stunport->Candidates()[0].foundation());
2103 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2104 stunport->Candidates()[0].foundation());
2105 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2106 stunport->Candidates()[0].foundation());
2107 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2108 stunport->Candidates()[0].foundation());
2109 // Verify GTURN candidate foundation.
2110 rtc::scoped_ptr<RelayPort> relayport(
2111 CreateGturnPort(kLocalAddr1));
2112 relayport->AddServerAddress(
2113 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2114 relayport->PrepareAddress();
2115 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2116 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2117 relayport->Candidates()[0].foundation());
2118 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2119 relayport->Candidates()[0].foundation());
2120 // Verifying TURN candidate foundation.
2121 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2122 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2123 turnport1->PrepareAddress();
2124 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2125 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2126 turnport1->Candidates()[0].foundation());
2127 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2128 turnport1->Candidates()[0].foundation());
2129 EXPECT_NE(stunport->Candidates()[0].foundation(),
2130 turnport1->Candidates()[0].foundation());
2131 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2132 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2133 turnport2->PrepareAddress();
2134 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2135 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2136 turnport2->Candidates()[0].foundation());
2137
2138 // Running a second turn server, to get different base IP address.
2139 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2140 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2141 TestTurnServer turn_server2(
2142 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2143 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2144 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2145 kTurnUdpIntAddr2));
2146 turnport3->PrepareAddress();
2147 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2148 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2149 turnport2->Candidates()[0].foundation());
2150}
2151
2152// This test verifies the related addresses of different types of
2153// ICE candiates.
2154TEST_F(PortTest, TestCandidateRelatedAddress) {
2155 rtc::scoped_ptr<rtc::NATServer> nat_server(
2156 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2157 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2158 udpport->PrepareAddress();
2159 // For UDPPort, related address will be empty.
2160 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2161 // Testing related address for stun candidates.
2162 // For stun candidate related address must be equal to the base
2163 // socket address.
2164 rtc::scoped_ptr<StunPort> stunport(
2165 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2166 stunport->PrepareAddress();
2167 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2168 // Check STUN candidate address.
2169 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2170 kNatAddr1.ipaddr());
2171 // Check STUN candidate related address.
2172 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2173 stunport->GetLocalAddress());
2174 // Verifying the related address for the GTURN candidates.
2175 // NOTE: In case of GTURN related address will be equal to the mapped
2176 // address, but address(mapped) will not be XOR.
2177 rtc::scoped_ptr<RelayPort> relayport(
2178 CreateGturnPort(kLocalAddr1));
2179 relayport->AddServerAddress(
2180 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2181 relayport->PrepareAddress();
2182 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2183 // For Gturn related address is set to "0.0.0.0:0"
2184 EXPECT_EQ(rtc::SocketAddress(),
2185 relayport->Candidates()[0].related_address());
2186 // Verifying the related address for TURN candidate.
2187 // For TURN related address must be equal to the mapped address.
2188 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2189 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2190 turnport->PrepareAddress();
2191 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2192 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2193 turnport->Candidates()[0].address().ipaddr());
2194 EXPECT_EQ(kNatAddr1.ipaddr(),
2195 turnport->Candidates()[0].related_address().ipaddr());
2196}
2197
2198// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002199TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002200 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002201 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002202 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002203 cand2.set_priority(1);
2204 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002205}
2206
2207// Test the Connection priority is calculated correctly.
2208TEST_F(PortTest, TestConnectionPriority) {
2209 rtc::scoped_ptr<TestPort> lport(
2210 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2211 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2212 rtc::scoped_ptr<TestPort> rport(
2213 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2214 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2215 lport->set_component(123);
2216 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2217 rport->set_component(23);
2218 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2219
2220 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2221 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2222
2223 // RFC 5245
2224 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2225 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2226 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2227 Connection* lconn = lport->CreateConnection(
2228 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2229#if defined(WEBRTC_WIN)
2230 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2231#else
2232 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2233#endif
2234
2235 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2236 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2237 Connection* rconn = rport->CreateConnection(
2238 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2239#if defined(WEBRTC_WIN)
2240 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2241#else
2242 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2243#endif
2244}
2245
2246TEST_F(PortTest, TestWritableState) {
2247 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002248 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002249 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002250 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002251
2252 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002253 TestChannel ch1(port1);
2254 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002255
2256 // Acquire addresses.
2257 ch1.Start();
2258 ch2.Start();
2259 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2260 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2261
2262 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002263 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002264 ASSERT_TRUE(ch1.conn() != NULL);
2265 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2266 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2267 ch1.Ping();
2268 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2269
2270 // Data should be unsendable until the connection is accepted.
2271 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002272 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002273 rtc::PacketOptions options;
2274 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2275
2276 // Accept the connection to return the binding response, transition to
2277 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002278 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002279 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2280 kTimeout);
2281 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2282
2283 // Ask the connection to update state as if enough time has passed to lose
2284 // full writability and 5 pings went unresponded to. We'll accomplish the
2285 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002286 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002287 ch1.Ping(i);
2288 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002289 uint32_t unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002290 ch1.conn()->UpdateState(unreliable_timeout_delay);
2291 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2292
2293 // Data should be able to be sent in this state.
2294 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2295
2296 // And now allow the other side to process the pings and send binding
2297 // responses.
2298 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2299 kTimeout);
2300
2301 // Wait long enough for a full timeout (past however long we've already
2302 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002303 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002304 ch1.Ping(unreliable_timeout_delay + i);
2305 }
2306 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2307 500u);
2308 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2309
2310 // Now that the connection has completely timed out, data send should fail.
2311 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2312
2313 ch1.Stop();
2314 ch2.Stop();
2315}
2316
2317TEST_F(PortTest, TestTimeoutForNeverWritable) {
2318 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002319 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002320 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002321 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002322
2323 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002324 TestChannel ch1(port1);
2325 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002326
2327 // Acquire addresses.
2328 ch1.Start();
2329 ch2.Start();
2330
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002331 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002332 ASSERT_TRUE(ch1.conn() != NULL);
2333 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2334
2335 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002336 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002337 ch1.Ping(i);
2338 }
2339 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2340 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2341}
2342
2343// This test verifies the connection setup between ICEMODE_FULL
2344// and ICEMODE_LITE.
2345// In this test |ch1| behaves like FULL mode client and we have created
2346// port which responds to the ping message just like LITE client.
2347TEST_F(PortTest, TestIceLiteConnectivity) {
2348 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002349 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002350 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2351
2352 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002353 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002354 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2355 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002356 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002357 ch1.SetIceMode(ICEMODE_FULL);
2358
2359 // Start gathering candidates.
2360 ch1.Start();
2361 ice_lite_port->PrepareAddress();
2362
2363 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2364 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2365
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002366 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002367 ASSERT_TRUE(ch1.conn() != NULL);
2368 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2369
2370 // Send ping from full mode client.
2371 // This ping must not have USE_CANDIDATE_ATTR.
2372 ch1.Ping();
2373
2374 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2375 // from port.
2376 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2377 IceMessage* msg = ice_full_port->last_stun_msg();
2378 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2379
2380 // Respond with a BINDING-RESPONSE from litemode client.
2381 // NOTE: Ideally we should't create connection at this stage from lite
2382 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2383 // But we need a connection to send a response message.
2384 ice_lite_port->CreateConnection(
2385 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2386 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2387 ice_lite_port->SendBindingResponse(
2388 request.get(), ice_full_port->Candidates()[0].address());
2389
2390 // Feeding the respone message from litemode to the full mode connection.
2391 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2392 ice_lite_port->last_stun_buf()->Length(),
2393 rtc::PacketTime());
2394 // Verifying full mode connection becomes writable from the response.
2395 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2396 kTimeout);
2397 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2398
2399 // Clear existing stun messsages. Otherwise we will process old stun
2400 // message right after we send ping.
2401 ice_full_port->Reset();
2402 // Send ping. This must have USE_CANDIDATE_ATTR.
2403 ch1.Ping();
2404 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2405 msg = ice_full_port->last_stun_msg();
2406 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2407 ch1.Stop();
2408}
2409
2410// This test case verifies that the CONTROLLING port does not time out.
2411TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002412 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2413 ConnectToSignalDestroyed(port1);
2414 port1->set_timeout_delay(10); // milliseconds
2415 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2416 port1->SetIceTiebreaker(kTiebreaker1);
2417
2418 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2419 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2420 port2->SetIceTiebreaker(kTiebreaker2);
2421
2422 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002423 TestChannel ch1(port1);
2424 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002425
2426 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002427 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002428
2429 // After the connection is destroyed, the port should not be destroyed.
2430 rtc::Thread::Current()->ProcessMessages(kTimeout);
2431 EXPECT_FALSE(destroyed());
2432}
2433
2434// This test case verifies that the CONTROLLED port does time out, but only
2435// after connectivity is lost.
2436TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002437 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2438 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2439 port1->SetIceTiebreaker(kTiebreaker1);
2440
2441 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2442 ConnectToSignalDestroyed(port2);
2443 port2->set_timeout_delay(10); // milliseconds
2444 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2445 port2->SetIceTiebreaker(kTiebreaker2);
2446
2447 // The connection must not be destroyed before a connection is attempted.
2448 EXPECT_FALSE(destroyed());
2449
2450 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2451 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2452
2453 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002454 TestChannel ch1(port1);
2455 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002456
2457 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002458 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002459
2460 // The controlled port should be destroyed after 10 milliseconds.
2461 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2462}
honghaizd0b31432015-09-30 12:42:17 -07002463
2464// This test case verifies that if the role of a port changes from controlled
2465// to controlling after all connections fail, the port will not be destroyed.
2466TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2467 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2468 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2469 port1->SetIceTiebreaker(kTiebreaker1);
2470
2471 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2472 ConnectToSignalDestroyed(port2);
2473 port2->set_timeout_delay(10); // milliseconds
2474 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2475 port2->SetIceTiebreaker(kTiebreaker2);
2476
2477 // The connection must not be destroyed before a connection is attempted.
2478 EXPECT_FALSE(destroyed());
2479
2480 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2481 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2482
2483 // Set up channels and ensure both ports will be deleted.
2484 TestChannel ch1(port1);
2485 TestChannel ch2(port2);
2486
2487 // Simulate a connection that succeeds, and then is destroyed.
2488 StartConnectAndStopChannels(&ch1, &ch2);
2489 // Switch the role after all connections are destroyed.
2490 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2491 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2492 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2493
2494 // After the connection is destroyed, the port should not be destroyed.
2495 rtc::Thread::Current()->ProcessMessages(kTimeout);
2496 EXPECT_FALSE(destroyed());
2497}