blob: 449021ad9fb4c78004d237bc4dd37b1d36eee599 [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
Honghai Zhangf9945b22015-12-15 12:20:13 -0800144 virtual bool SupportsProtocol(const std::string& protocol) const {
145 return true;
146 }
147
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 // Exposed for testing candidate building.
149 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700150 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 type_preference_, 0, false);
152 }
153 void AddCandidateAddress(const rtc::SocketAddress& addr,
154 const rtc::SocketAddress& base_address,
155 const std::string& type,
156 int type_preference,
157 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700158 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000159 type_preference, 0, final);
160 }
161
162 virtual Connection* CreateConnection(const Candidate& remote_candidate,
163 CandidateOrigin origin) {
164 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
165 AddConnection(conn);
166 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
167 // in STUN binding requests.
168 conn->set_use_candidate_attr(true);
169 return conn;
170 }
171 virtual int SendTo(
172 const void* data, size_t size, const rtc::SocketAddress& addr,
173 const rtc::PacketOptions& options, bool payload) {
174 if (!payload) {
175 IceMessage* msg = new IceMessage;
176 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
177 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
178 if (!msg->Read(buf)) {
179 delete msg;
180 delete buf;
181 return -1;
182 }
183 buf->SetReadPosition(pos);
184 last_stun_buf_.reset(buf);
185 last_stun_msg_.reset(msg);
186 }
187 return static_cast<int>(size);
188 }
189 virtual int SetOption(rtc::Socket::Option opt, int value) {
190 return 0;
191 }
192 virtual int GetOption(rtc::Socket::Option opt, int* value) {
193 return -1;
194 }
195 virtual int GetError() {
196 return 0;
197 }
198 void Reset() {
199 last_stun_buf_.reset();
200 last_stun_msg_.reset();
201 }
202 void set_type_preference(int type_preference) {
203 type_preference_ = type_preference;
204 }
205
206 private:
Stefan Holmer55674ff2016-01-14 15:49:16 +0100207 void OnSentPacket(rtc::AsyncPacketSocket* socket,
208 const rtc::SentPacket& sent_packet) {
209 PortInterface::SignalSentPacket(sent_packet);
210 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
212 rtc::scoped_ptr<IceMessage> last_stun_msg_;
pbos7640ffa2015-11-30 09:16:59 -0800213 int type_preference_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214};
215
216class TestChannel : public sigslot::has_slots<> {
217 public:
218 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700219 TestChannel(Port* p1)
220 : ice_mode_(ICEMODE_FULL),
221 port_(p1),
222 complete_count_(0),
223 conn_(NULL),
224 remote_request_(),
225 nominated_(false) {
226 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
227 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
228 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229 }
230
231 int complete_count() { return complete_count_; }
232 Connection* conn() { return conn_; }
233 const SocketAddress& remote_address() { return remote_address_; }
234 const std::string remote_fragment() { return remote_frag_; }
235
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700236 void Start() { port_->PrepareAddress(); }
237 void CreateConnection(const Candidate& remote_candidate) {
238 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239 IceMode remote_ice_mode =
240 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
241 conn_->set_remote_ice_mode(remote_ice_mode);
242 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
243 conn_->SignalStateChange.connect(
244 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700245 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700246 conn_->SignalReadyToSend.connect(this,
247 &TestChannel::OnConnectionReadyToSend);
248 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 }
250 void OnConnectionStateChange(Connection* conn) {
251 if (conn->write_state() == Connection::STATE_WRITABLE) {
252 conn->set_use_candidate_attr(true);
253 nominated_ = true;
254 }
255 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700256 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700258 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700260 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700261 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700262 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263 remote_request_.reset();
264 }
265 void Ping() {
266 Ping(0);
267 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200268 void Ping(uint32_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700270 if (conn_) {
271 conn_->Destroy();
272 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273 }
274
275 void OnPortComplete(Port* port) {
276 complete_count_++;
277 }
278 void SetIceMode(IceMode ice_mode) {
279 ice_mode_ = ice_mode;
280 }
281
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700282 int SendData(const char* data, size_t len) {
283 rtc::PacketOptions options;
284 return conn_->Send(data, len, options);
285 }
286
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
288 ProtocolType proto,
289 IceMessage* msg, const std::string& rf,
290 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700291 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 if (!remote_address_.IsNil()) {
293 ASSERT_EQ(remote_address_, addr);
294 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 const cricket::StunUInt32Attribute* priority_attr =
296 msg->GetUInt32(STUN_ATTR_PRIORITY);
297 const cricket::StunByteStringAttribute* mi_attr =
298 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
299 const cricket::StunUInt32Attribute* fingerprint_attr =
300 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700301 EXPECT_TRUE(priority_attr != NULL);
302 EXPECT_TRUE(mi_attr != NULL);
303 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 remote_address_ = addr;
305 remote_request_.reset(CopyStunMessage(msg));
306 remote_frag_ = rf;
307 }
308
309 void OnDestroyed(Connection* conn) {
310 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700311 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000312 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700313 // When the connection is destroyed, also clear these fields so future
314 // connections are possible.
315 remote_request_.reset();
316 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000317 }
318
319 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700320 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321 ASSERT_EQ(destroyed_src, port);
322 }
323
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700324 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700325
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 bool nominated() const { return nominated_; }
327
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700328 void set_connection_ready_to_send(bool ready) {
329 connection_ready_to_send_ = ready;
330 }
331 bool connection_ready_to_send() const {
332 return connection_ready_to_send_;
333 }
334
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000335 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700336 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
337 void OnConnectionReadyToSend(Connection* conn) {
338 ASSERT_EQ(conn, conn_);
339 connection_ready_to_send_ = true;
340 }
341
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000342 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700343 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344
345 int complete_count_;
346 Connection* conn_;
347 SocketAddress remote_address_;
348 rtc::scoped_ptr<StunMessage> remote_request_;
349 std::string remote_frag_;
350 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700351 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352};
353
354class PortTest : public testing::Test, public sigslot::has_slots<> {
355 public:
356 PortTest()
357 : main_(rtc::Thread::Current()),
358 pss_(new rtc::PhysicalSocketServer),
359 ss_(new rtc::VirtualSocketServer(pss_.get())),
360 ss_scope_(ss_.get()),
361 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
362 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700363 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
364 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365 nat_socket_factory1_(&nat_factory1_),
366 nat_socket_factory2_(&nat_factory2_),
367 stun_server_(TestStunServer::Create(main_, kStunAddr)),
368 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700369 relay_server_(main_,
370 kRelayUdpIntAddr,
371 kRelayUdpExtAddr,
372 kRelayTcpIntAddr,
373 kRelayTcpExtAddr,
374 kRelaySslTcpIntAddr,
375 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000376 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
377 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 role_conflict_(false),
379 destroyed_(false) {
380 network_.AddIP(rtc::IPAddress(INADDR_ANY));
381 }
382
383 protected:
384 void TestLocalToLocal() {
385 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700386 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 Port* port2 = CreateUdpPort(kLocalAddr2);
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, "udp", port2, true, true, true, true);
390 }
391 void TestLocalToStun(NATType ntype) {
392 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700393 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
395 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700396 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000397 TestConnectivity("udp", port1, StunName(ntype), port2,
398 ntype == NAT_OPEN_CONE, true,
399 ntype != NAT_SYMMETRIC, true);
400 }
401 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
402 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700403 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700405 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000406 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
407 rtype == RELAY_GTURN, true, true, true);
408 }
409 void TestStunToLocal(NATType ntype) {
410 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
411 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700412 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700414 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000415 TestConnectivity(StunName(ntype), port1, "udp", port2,
416 true, ntype != NAT_SYMMETRIC, true, true);
417 }
418 void TestStunToStun(NATType ntype1, NATType ntype2) {
419 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
420 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700421 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
423 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700424 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000425 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
426 ntype2 == NAT_OPEN_CONE,
427 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
428 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
429 }
430 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
431 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
432 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700433 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000434 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700435 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000436 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
437 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
438 }
439 void TestTcpToTcp() {
440 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700441 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700443 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
445 }
446 void TestTcpToRelay(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_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700450 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
452 rtype == RELAY_GTURN, false, true, true);
453 }
454 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
455 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700456 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700458 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
460 rtype == RELAY_GTURN, false, true, true);
461 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462 // helpers for above functions
463 UDPPort* CreateUdpPort(const SocketAddress& addr) {
464 return CreateUdpPort(addr, &socket_factory_);
465 }
466 UDPPort* CreateUdpPort(const SocketAddress& addr,
467 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800468 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
469 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000470 }
471 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700472 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000473 }
474 TCPPort* CreateTcpPort(const SocketAddress& addr,
475 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700476 return TCPPort::Create(main_, socket_factory, &network_,
477 addr.ipaddr(), 0, 0, username_, password_,
478 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 }
480 StunPort* CreateStunPort(const SocketAddress& addr,
481 rtc::PacketSocketFactory* factory) {
482 ServerAddresses stun_servers;
483 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700484 return StunPort::Create(main_, factory, &network_,
485 addr.ipaddr(), 0, 0,
486 username_, password_, stun_servers,
487 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488 }
489 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
490 ProtocolType int_proto, ProtocolType ext_proto) {
491 if (rtype == RELAY_TURN) {
492 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
493 } else {
494 return CreateGturnPort(addr, int_proto, ext_proto);
495 }
496 }
497 TurnPort* CreateTurnPort(const SocketAddress& addr,
498 PacketSocketFactory* socket_factory,
499 ProtocolType int_proto, ProtocolType ext_proto) {
500 return CreateTurnPort(addr, socket_factory,
501 int_proto, ext_proto, kTurnUdpIntAddr);
502 }
503 TurnPort* CreateTurnPort(const SocketAddress& addr,
504 PacketSocketFactory* socket_factory,
505 ProtocolType int_proto, ProtocolType ext_proto,
506 const rtc::SocketAddress& server_addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700507 return TurnPort::Create(main_, socket_factory, &network_,
508 addr.ipaddr(), 0, 0,
509 username_, password_, ProtocolAddress(
510 server_addr, PROTO_UDP),
511 kRelayCredentials, 0,
512 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000513 }
514 RelayPort* CreateGturnPort(const SocketAddress& addr,
515 ProtocolType int_proto, ProtocolType ext_proto) {
516 RelayPort* port = CreateGturnPort(addr);
517 SocketAddress addrs[] =
518 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
519 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
520 return port;
521 }
522 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700523 // TODO(pthatcher): Remove GTURN.
524 return RelayPort::Create(main_, &socket_factory_, &network_,
525 addr.ipaddr(), 0, 0,
526 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000527 // TODO: Add an external address for ext_proto, so that the
528 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000529 }
530 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
531 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700532 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000533 }
534 static const char* StunName(NATType type) {
535 switch (type) {
536 case NAT_OPEN_CONE: return "stun(open cone)";
537 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
538 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
539 case NAT_SYMMETRIC: return "stun(symmetric)";
540 default: return "stun(?)";
541 }
542 }
543 static const char* RelayName(RelayType type, ProtocolType proto) {
544 if (type == RELAY_TURN) {
545 switch (proto) {
546 case PROTO_UDP: return "turn(udp)";
547 case PROTO_TCP: return "turn(tcp)";
548 case PROTO_SSLTCP: return "turn(ssltcp)";
549 default: return "turn(?)";
550 }
551 } else {
552 switch (proto) {
553 case PROTO_UDP: return "gturn(udp)";
554 case PROTO_TCP: return "gturn(tcp)";
555 case PROTO_SSLTCP: return "gturn(ssltcp)";
556 default: return "gturn(?)";
557 }
558 }
559 }
560
561 void TestCrossFamilyPorts(int type);
562
Peter Thatcherb8b01432015-07-07 16:45:53 -0700563 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
564
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000565 // This does all the work and then deletes |port1| and |port2|.
566 void TestConnectivity(const char* name1, Port* port1,
567 const char* name2, Port* port2,
568 bool accept, bool same_addr1,
569 bool same_addr2, bool possible);
570
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700571 // This connects the provided channels which have already started. |ch1|
572 // should have its Connection created (either through CreateConnection() or
573 // TCP reconnecting mechanism before entering this function.
574 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
575 ASSERT_TRUE(ch1->conn());
576 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
577 ch1->Ping();
578 WAIT(!ch2->remote_address().IsNil(), kTimeout);
579
580 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700581 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700582 ch2->Ping();
583 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
584 kTimeout);
585 }
586
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 // This connects and disconnects the provided channels in the same sequence as
588 // TestConnectivity with all options set to |true|. It does not delete either
589 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700590 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
591 // Acquire addresses.
592 ch1->Start();
593 ch2->Start();
594
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700595 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700596 ConnectStartedChannels(ch1, ch2);
597
598 // Destroy the connections.
599 ch1->Stop();
600 ch2->Stop();
601 }
602
603 // This disconnects both end's Connection and make sure ch2 ready for new
604 // connection.
605 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700606 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
607 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
608 ASSERT_TRUE(
609 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
610 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700611
612 // Wait for both OnClose are delivered.
613 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
614 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
615
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700616 // Ensure redundant SignalClose events on TcpConnection won't break tcp
617 // reconnection. Chromium will fire SignalClose for all outstanding IPC
618 // packets during reconnection.
619 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
620 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
621
622 // Speed up destroying ch2's connection such that the test is ready to
623 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700624 ch2->conn()->Destroy();
625 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
626 }
627
628 void TestTcpReconnect(bool ping_after_disconnected,
629 bool send_after_disconnected) {
630 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700631 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700632 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700633 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700634
635 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
636 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
637
638 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700639 TestChannel ch1(port1);
640 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700641 EXPECT_EQ(0, ch1.complete_count());
642 EXPECT_EQ(0, ch2.complete_count());
643
644 ch1.Start();
645 ch2.Start();
646 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
647 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
648
649 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700650 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700651 ConnectStartedChannels(&ch1, &ch2);
652
653 // Shorten the timeout period.
654 const int kTcpReconnectTimeout = kTimeout;
655 static_cast<TCPConnection*>(ch1.conn())
656 ->set_reconnection_timeout(kTcpReconnectTimeout);
657 static_cast<TCPConnection*>(ch2.conn())
658 ->set_reconnection_timeout(kTcpReconnectTimeout);
659
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700660 EXPECT_FALSE(ch1.connection_ready_to_send());
661 EXPECT_FALSE(ch2.connection_ready_to_send());
662
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700663 // Once connected, disconnect them.
664 DisconnectTcpTestChannels(&ch1, &ch2);
665
666 if (send_after_disconnected || ping_after_disconnected) {
667 if (send_after_disconnected) {
668 // First SendData after disconnect should fail but will trigger
669 // reconnect.
670 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
671 }
672
673 if (ping_after_disconnected) {
674 // Ping should trigger reconnect.
675 ch1.Ping();
676 }
677
678 // Wait for channel's outgoing TCPConnection connected.
679 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
680
681 // Verify that we could still connect channels.
682 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700683 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
684 kTcpReconnectTimeout);
685 // Channel2 is the passive one so a new connection is created during
686 // reconnect. This new connection should never have issued EWOULDBLOCK
687 // hence the connection_ready_to_send() should be false.
688 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700689 } else {
690 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700691 // Since the reconnection never happens, the connections should have been
692 // destroyed after the timeout.
693 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
694 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700695 }
696
697 // Tear down and ensure that goes smoothly.
698 ch1.Stop();
699 ch2.Stop();
700 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
701 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
702 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000703
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704 IceMessage* CreateStunMessage(int type) {
705 IceMessage* msg = new IceMessage();
706 msg->SetType(type);
707 msg->SetTransactionID("TESTTESTTEST");
708 return msg;
709 }
710 IceMessage* CreateStunMessageWithUsername(int type,
711 const std::string& username) {
712 IceMessage* msg = CreateStunMessage(type);
713 msg->AddAttribute(
714 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
715 return msg;
716 }
717 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
718 const std::string& username,
719 const std::string& password) {
720 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
721 addr.ipaddr(), 0, 0, username, password);
722 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
723 return port;
724 }
725 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
726 const std::string& username,
727 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000728 cricket::IceRole role,
729 int tiebreaker) {
730 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731 port->SetIceRole(role);
732 port->SetIceTiebreaker(tiebreaker);
733 return port;
734 }
735
736 void OnRoleConflict(PortInterface* port) {
737 role_conflict_ = true;
738 }
739 bool role_conflict() const { return role_conflict_; }
740
741 void ConnectToSignalDestroyed(PortInterface* port) {
742 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
743 }
744
745 void OnDestroyed(PortInterface* port) {
746 destroyed_ = true;
747 }
748 bool destroyed() const { return destroyed_; }
749
750 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
751 return &nat_socket_factory1_;
752 }
753
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700754 protected:
755 rtc::VirtualSocketServer* vss() { return ss_.get(); }
756
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 private:
758 rtc::Thread* main_;
759 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
760 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
761 rtc::SocketServerScope ss_scope_;
762 rtc::Network network_;
763 rtc::BasicPacketSocketFactory socket_factory_;
764 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
765 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
766 rtc::NATSocketFactory nat_factory1_;
767 rtc::NATSocketFactory nat_factory2_;
768 rtc::BasicPacketSocketFactory nat_socket_factory1_;
769 rtc::BasicPacketSocketFactory nat_socket_factory2_;
770 scoped_ptr<TestStunServer> stun_server_;
771 TestTurnServer turn_server_;
772 TestRelayServer relay_server_;
773 std::string username_;
774 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000775 bool role_conflict_;
776 bool destroyed_;
777};
778
779void PortTest::TestConnectivity(const char* name1, Port* port1,
780 const char* name2, Port* port2,
781 bool accept, bool same_addr1,
782 bool same_addr2, bool possible) {
783 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
784 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
785 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
786
787 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700788 TestChannel ch1(port1);
789 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000790 EXPECT_EQ(0, ch1.complete_count());
791 EXPECT_EQ(0, ch2.complete_count());
792
793 // Acquire addresses.
794 ch1.Start();
795 ch2.Start();
796 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
797 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
798
799 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700800 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 ASSERT_TRUE(ch1.conn() != NULL);
802 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
803 ch1.Ping();
804 WAIT(!ch2.remote_address().IsNil(), kTimeout);
805
806 if (accept) {
807 // We are able to send a ping from src to dst. This is the case when
808 // sending to UDP ports and cone NATs.
809 EXPECT_TRUE(ch1.remote_address().IsNil());
810 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
811
812 // Ensure the ping came from the same address used for src.
813 // This is the case unless the source NAT was symmetric.
814 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
815 EXPECT_TRUE(same_addr2);
816
817 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700818 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819 ASSERT_TRUE(ch2.conn() != NULL);
820 ch2.Ping();
821 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
822 kTimeout);
823 } else {
824 // We can't send a ping from src to dst, so flip it around. This will happen
825 // when the destination NAT is addr/port restricted or symmetric.
826 EXPECT_TRUE(ch1.remote_address().IsNil());
827 EXPECT_TRUE(ch2.remote_address().IsNil());
828
829 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700830 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831 ASSERT_TRUE(ch2.conn() != NULL);
832 ch2.Ping();
833 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
834
835 if (same_addr1 && same_addr2) {
836 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700837 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000838 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
839
840 // First connection may not be writable if the first ping did not get
841 // through. So we will have to do another.
842 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
843 ch1.Ping();
844 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
845 kTimeout);
846 }
847 } else if (!same_addr1 && possible) {
848 // The new ping went to the candidate address, but that address was bad.
849 // This will happen when the source NAT is symmetric.
850 EXPECT_TRUE(ch1.remote_address().IsNil());
851 EXPECT_TRUE(ch2.remote_address().IsNil());
852
853 // However, since we have now sent a ping to the source IP, we should be
854 // able to get a ping from it. This gives us the real source address.
855 ch1.Ping();
856 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700857 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000858 EXPECT_TRUE(ch1.remote_address().IsNil());
859
860 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700861 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862 ASSERT_TRUE(ch2.conn() != NULL);
863 ch2.Ping();
864 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
865 kTimeout);
866 } else if (!same_addr2 && possible) {
867 // The new ping came in, but from an unexpected address. This will happen
868 // when the destination NAT is symmetric.
869 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700870 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000871
872 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700873 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 ch1.Ping();
875 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
876 kTimeout);
877 } else { // (!possible)
878 // There should be s no way for the pings to reach each other. Check it.
879 EXPECT_TRUE(ch1.remote_address().IsNil());
880 EXPECT_TRUE(ch2.remote_address().IsNil());
881 ch1.Ping();
882 WAIT(!ch2.remote_address().IsNil(), kTimeout);
883 EXPECT_TRUE(ch1.remote_address().IsNil());
884 EXPECT_TRUE(ch2.remote_address().IsNil());
885 }
886 }
887
888 // Everything should be good, unless we know the situation is impossible.
889 ASSERT_TRUE(ch1.conn() != NULL);
890 ASSERT_TRUE(ch2.conn() != NULL);
891 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700892 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700894 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
896 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700897 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700899 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
901 }
902
903 // Tear down and ensure that goes smoothly.
904 ch1.Stop();
905 ch2.Stop();
906 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
907 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
908}
909
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910class FakePacketSocketFactory : public rtc::PacketSocketFactory {
911 public:
912 FakePacketSocketFactory()
913 : next_udp_socket_(NULL),
914 next_server_tcp_socket_(NULL),
915 next_client_tcp_socket_(NULL) {
916 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000917 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000919 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200920 uint16_t min_port,
921 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922 EXPECT_TRUE(next_udp_socket_ != NULL);
923 AsyncPacketSocket* result = next_udp_socket_;
924 next_udp_socket_ = NULL;
925 return result;
926 }
927
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000928 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200929 uint16_t min_port,
930 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000931 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000932 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
933 AsyncPacketSocket* result = next_server_tcp_socket_;
934 next_server_tcp_socket_ = NULL;
935 return result;
936 }
937
938 // TODO: |proxy_info| and |user_agent| should be set
939 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000940 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
941 const SocketAddress& remote_address,
942 const rtc::ProxyInfo& proxy_info,
943 const std::string& user_agent,
944 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000945 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
946 AsyncPacketSocket* result = next_client_tcp_socket_;
947 next_client_tcp_socket_ = NULL;
948 return result;
949 }
950
951 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
952 next_udp_socket_ = next_udp_socket;
953 }
954 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
955 next_server_tcp_socket_ = next_server_tcp_socket;
956 }
957 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
958 next_client_tcp_socket_ = next_client_tcp_socket;
959 }
960 rtc::AsyncResolverInterface* CreateAsyncResolver() {
961 return NULL;
962 }
963
964 private:
965 AsyncPacketSocket* next_udp_socket_;
966 AsyncPacketSocket* next_server_tcp_socket_;
967 AsyncPacketSocket* next_client_tcp_socket_;
968};
969
970class FakeAsyncPacketSocket : public AsyncPacketSocket {
971 public:
972 // Returns current local address. Address may be set to NULL if the
973 // socket is not bound yet (GetState() returns STATE_BINDING).
974 virtual SocketAddress GetLocalAddress() const {
975 return SocketAddress();
976 }
977
978 // Returns remote address. Returns zeroes if this is not a client TCP socket.
979 virtual SocketAddress GetRemoteAddress() const {
980 return SocketAddress();
981 }
982
983 // Send a packet.
984 virtual int Send(const void *pv, size_t cb,
985 const rtc::PacketOptions& options) {
986 return static_cast<int>(cb);
987 }
988 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
989 const rtc::PacketOptions& options) {
990 return static_cast<int>(cb);
991 }
992 virtual int Close() {
993 return 0;
994 }
995
996 virtual State GetState() const { return state_; }
997 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
998 virtual int SetOption(Socket::Option opt, int value) { return 0; }
999 virtual int GetError() const { return 0; }
1000 virtual void SetError(int error) { }
1001
1002 void set_state(State state) { state_ = state; }
1003
1004 private:
1005 State state_;
1006};
1007
1008// Local -> XXXX
1009TEST_F(PortTest, TestLocalToLocal) {
1010 TestLocalToLocal();
1011}
1012
1013TEST_F(PortTest, TestLocalToConeNat) {
1014 TestLocalToStun(NAT_OPEN_CONE);
1015}
1016
1017TEST_F(PortTest, TestLocalToARNat) {
1018 TestLocalToStun(NAT_ADDR_RESTRICTED);
1019}
1020
1021TEST_F(PortTest, TestLocalToPRNat) {
1022 TestLocalToStun(NAT_PORT_RESTRICTED);
1023}
1024
1025TEST_F(PortTest, TestLocalToSymNat) {
1026 TestLocalToStun(NAT_SYMMETRIC);
1027}
1028
1029// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1030TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1031 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1032}
1033
1034TEST_F(PortTest, TestLocalToGturn) {
1035 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1036}
1037
1038TEST_F(PortTest, TestLocalToTcpGturn) {
1039 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1040}
1041
1042TEST_F(PortTest, TestLocalToSslTcpGturn) {
1043 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1044}
1045
1046// Cone NAT -> XXXX
1047TEST_F(PortTest, TestConeNatToLocal) {
1048 TestStunToLocal(NAT_OPEN_CONE);
1049}
1050
1051TEST_F(PortTest, TestConeNatToConeNat) {
1052 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1053}
1054
1055TEST_F(PortTest, TestConeNatToARNat) {
1056 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1057}
1058
1059TEST_F(PortTest, TestConeNatToPRNat) {
1060 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1061}
1062
1063TEST_F(PortTest, TestConeNatToSymNat) {
1064 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1065}
1066
1067TEST_F(PortTest, TestConeNatToTurn) {
1068 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1069}
1070
1071TEST_F(PortTest, TestConeNatToGturn) {
1072 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1073}
1074
1075TEST_F(PortTest, TestConeNatToTcpGturn) {
1076 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1077}
1078
1079// Address-restricted NAT -> XXXX
1080TEST_F(PortTest, TestARNatToLocal) {
1081 TestStunToLocal(NAT_ADDR_RESTRICTED);
1082}
1083
1084TEST_F(PortTest, TestARNatToConeNat) {
1085 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1086}
1087
1088TEST_F(PortTest, TestARNatToARNat) {
1089 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1090}
1091
1092TEST_F(PortTest, TestARNatToPRNat) {
1093 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1094}
1095
1096TEST_F(PortTest, TestARNatToSymNat) {
1097 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1098}
1099
1100TEST_F(PortTest, TestARNatToTurn) {
1101 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1102}
1103
1104TEST_F(PortTest, TestARNatToGturn) {
1105 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1106}
1107
1108TEST_F(PortTest, TestARNATNatToTcpGturn) {
1109 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1110}
1111
1112// Port-restricted NAT -> XXXX
1113TEST_F(PortTest, TestPRNatToLocal) {
1114 TestStunToLocal(NAT_PORT_RESTRICTED);
1115}
1116
1117TEST_F(PortTest, TestPRNatToConeNat) {
1118 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1119}
1120
1121TEST_F(PortTest, TestPRNatToARNat) {
1122 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1123}
1124
1125TEST_F(PortTest, TestPRNatToPRNat) {
1126 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1127}
1128
1129TEST_F(PortTest, TestPRNatToSymNat) {
1130 // Will "fail"
1131 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1132}
1133
1134TEST_F(PortTest, TestPRNatToTurn) {
1135 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1136}
1137
1138TEST_F(PortTest, TestPRNatToGturn) {
1139 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1140}
1141
1142TEST_F(PortTest, TestPRNatToTcpGturn) {
1143 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1144}
1145
1146// Symmetric NAT -> XXXX
1147TEST_F(PortTest, TestSymNatToLocal) {
1148 TestStunToLocal(NAT_SYMMETRIC);
1149}
1150
1151TEST_F(PortTest, TestSymNatToConeNat) {
1152 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1153}
1154
1155TEST_F(PortTest, TestSymNatToARNat) {
1156 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1157}
1158
1159TEST_F(PortTest, TestSymNatToPRNat) {
1160 // Will "fail"
1161 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1162}
1163
1164TEST_F(PortTest, TestSymNatToSymNat) {
1165 // Will "fail"
1166 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1167}
1168
1169TEST_F(PortTest, TestSymNatToTurn) {
1170 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1171}
1172
1173TEST_F(PortTest, TestSymNatToGturn) {
1174 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1175}
1176
1177TEST_F(PortTest, TestSymNatToTcpGturn) {
1178 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1179}
1180
1181// Outbound TCP -> XXXX
1182TEST_F(PortTest, TestTcpToTcp) {
1183 TestTcpToTcp();
1184}
1185
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001186TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1187 TestTcpReconnect(false /* ping */, true /* send */);
1188}
1189
1190TEST_F(PortTest, TestTcpReconnectOnPing) {
1191 TestTcpReconnect(true /* ping */, false /* send */);
1192}
1193
1194TEST_F(PortTest, TestTcpReconnectTimeout) {
1195 TestTcpReconnect(false /* ping */, false /* send */);
1196}
1197
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001198// Test when TcpConnection never connects, the OnClose() will be called to
1199// destroy the connection.
1200TEST_F(PortTest, TestTcpNeverConnect) {
1201 Port* port1 = CreateTcpPort(kLocalAddr1);
1202 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1203 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1204
1205 // Set up a channel and ensure the port will be deleted.
1206 TestChannel ch1(port1);
1207 EXPECT_EQ(0, ch1.complete_count());
1208
1209 ch1.Start();
1210 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1211
1212 rtc::scoped_ptr<rtc::AsyncSocket> server(
1213 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1214 // Bind but not listen.
1215 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1216
1217 Candidate c = GetCandidate(port1);
1218 c.set_address(server->GetLocalAddress());
1219
1220 ch1.CreateConnection(c);
1221 EXPECT_TRUE(ch1.conn());
1222 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1223}
1224
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001225/* TODO: Enable these once testrelayserver can accept external TCP.
1226TEST_F(PortTest, TestTcpToTcpRelay) {
1227 TestTcpToRelay(PROTO_TCP);
1228}
1229
1230TEST_F(PortTest, TestTcpToSslTcpRelay) {
1231 TestTcpToRelay(PROTO_SSLTCP);
1232}
1233*/
1234
1235// Outbound SSLTCP -> XXXX
1236/* TODO: Enable these once testrelayserver can accept external SSL.
1237TEST_F(PortTest, TestSslTcpToTcpRelay) {
1238 TestSslTcpToRelay(PROTO_TCP);
1239}
1240
1241TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1242 TestSslTcpToRelay(PROTO_SSLTCP);
1243}
1244*/
1245
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001246// Test that a connection will be dead and deleted if
1247// i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1248// since it was created, or
1249// ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1250// milliseconds since last receiving.
1251TEST_F(PortTest, TestConnectionDead) {
1252 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1253 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1254 TestChannel ch1(port1);
1255 TestChannel ch2(port2);
1256 // Acquire address.
1257 ch1.Start();
1258 ch2.Start();
1259 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1260 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
1261
honghaiz37389b42016-01-04 21:57:33 -08001262 // Test case that the connection has never received anything.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001263 uint32_t before_created = rtc::Time();
1264 ch1.CreateConnection(GetCandidate(port2));
1265 uint32_t after_created = rtc::Time();
1266 Connection* conn = ch1.conn();
1267 ASSERT(conn != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001268 // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned.
1269 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1270 rtc::Thread::Current()->ProcessMessages(0);
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001271 EXPECT_TRUE(ch1.conn() != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001272 // It is not dead if it is before MIN_CONNECTION_LIFETIME and pruned.
1273 conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1274 conn->Prune();
1275 rtc::Thread::Current()->ProcessMessages(0);
1276 EXPECT_TRUE(ch1.conn() != nullptr);
1277 // It will be dead after MIN_CONNECTION_LIFETIME and pruned.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001278 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1279 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1280
honghaiz37389b42016-01-04 21:57:33 -08001281 // Test case that the connection has received something.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001282 // Create a connection again and receive a ping.
1283 ch1.CreateConnection(GetCandidate(port2));
1284 conn = ch1.conn();
1285 ASSERT(conn != nullptr);
1286 uint32_t before_last_receiving = rtc::Time();
1287 conn->ReceivedPing();
1288 uint32_t after_last_receiving = rtc::Time();
1289 // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1290 conn->UpdateState(
1291 before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1292 rtc::Thread::Current()->ProcessMessages(100);
1293 EXPECT_TRUE(ch1.conn() != nullptr);
1294 conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1295 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1296}
1297
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001298// This test case verifies standard ICE features in STUN messages. Currently it
1299// verifies Message Integrity attribute in STUN messages and username in STUN
1300// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001301TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001302 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1303 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1304 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001305 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1306 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1307 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001308 // Same parameters as TestLocalToLocal above.
1309 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1310}
1311
1312// This test is trying to validate a successful and failure scenario in a
1313// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1314// should remain equal to the request generated by the port and role of port
1315// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001316TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317 rtc::scoped_ptr<TestPort> lport(
1318 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001319 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1320 lport->SetIceTiebreaker(kTiebreaker1);
1321 lport->PrepareAddress();
1322 ASSERT_FALSE(lport->Candidates().empty());
1323 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1324 Port::ORIGIN_MESSAGE);
1325 conn->Ping(0);
1326
1327 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1328 IceMessage* msg = lport->last_stun_msg();
1329 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1330 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1331 lport->last_stun_buf()->Length(),
1332 rtc::PacketTime());
1333 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1334 msg = lport->last_stun_msg();
1335 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1336
1337 // If the tiebreaker value is different from port, we expect a error
1338 // response.
1339 lport->Reset();
1340 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001341 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1343 Port::ORIGIN_MESSAGE);
1344 conn1->Ping(0);
1345
1346 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1347 msg = lport->last_stun_msg();
1348 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1349 rtc::scoped_ptr<IceMessage> modified_req(
1350 CreateStunMessage(STUN_BINDING_REQUEST));
1351 const StunByteStringAttribute* username_attr = msg->GetByteString(
1352 STUN_ATTR_USERNAME);
1353 modified_req->AddAttribute(new StunByteStringAttribute(
1354 STUN_ATTR_USERNAME, username_attr->GetString()));
1355 // To make sure we receive error response, adding tiebreaker less than
1356 // what's present in request.
1357 modified_req->AddAttribute(new StunUInt64Attribute(
1358 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1359 modified_req->AddMessageIntegrity("lpass");
1360 modified_req->AddFingerprint();
1361
1362 lport->Reset();
1363 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1364 WriteStunMessage(modified_req.get(), buf.get());
1365 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1366 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1367 msg = lport->last_stun_msg();
1368 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1369}
1370
1371// This test verifies role conflict signal is received when there is
1372// conflict in the role. In this case both ports are in controlling and
1373// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1374// value of tiebreaker, when it receives ping request from |rport| it will
1375// send role conflict signal.
1376TEST_F(PortTest, TestIceRoleConflict) {
1377 rtc::scoped_ptr<TestPort> lport(
1378 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1380 lport->SetIceTiebreaker(kTiebreaker1);
1381 rtc::scoped_ptr<TestPort> rport(
1382 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001383 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1384 rport->SetIceTiebreaker(kTiebreaker2);
1385
1386 lport->PrepareAddress();
1387 rport->PrepareAddress();
1388 ASSERT_FALSE(lport->Candidates().empty());
1389 ASSERT_FALSE(rport->Candidates().empty());
1390 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1391 Port::ORIGIN_MESSAGE);
1392 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1393 Port::ORIGIN_MESSAGE);
1394 rconn->Ping(0);
1395
1396 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1397 IceMessage* msg = rport->last_stun_msg();
1398 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1399 // Send rport binding request to lport.
1400 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1401 rport->last_stun_buf()->Length(),
1402 rtc::PacketTime());
1403
1404 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1405 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1406 EXPECT_TRUE(role_conflict());
1407}
1408
1409TEST_F(PortTest, TestTcpNoDelay) {
1410 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001411 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412 int option_value = -1;
1413 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1414 &option_value);
1415 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1416 ASSERT_EQ(1, option_value);
1417 delete port1;
1418}
1419
1420TEST_F(PortTest, TestDelayedBindingUdp) {
1421 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1422 FakePacketSocketFactory socket_factory;
1423
1424 socket_factory.set_next_udp_socket(socket);
1425 scoped_ptr<UDPPort> port(
1426 CreateUdpPort(kLocalAddr1, &socket_factory));
1427
1428 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1429 port->PrepareAddress();
1430
1431 EXPECT_EQ(0U, port->Candidates().size());
1432 socket->SignalAddressReady(socket, kLocalAddr2);
1433
1434 EXPECT_EQ(1U, port->Candidates().size());
1435}
1436
1437TEST_F(PortTest, TestDelayedBindingTcp) {
1438 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1439 FakePacketSocketFactory socket_factory;
1440
1441 socket_factory.set_next_server_tcp_socket(socket);
1442 scoped_ptr<TCPPort> port(
1443 CreateTcpPort(kLocalAddr1, &socket_factory));
1444
1445 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1446 port->PrepareAddress();
1447
1448 EXPECT_EQ(0U, port->Candidates().size());
1449 socket->SignalAddressReady(socket, kLocalAddr2);
1450
1451 EXPECT_EQ(1U, port->Candidates().size());
1452}
1453
1454void PortTest::TestCrossFamilyPorts(int type) {
1455 FakePacketSocketFactory factory;
1456 scoped_ptr<Port> ports[4];
1457 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1458 SocketAddress("192.168.1.4", 0),
1459 SocketAddress("2001:db8::1", 0),
1460 SocketAddress("2001:db8::2", 0)};
1461 for (int i = 0; i < 4; i++) {
1462 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1463 if (type == SOCK_DGRAM) {
1464 factory.set_next_udp_socket(socket);
1465 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1466 } else if (type == SOCK_STREAM) {
1467 factory.set_next_server_tcp_socket(socket);
1468 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1469 }
1470 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1471 socket->SignalAddressReady(socket, addresses[i]);
1472 ports[i]->PrepareAddress();
1473 }
1474
1475 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1476 if (type == SOCK_STREAM) {
1477 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1478 factory.set_next_client_tcp_socket(clientsocket);
1479 }
1480 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1481 Port::ORIGIN_MESSAGE);
1482 EXPECT_TRUE(NULL == c);
1483 EXPECT_EQ(0U, ports[0]->connections().size());
1484 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1485 Port::ORIGIN_MESSAGE);
1486 EXPECT_FALSE(NULL == c);
1487 EXPECT_EQ(1U, ports[0]->connections().size());
1488
1489 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1490 if (type == SOCK_STREAM) {
1491 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1492 factory.set_next_client_tcp_socket(clientsocket);
1493 }
1494 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1495 Port::ORIGIN_MESSAGE);
1496 EXPECT_TRUE(NULL == c);
1497 EXPECT_EQ(0U, ports[2]->connections().size());
1498 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1499 Port::ORIGIN_MESSAGE);
1500 EXPECT_FALSE(NULL == c);
1501 EXPECT_EQ(1U, ports[2]->connections().size());
1502}
1503
1504TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1505 TestCrossFamilyPorts(SOCK_STREAM);
1506}
1507
1508TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1509 TestCrossFamilyPorts(SOCK_DGRAM);
1510}
1511
Peter Thatcherb8b01432015-07-07 16:45:53 -07001512void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1513 Connection* c = p1->CreateConnection(GetCandidate(p2),
1514 Port::ORIGIN_MESSAGE);
1515 if (can_connect) {
1516 EXPECT_FALSE(NULL == c);
1517 EXPECT_EQ(1U, p1->connections().size());
1518 } else {
1519 EXPECT_TRUE(NULL == c);
1520 EXPECT_EQ(0U, p1->connections().size());
1521 }
1522}
1523
1524TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1525 FakePacketSocketFactory factory;
1526 scoped_ptr<Port> ports[4];
1527 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1528 SocketAddress("fe80::1", 0),
1529 SocketAddress("fe80::2", 0),
1530 SocketAddress("::1", 0)};
1531 for (int i = 0; i < 4; i++) {
1532 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1533 factory.set_next_udp_socket(socket);
1534 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1535 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1536 socket->SignalAddressReady(socket, addresses[i]);
1537 ports[i]->PrepareAddress();
1538 }
1539
1540 Port* standard = ports[0].get();
1541 Port* link_local1 = ports[1].get();
1542 Port* link_local2 = ports[2].get();
1543 Port* localhost = ports[3].get();
1544
1545 ExpectPortsCanConnect(false, link_local1, standard);
1546 ExpectPortsCanConnect(false, standard, link_local1);
1547 ExpectPortsCanConnect(false, link_local1, localhost);
1548 ExpectPortsCanConnect(false, localhost, link_local1);
1549
1550 ExpectPortsCanConnect(true, link_local1, link_local2);
1551 ExpectPortsCanConnect(true, localhost, standard);
1552 ExpectPortsCanConnect(true, standard, localhost);
1553}
1554
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001555// This test verifies DSCP value set through SetOption interface can be
1556// get through DefaultDscpValue.
1557TEST_F(PortTest, TestDefaultDscpValue) {
1558 int dscp;
1559 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1560 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1561 rtc::DSCP_CS6));
1562 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1563 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1564 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1565 rtc::DSCP_AF31));
1566 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1567 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1568 rtc::scoped_ptr<StunPort> stunport(
1569 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1570 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1571 rtc::DSCP_AF41));
1572 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1573 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1574 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1575 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1576 // Socket is created in PrepareAddress.
1577 turnport1->PrepareAddress();
1578 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1579 rtc::DSCP_CS7));
1580 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1581 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1582 // This will verify correct value returned without the socket.
1583 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1584 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1585 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1586 rtc::DSCP_CS6));
1587 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1588 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1589}
1590
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001591// Test sending STUN messages.
1592TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001593 rtc::scoped_ptr<TestPort> lport(
1594 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1595 rtc::scoped_ptr<TestPort> rport(
1596 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001597 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1598 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001599 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1600 rport->SetIceTiebreaker(kTiebreaker2);
1601
1602 // Send a fake ping from lport to rport.
1603 lport->PrepareAddress();
1604 rport->PrepareAddress();
1605 ASSERT_FALSE(rport->Candidates().empty());
1606 Connection* lconn = lport->CreateConnection(
1607 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1608 Connection* rconn = rport->CreateConnection(
1609 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1610 lconn->Ping(0);
1611
1612 // Check that it's a proper BINDING-REQUEST.
1613 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1614 IceMessage* msg = lport->last_stun_msg();
1615 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1616 EXPECT_FALSE(msg->IsLegacy());
1617 const StunByteStringAttribute* username_attr =
1618 msg->GetByteString(STUN_ATTR_USERNAME);
1619 ASSERT_TRUE(username_attr != NULL);
1620 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1621 ASSERT_TRUE(priority_attr != NULL);
1622 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1623 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1624 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1625 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1626 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1627 "rpass"));
1628 const StunUInt64Attribute* ice_controlling_attr =
1629 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1630 ASSERT_TRUE(ice_controlling_attr != NULL);
1631 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1632 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1633 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1634 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1635 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1636 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1637
1638 // Request should not include ping count.
1639 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1640
1641 // Save a copy of the BINDING-REQUEST for use below.
1642 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1643
1644 // Respond with a BINDING-RESPONSE.
1645 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1646 msg = rport->last_stun_msg();
1647 ASSERT_TRUE(msg != NULL);
1648 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1649
1650
1651 EXPECT_FALSE(msg->IsLegacy());
1652 const StunAddressAttribute* addr_attr = msg->GetAddress(
1653 STUN_ATTR_XOR_MAPPED_ADDRESS);
1654 ASSERT_TRUE(addr_attr != NULL);
1655 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1656 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1657 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1658 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1659 "rpass"));
1660 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1661 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1662 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1663 // No USERNAME or PRIORITY in ICE responses.
1664 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1665 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1666 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1667 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1668 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1669 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1670
1671 // Response should not include ping count.
1672 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1673
1674 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1675 // but we can do it here.
1676 rport->SendBindingErrorResponse(request.get(),
1677 lport->Candidates()[0].address(),
1678 STUN_ERROR_SERVER_ERROR,
1679 STUN_ERROR_REASON_SERVER_ERROR);
1680 msg = rport->last_stun_msg();
1681 ASSERT_TRUE(msg != NULL);
1682 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1683 EXPECT_FALSE(msg->IsLegacy());
1684 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1685 ASSERT_TRUE(error_attr != NULL);
1686 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1687 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1688 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1689 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1690 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1691 "rpass"));
1692 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1693 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1694 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1695 // No USERNAME with ICE.
1696 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1697 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1698
1699 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1700 // and (incremented) RETRANSMIT_COUNT attributes.
1701 rport->Reset();
1702 rport->set_send_retransmit_count_attribute(true);
1703 rconn->Ping(0);
1704 rconn->Ping(0);
1705 rconn->Ping(0);
1706 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1707 msg = rport->last_stun_msg();
1708 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1709 const StunUInt64Attribute* ice_controlled_attr =
1710 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1711 ASSERT_TRUE(ice_controlled_attr != NULL);
1712 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1713 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1714
1715 // Request should include ping count.
1716 const StunUInt32Attribute* retransmit_attr =
1717 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1718 ASSERT_TRUE(retransmit_attr != NULL);
1719 EXPECT_EQ(2U, retransmit_attr->value());
1720
1721 // Respond with a BINDING-RESPONSE.
1722 request.reset(CopyStunMessage(msg));
1723 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1724 msg = lport->last_stun_msg();
1725
1726 // Response should include same ping count.
1727 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1728 ASSERT_TRUE(retransmit_attr != NULL);
1729 EXPECT_EQ(2U, retransmit_attr->value());
1730}
1731
1732TEST_F(PortTest, TestUseCandidateAttribute) {
1733 rtc::scoped_ptr<TestPort> lport(
1734 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1735 rtc::scoped_ptr<TestPort> rport(
1736 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001737 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1738 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001739 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1740 rport->SetIceTiebreaker(kTiebreaker2);
1741
1742 // Send a fake ping from lport to rport.
1743 lport->PrepareAddress();
1744 rport->PrepareAddress();
1745 ASSERT_FALSE(rport->Candidates().empty());
1746 Connection* lconn = lport->CreateConnection(
1747 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1748 lconn->Ping(0);
1749 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1750 IceMessage* msg = lport->last_stun_msg();
1751 const StunUInt64Attribute* ice_controlling_attr =
1752 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1753 ASSERT_TRUE(ice_controlling_attr != NULL);
1754 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1755 STUN_ATTR_USE_CANDIDATE);
1756 ASSERT_TRUE(use_candidate_attr != NULL);
1757}
1758
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001759// Test handling STUN messages.
1760TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001761 // Our port will act as the "remote" port.
1762 rtc::scoped_ptr<TestPort> port(
1763 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001764
1765 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1766 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1767 rtc::SocketAddress addr(kLocalAddr1);
1768 std::string username;
1769
1770 // BINDING-REQUEST from local to remote with valid ICE username,
1771 // MESSAGE-INTEGRITY, and FINGERPRINT.
1772 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1773 "rfrag:lfrag"));
1774 in_msg->AddMessageIntegrity("rpass");
1775 in_msg->AddFingerprint();
1776 WriteStunMessage(in_msg.get(), buf.get());
1777 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1778 out_msg.accept(), &username));
1779 EXPECT_TRUE(out_msg.get() != NULL);
1780 EXPECT_EQ("lfrag", username);
1781
1782 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1783 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1784 in_msg->AddAttribute(
1785 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1786 in_msg->AddMessageIntegrity("rpass");
1787 in_msg->AddFingerprint();
1788 WriteStunMessage(in_msg.get(), buf.get());
1789 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1790 out_msg.accept(), &username));
1791 EXPECT_TRUE(out_msg.get() != NULL);
1792 EXPECT_EQ("", username);
1793
1794 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1795 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1796 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1797 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1798 in_msg->AddFingerprint();
1799 WriteStunMessage(in_msg.get(), buf.get());
1800 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1801 out_msg.accept(), &username));
1802 EXPECT_TRUE(out_msg.get() != NULL);
1803 EXPECT_EQ("", username);
1804 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1805 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1806 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1807 out_msg->GetErrorCode()->reason());
1808}
1809
guoweisd12140a2015-09-10 13:32:11 -07001810// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001811TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001812 rtc::scoped_ptr<TestPort> port(
1813 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001814
1815 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1816 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1817 rtc::SocketAddress addr(kLocalAddr1);
1818 std::string username;
1819
1820 // BINDING-REQUEST with no username.
1821 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1822 in_msg->AddMessageIntegrity("rpass");
1823 in_msg->AddFingerprint();
1824 WriteStunMessage(in_msg.get(), buf.get());
1825 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1826 out_msg.accept(), &username));
1827 EXPECT_TRUE(out_msg.get() == NULL);
1828 EXPECT_EQ("", username);
1829 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1830
1831 // BINDING-REQUEST with empty username.
1832 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1833 in_msg->AddMessageIntegrity("rpass");
1834 in_msg->AddFingerprint();
1835 WriteStunMessage(in_msg.get(), buf.get());
1836 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1837 out_msg.accept(), &username));
1838 EXPECT_TRUE(out_msg.get() == NULL);
1839 EXPECT_EQ("", username);
1840 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1841
1842 // BINDING-REQUEST with too-short username.
1843 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1844 in_msg->AddMessageIntegrity("rpass");
1845 in_msg->AddFingerprint();
1846 WriteStunMessage(in_msg.get(), buf.get());
1847 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1848 out_msg.accept(), &username));
1849 EXPECT_TRUE(out_msg.get() == NULL);
1850 EXPECT_EQ("", username);
1851 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1852
1853 // BINDING-REQUEST with reversed username.
1854 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1855 "lfrag:rfrag"));
1856 in_msg->AddMessageIntegrity("rpass");
1857 in_msg->AddFingerprint();
1858 WriteStunMessage(in_msg.get(), buf.get());
1859 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1860 out_msg.accept(), &username));
1861 EXPECT_TRUE(out_msg.get() == NULL);
1862 EXPECT_EQ("", username);
1863 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1864
1865 // BINDING-REQUEST with garbage username.
1866 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1867 "abcd:efgh"));
1868 in_msg->AddMessageIntegrity("rpass");
1869 in_msg->AddFingerprint();
1870 WriteStunMessage(in_msg.get(), buf.get());
1871 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1872 out_msg.accept(), &username));
1873 EXPECT_TRUE(out_msg.get() == NULL);
1874 EXPECT_EQ("", username);
1875 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1876}
1877
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001878// Test handling STUN messages with missing or malformed M-I.
1879TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001880 // Our port will act as the "remote" port.
1881 rtc::scoped_ptr<TestPort> port(
1882 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001883
1884 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1885 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1886 rtc::SocketAddress addr(kLocalAddr1);
1887 std::string username;
1888
1889 // BINDING-REQUEST from local to remote with valid ICE username and
1890 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1891 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1892 "rfrag:lfrag"));
1893 in_msg->AddFingerprint();
1894 WriteStunMessage(in_msg.get(), buf.get());
1895 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1896 out_msg.accept(), &username));
1897 EXPECT_TRUE(out_msg.get() == NULL);
1898 EXPECT_EQ("", username);
1899 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1900
1901 // BINDING-REQUEST from local to remote with valid ICE username and
1902 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1903 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1904 "rfrag:lfrag"));
1905 in_msg->AddMessageIntegrity("invalid");
1906 in_msg->AddFingerprint();
1907 WriteStunMessage(in_msg.get(), buf.get());
1908 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1909 out_msg.accept(), &username));
1910 EXPECT_TRUE(out_msg.get() == NULL);
1911 EXPECT_EQ("", username);
1912 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1913
1914 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1915 // by the Connection, not the Port, since they require the remote username.
1916 // Change this test to pass in data via Connection::OnReadPacket instead.
1917}
1918
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001919// Test handling STUN messages with missing or malformed FINGERPRINT.
1920TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001921 // Our port will act as the "remote" port.
1922 rtc::scoped_ptr<TestPort> port(
1923 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001924
1925 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1926 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1927 rtc::SocketAddress addr(kLocalAddr1);
1928 std::string username;
1929
1930 // BINDING-REQUEST from local to remote with valid ICE username and
1931 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1932 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1933 "rfrag:lfrag"));
1934 in_msg->AddMessageIntegrity("rpass");
1935 WriteStunMessage(in_msg.get(), buf.get());
1936 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1937 out_msg.accept(), &username));
1938 EXPECT_EQ(0, port->last_stun_error_code());
1939
1940 // Now, add a fingerprint, but munge the message so it's not valid.
1941 in_msg->AddFingerprint();
1942 in_msg->SetTransactionID("TESTTESTBADD");
1943 WriteStunMessage(in_msg.get(), buf.get());
1944 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1945 out_msg.accept(), &username));
1946 EXPECT_EQ(0, port->last_stun_error_code());
1947
1948 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1949 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1950 in_msg->AddAttribute(
1951 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1952 in_msg->AddMessageIntegrity("rpass");
1953 WriteStunMessage(in_msg.get(), buf.get());
1954 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1955 out_msg.accept(), &username));
1956 EXPECT_EQ(0, port->last_stun_error_code());
1957
1958 // Now, add a fingerprint, but munge the message so it's not valid.
1959 in_msg->AddFingerprint();
1960 in_msg->SetTransactionID("TESTTESTBADD");
1961 WriteStunMessage(in_msg.get(), buf.get());
1962 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1963 out_msg.accept(), &username));
1964 EXPECT_EQ(0, port->last_stun_error_code());
1965
1966 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1967 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1968 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1969 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1970 in_msg->AddMessageIntegrity("rpass");
1971 WriteStunMessage(in_msg.get(), buf.get());
1972 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1973 out_msg.accept(), &username));
1974 EXPECT_EQ(0, port->last_stun_error_code());
1975
1976 // Now, add a fingerprint, but munge the message so it's not valid.
1977 in_msg->AddFingerprint();
1978 in_msg->SetTransactionID("TESTTESTBADD");
1979 WriteStunMessage(in_msg.get(), buf.get());
1980 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1981 out_msg.accept(), &username));
1982 EXPECT_EQ(0, port->last_stun_error_code());
1983}
1984
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001985// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001986// indications are allowed only to the connection which is in read mode.
1987TEST_F(PortTest, TestHandleStunBindingIndication) {
1988 rtc::scoped_ptr<TestPort> lport(
1989 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001990 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1991 lport->SetIceTiebreaker(kTiebreaker1);
1992
1993 // Verifying encoding and decoding STUN indication message.
1994 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1995 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1996 rtc::SocketAddress addr(kLocalAddr1);
1997 std::string username;
1998
1999 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
2000 in_msg->AddFingerprint();
2001 WriteStunMessage(in_msg.get(), buf.get());
2002 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
2003 out_msg.accept(), &username));
2004 EXPECT_TRUE(out_msg.get() != NULL);
2005 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2006 EXPECT_EQ("", username);
2007
2008 // Verify connection can handle STUN indication and updates
2009 // last_ping_received.
2010 rtc::scoped_ptr<TestPort> rport(
2011 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002012 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2013 rport->SetIceTiebreaker(kTiebreaker2);
2014
2015 lport->PrepareAddress();
2016 rport->PrepareAddress();
2017 ASSERT_FALSE(lport->Candidates().empty());
2018 ASSERT_FALSE(rport->Candidates().empty());
2019
2020 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2021 Port::ORIGIN_MESSAGE);
2022 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2023 Port::ORIGIN_MESSAGE);
2024 rconn->Ping(0);
2025
2026 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2027 IceMessage* msg = rport->last_stun_msg();
2028 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2029 // Send rport binding request to lport.
2030 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
2031 rport->last_stun_buf()->Length(),
2032 rtc::PacketTime());
2033 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2034 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
Peter Boström0c4e06b2015-10-07 12:23:21 +02002035 uint32_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002036
2037 // Adding a delay of 100ms.
2038 rtc::Thread::Current()->ProcessMessages(100);
2039 // Pinging lconn using stun indication message.
2040 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
Peter Boström0c4e06b2015-10-07 12:23:21 +02002041 uint32_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002042 EXPECT_GT(last_ping_received2, last_ping_received1);
2043}
2044
2045TEST_F(PortTest, TestComputeCandidatePriority) {
2046 rtc::scoped_ptr<TestPort> port(
2047 CreateTestPort(kLocalAddr1, "name", "pass"));
2048 port->set_type_preference(90);
2049 port->set_component(177);
2050 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2051 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2052 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2053 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2054 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2055 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2056 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2057 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2058 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2059 // These should all be:
2060 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002061 uint32_t expected_priority_v4 = 1509957199U;
2062 uint32_t expected_priority_v6 = 1509959759U;
2063 uint32_t expected_priority_ula = 1509962319U;
2064 uint32_t expected_priority_v4mapped = expected_priority_v4;
2065 uint32_t expected_priority_v4compat = 1509949775U;
2066 uint32_t expected_priority_6to4 = 1509954639U;
2067 uint32_t expected_priority_teredo = 1509952079U;
2068 uint32_t expected_priority_sitelocal = 1509949775U;
2069 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002070 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2071 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2072 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2073 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2074 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2075 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2076 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2077 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2078 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2079}
2080
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002081// In the case of shared socket, one port may be shared by local and stun.
2082// Test that candidates with different types will have different foundation.
2083TEST_F(PortTest, TestFoundation) {
2084 rtc::scoped_ptr<TestPort> testport(
2085 CreateTestPort(kLocalAddr1, "name", "pass"));
2086 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2087 LOCAL_PORT_TYPE,
2088 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2089 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2090 STUN_PORT_TYPE,
2091 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2092 EXPECT_NE(testport->Candidates()[0].foundation(),
2093 testport->Candidates()[1].foundation());
2094}
2095
2096// This test verifies the foundation of different types of ICE candidates.
2097TEST_F(PortTest, TestCandidateFoundation) {
2098 rtc::scoped_ptr<rtc::NATServer> nat_server(
2099 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2100 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2101 udpport1->PrepareAddress();
2102 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2103 udpport2->PrepareAddress();
2104 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2105 udpport2->Candidates()[0].foundation());
2106 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2107 tcpport1->PrepareAddress();
2108 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2109 tcpport2->PrepareAddress();
2110 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2111 tcpport2->Candidates()[0].foundation());
2112 rtc::scoped_ptr<Port> stunport(
2113 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2114 stunport->PrepareAddress();
2115 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2116 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2117 stunport->Candidates()[0].foundation());
2118 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2119 stunport->Candidates()[0].foundation());
2120 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2121 stunport->Candidates()[0].foundation());
2122 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2123 stunport->Candidates()[0].foundation());
2124 // Verify GTURN candidate foundation.
2125 rtc::scoped_ptr<RelayPort> relayport(
2126 CreateGturnPort(kLocalAddr1));
2127 relayport->AddServerAddress(
2128 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2129 relayport->PrepareAddress();
2130 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2131 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2132 relayport->Candidates()[0].foundation());
2133 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2134 relayport->Candidates()[0].foundation());
2135 // Verifying TURN candidate foundation.
2136 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2137 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2138 turnport1->PrepareAddress();
2139 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2140 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2141 turnport1->Candidates()[0].foundation());
2142 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2143 turnport1->Candidates()[0].foundation());
2144 EXPECT_NE(stunport->Candidates()[0].foundation(),
2145 turnport1->Candidates()[0].foundation());
2146 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2147 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2148 turnport2->PrepareAddress();
2149 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2150 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2151 turnport2->Candidates()[0].foundation());
2152
2153 // Running a second turn server, to get different base IP address.
2154 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2155 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2156 TestTurnServer turn_server2(
2157 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2158 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2159 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2160 kTurnUdpIntAddr2));
2161 turnport3->PrepareAddress();
2162 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2163 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2164 turnport2->Candidates()[0].foundation());
2165}
2166
2167// This test verifies the related addresses of different types of
2168// ICE candiates.
2169TEST_F(PortTest, TestCandidateRelatedAddress) {
2170 rtc::scoped_ptr<rtc::NATServer> nat_server(
2171 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2172 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2173 udpport->PrepareAddress();
2174 // For UDPPort, related address will be empty.
2175 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2176 // Testing related address for stun candidates.
2177 // For stun candidate related address must be equal to the base
2178 // socket address.
2179 rtc::scoped_ptr<StunPort> stunport(
2180 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2181 stunport->PrepareAddress();
2182 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2183 // Check STUN candidate address.
2184 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2185 kNatAddr1.ipaddr());
2186 // Check STUN candidate related address.
2187 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2188 stunport->GetLocalAddress());
2189 // Verifying the related address for the GTURN candidates.
2190 // NOTE: In case of GTURN related address will be equal to the mapped
2191 // address, but address(mapped) will not be XOR.
2192 rtc::scoped_ptr<RelayPort> relayport(
2193 CreateGturnPort(kLocalAddr1));
2194 relayport->AddServerAddress(
2195 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2196 relayport->PrepareAddress();
2197 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2198 // For Gturn related address is set to "0.0.0.0:0"
2199 EXPECT_EQ(rtc::SocketAddress(),
2200 relayport->Candidates()[0].related_address());
2201 // Verifying the related address for TURN candidate.
2202 // For TURN related address must be equal to the mapped address.
2203 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2204 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2205 turnport->PrepareAddress();
2206 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2207 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2208 turnport->Candidates()[0].address().ipaddr());
2209 EXPECT_EQ(kNatAddr1.ipaddr(),
2210 turnport->Candidates()[0].related_address().ipaddr());
2211}
2212
2213// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002214TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002215 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002216 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002217 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002218 cand2.set_priority(1);
2219 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002220}
2221
2222// Test the Connection priority is calculated correctly.
2223TEST_F(PortTest, TestConnectionPriority) {
2224 rtc::scoped_ptr<TestPort> lport(
2225 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2226 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2227 rtc::scoped_ptr<TestPort> rport(
2228 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2229 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2230 lport->set_component(123);
2231 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2232 rport->set_component(23);
2233 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2234
2235 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2236 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2237
2238 // RFC 5245
2239 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2240 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2241 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2242 Connection* lconn = lport->CreateConnection(
2243 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2244#if defined(WEBRTC_WIN)
2245 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2246#else
2247 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2248#endif
2249
2250 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2251 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2252 Connection* rconn = rport->CreateConnection(
2253 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2254#if defined(WEBRTC_WIN)
2255 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2256#else
2257 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2258#endif
2259}
2260
2261TEST_F(PortTest, TestWritableState) {
2262 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002263 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002264 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002265 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002266
2267 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002268 TestChannel ch1(port1);
2269 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002270
2271 // Acquire addresses.
2272 ch1.Start();
2273 ch2.Start();
2274 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2275 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2276
2277 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002278 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002279 ASSERT_TRUE(ch1.conn() != NULL);
2280 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2281 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2282 ch1.Ping();
2283 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2284
2285 // Data should be unsendable until the connection is accepted.
2286 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002287 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002288 rtc::PacketOptions options;
2289 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2290
2291 // Accept the connection to return the binding response, transition to
2292 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002293 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002294 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2295 kTimeout);
2296 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2297
2298 // Ask the connection to update state as if enough time has passed to lose
2299 // full writability and 5 pings went unresponded to. We'll accomplish the
2300 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002301 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002302 ch1.Ping(i);
2303 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002304 uint32_t unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002305 ch1.conn()->UpdateState(unreliable_timeout_delay);
2306 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2307
2308 // Data should be able to be sent in this state.
2309 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2310
2311 // And now allow the other side to process the pings and send binding
2312 // responses.
2313 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2314 kTimeout);
2315
2316 // Wait long enough for a full timeout (past however long we've already
2317 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002318 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002319 ch1.Ping(unreliable_timeout_delay + i);
2320 }
2321 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2322 500u);
2323 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2324
2325 // Now that the connection has completely timed out, data send should fail.
2326 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2327
2328 ch1.Stop();
2329 ch2.Stop();
2330}
2331
2332TEST_F(PortTest, TestTimeoutForNeverWritable) {
2333 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002334 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002335 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002336 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002337
2338 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002339 TestChannel ch1(port1);
2340 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002341
2342 // Acquire addresses.
2343 ch1.Start();
2344 ch2.Start();
2345
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002346 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002347 ASSERT_TRUE(ch1.conn() != NULL);
2348 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2349
2350 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002351 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002352 ch1.Ping(i);
2353 }
2354 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2355 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2356}
2357
2358// This test verifies the connection setup between ICEMODE_FULL
2359// and ICEMODE_LITE.
2360// In this test |ch1| behaves like FULL mode client and we have created
2361// port which responds to the ping message just like LITE client.
2362TEST_F(PortTest, TestIceLiteConnectivity) {
2363 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002364 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002365 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2366
2367 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002368 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002369 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2370 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002371 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002372 ch1.SetIceMode(ICEMODE_FULL);
2373
2374 // Start gathering candidates.
2375 ch1.Start();
2376 ice_lite_port->PrepareAddress();
2377
2378 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2379 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2380
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002381 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002382 ASSERT_TRUE(ch1.conn() != NULL);
2383 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2384
2385 // Send ping from full mode client.
2386 // This ping must not have USE_CANDIDATE_ATTR.
2387 ch1.Ping();
2388
2389 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2390 // from port.
2391 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2392 IceMessage* msg = ice_full_port->last_stun_msg();
2393 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2394
2395 // Respond with a BINDING-RESPONSE from litemode client.
2396 // NOTE: Ideally we should't create connection at this stage from lite
2397 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2398 // But we need a connection to send a response message.
2399 ice_lite_port->CreateConnection(
2400 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2401 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2402 ice_lite_port->SendBindingResponse(
2403 request.get(), ice_full_port->Candidates()[0].address());
2404
2405 // Feeding the respone message from litemode to the full mode connection.
2406 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2407 ice_lite_port->last_stun_buf()->Length(),
2408 rtc::PacketTime());
2409 // Verifying full mode connection becomes writable from the response.
2410 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2411 kTimeout);
2412 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2413
2414 // Clear existing stun messsages. Otherwise we will process old stun
2415 // message right after we send ping.
2416 ice_full_port->Reset();
2417 // Send ping. This must have USE_CANDIDATE_ATTR.
2418 ch1.Ping();
2419 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2420 msg = ice_full_port->last_stun_msg();
2421 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2422 ch1.Stop();
2423}
2424
2425// This test case verifies that the CONTROLLING port does not time out.
2426TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002427 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2428 ConnectToSignalDestroyed(port1);
2429 port1->set_timeout_delay(10); // milliseconds
2430 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2431 port1->SetIceTiebreaker(kTiebreaker1);
2432
2433 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2434 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2435 port2->SetIceTiebreaker(kTiebreaker2);
2436
2437 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002438 TestChannel ch1(port1);
2439 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002440
2441 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002442 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002443
2444 // After the connection is destroyed, the port should not be destroyed.
2445 rtc::Thread::Current()->ProcessMessages(kTimeout);
2446 EXPECT_FALSE(destroyed());
2447}
2448
2449// This test case verifies that the CONTROLLED port does time out, but only
2450// after connectivity is lost.
2451TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002452 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2453 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2454 port1->SetIceTiebreaker(kTiebreaker1);
2455
2456 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2457 ConnectToSignalDestroyed(port2);
2458 port2->set_timeout_delay(10); // milliseconds
2459 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2460 port2->SetIceTiebreaker(kTiebreaker2);
2461
2462 // The connection must not be destroyed before a connection is attempted.
2463 EXPECT_FALSE(destroyed());
2464
2465 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2466 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2467
2468 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002469 TestChannel ch1(port1);
2470 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002471
2472 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002473 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002474
2475 // The controlled port should be destroyed after 10 milliseconds.
2476 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2477}
honghaizd0b31432015-09-30 12:42:17 -07002478
2479// This test case verifies that if the role of a port changes from controlled
2480// to controlling after all connections fail, the port will not be destroyed.
2481TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2482 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2483 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2484 port1->SetIceTiebreaker(kTiebreaker1);
2485
2486 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2487 ConnectToSignalDestroyed(port2);
2488 port2->set_timeout_delay(10); // milliseconds
2489 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2490 port2->SetIceTiebreaker(kTiebreaker2);
2491
2492 // The connection must not be destroyed before a connection is attempted.
2493 EXPECT_FALSE(destroyed());
2494
2495 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2496 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2497
2498 // Set up channels and ensure both ports will be deleted.
2499 TestChannel ch1(port1);
2500 TestChannel ch2(port2);
2501
2502 // Simulate a connection that succeeds, and then is destroyed.
2503 StartConnectAndStopChannels(&ch1, &ch2);
2504 // Switch the role after all connections are destroyed.
2505 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2506 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2507 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2508
2509 // After the connection is destroyed, the port should not be destroyed.
2510 rtc::Thread::Current()->ProcessMessages(kTimeout);
2511 EXPECT_FALSE(destroyed());
2512}
Honghai Zhangf9945b22015-12-15 12:20:13 -08002513
2514TEST_F(PortTest, TestSupportsProtocol) {
2515 rtc::scoped_ptr<Port> udp_port(CreateUdpPort(kLocalAddr1));
2516 EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2517 EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2518
2519 rtc::scoped_ptr<Port> stun_port(
2520 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2521 EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2522 EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2523
2524 rtc::scoped_ptr<Port> tcp_port(CreateTcpPort(kLocalAddr1));
2525 EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2526 EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
2527 EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2528
2529 rtc::scoped_ptr<Port> turn_port(
2530 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2531 EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2532 EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2533}