blob: 34806d9a79e0b8e8cc36118cde518bd1989a6eda [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:
207 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
208 rtc::scoped_ptr<IceMessage> last_stun_msg_;
pbos7640ffa2015-11-30 09:16:59 -0800209 int type_preference_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210};
211
212class TestChannel : public sigslot::has_slots<> {
213 public:
214 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700215 TestChannel(Port* p1)
216 : ice_mode_(ICEMODE_FULL),
217 port_(p1),
218 complete_count_(0),
219 conn_(NULL),
220 remote_request_(),
221 nominated_(false) {
222 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
223 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
224 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000225 }
226
227 int complete_count() { return complete_count_; }
228 Connection* conn() { return conn_; }
229 const SocketAddress& remote_address() { return remote_address_; }
230 const std::string remote_fragment() { return remote_frag_; }
231
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700232 void Start() { port_->PrepareAddress(); }
233 void CreateConnection(const Candidate& remote_candidate) {
234 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235 IceMode remote_ice_mode =
236 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
237 conn_->set_remote_ice_mode(remote_ice_mode);
238 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
239 conn_->SignalStateChange.connect(
240 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700241 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700242 conn_->SignalReadyToSend.connect(this,
243 &TestChannel::OnConnectionReadyToSend);
244 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000245 }
246 void OnConnectionStateChange(Connection* conn) {
247 if (conn->write_state() == Connection::STATE_WRITABLE) {
248 conn->set_use_candidate_attr(true);
249 nominated_ = true;
250 }
251 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700252 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700254 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700256 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700257 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700258 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259 remote_request_.reset();
260 }
261 void Ping() {
262 Ping(0);
263 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200264 void Ping(uint32_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700266 if (conn_) {
267 conn_->Destroy();
268 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 }
270
271 void OnPortComplete(Port* port) {
272 complete_count_++;
273 }
274 void SetIceMode(IceMode ice_mode) {
275 ice_mode_ = ice_mode;
276 }
277
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700278 int SendData(const char* data, size_t len) {
279 rtc::PacketOptions options;
280 return conn_->Send(data, len, options);
281 }
282
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
284 ProtocolType proto,
285 IceMessage* msg, const std::string& rf,
286 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700287 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 if (!remote_address_.IsNil()) {
289 ASSERT_EQ(remote_address_, addr);
290 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 const cricket::StunUInt32Attribute* priority_attr =
292 msg->GetUInt32(STUN_ATTR_PRIORITY);
293 const cricket::StunByteStringAttribute* mi_attr =
294 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
295 const cricket::StunUInt32Attribute* fingerprint_attr =
296 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700297 EXPECT_TRUE(priority_attr != NULL);
298 EXPECT_TRUE(mi_attr != NULL);
299 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000300 remote_address_ = addr;
301 remote_request_.reset(CopyStunMessage(msg));
302 remote_frag_ = rf;
303 }
304
305 void OnDestroyed(Connection* conn) {
306 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700307 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700309 // When the connection is destroyed, also clear these fields so future
310 // connections are possible.
311 remote_request_.reset();
312 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 }
314
315 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700316 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000317 ASSERT_EQ(destroyed_src, port);
318 }
319
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700320 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700321
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322 bool nominated() const { return nominated_; }
323
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700324 void set_connection_ready_to_send(bool ready) {
325 connection_ready_to_send_ = ready;
326 }
327 bool connection_ready_to_send() const {
328 return connection_ready_to_send_;
329 }
330
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700332 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
333 void OnConnectionReadyToSend(Connection* conn) {
334 ASSERT_EQ(conn, conn_);
335 connection_ready_to_send_ = true;
336 }
337
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000338 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700339 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340
341 int complete_count_;
342 Connection* conn_;
343 SocketAddress remote_address_;
344 rtc::scoped_ptr<StunMessage> remote_request_;
345 std::string remote_frag_;
346 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700347 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348};
349
350class PortTest : public testing::Test, public sigslot::has_slots<> {
351 public:
352 PortTest()
353 : main_(rtc::Thread::Current()),
354 pss_(new rtc::PhysicalSocketServer),
355 ss_(new rtc::VirtualSocketServer(pss_.get())),
356 ss_scope_(ss_.get()),
357 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
358 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700359 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
360 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 nat_socket_factory1_(&nat_factory1_),
362 nat_socket_factory2_(&nat_factory2_),
363 stun_server_(TestStunServer::Create(main_, kStunAddr)),
364 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700365 relay_server_(main_,
366 kRelayUdpIntAddr,
367 kRelayUdpExtAddr,
368 kRelayTcpIntAddr,
369 kRelayTcpExtAddr,
370 kRelaySslTcpIntAddr,
371 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
373 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000374 role_conflict_(false),
375 destroyed_(false) {
376 network_.AddIP(rtc::IPAddress(INADDR_ANY));
377 }
378
379 protected:
380 void TestLocalToLocal() {
381 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700382 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000383 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700384 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000385 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
386 }
387 void TestLocalToStun(NATType ntype) {
388 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700389 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
391 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700392 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000393 TestConnectivity("udp", port1, StunName(ntype), port2,
394 ntype == NAT_OPEN_CONE, true,
395 ntype != NAT_SYMMETRIC, true);
396 }
397 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
398 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700399 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000400 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700401 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
403 rtype == RELAY_GTURN, true, true, true);
404 }
405 void TestStunToLocal(NATType ntype) {
406 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
407 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700408 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700410 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000411 TestConnectivity(StunName(ntype), port1, "udp", port2,
412 true, ntype != NAT_SYMMETRIC, true, true);
413 }
414 void TestStunToStun(NATType ntype1, NATType ntype2) {
415 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
416 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700417 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
419 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700420 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000421 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
422 ntype2 == NAT_OPEN_CONE,
423 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
424 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
425 }
426 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
427 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
428 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700429 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700431 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000432 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
433 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
434 }
435 void TestTcpToTcp() {
436 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700437 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700439 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
441 }
442 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
443 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700444 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700446 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000447 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
448 rtype == RELAY_GTURN, false, true, true);
449 }
450 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
451 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700452 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700454 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
456 rtype == RELAY_GTURN, false, true, true);
457 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 // helpers for above functions
459 UDPPort* CreateUdpPort(const SocketAddress& addr) {
460 return CreateUdpPort(addr, &socket_factory_);
461 }
462 UDPPort* CreateUdpPort(const SocketAddress& addr,
463 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800464 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
465 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 }
467 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700468 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469 }
470 TCPPort* CreateTcpPort(const SocketAddress& addr,
471 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700472 return TCPPort::Create(main_, socket_factory, &network_,
473 addr.ipaddr(), 0, 0, username_, password_,
474 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475 }
476 StunPort* CreateStunPort(const SocketAddress& addr,
477 rtc::PacketSocketFactory* factory) {
478 ServerAddresses stun_servers;
479 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700480 return StunPort::Create(main_, factory, &network_,
481 addr.ipaddr(), 0, 0,
482 username_, password_, stun_servers,
483 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484 }
485 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
486 ProtocolType int_proto, ProtocolType ext_proto) {
487 if (rtype == RELAY_TURN) {
488 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
489 } else {
490 return CreateGturnPort(addr, int_proto, ext_proto);
491 }
492 }
493 TurnPort* CreateTurnPort(const SocketAddress& addr,
494 PacketSocketFactory* socket_factory,
495 ProtocolType int_proto, ProtocolType ext_proto) {
496 return CreateTurnPort(addr, socket_factory,
497 int_proto, ext_proto, kTurnUdpIntAddr);
498 }
499 TurnPort* CreateTurnPort(const SocketAddress& addr,
500 PacketSocketFactory* socket_factory,
501 ProtocolType int_proto, ProtocolType ext_proto,
502 const rtc::SocketAddress& server_addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700503 return TurnPort::Create(main_, socket_factory, &network_,
504 addr.ipaddr(), 0, 0,
505 username_, password_, ProtocolAddress(
506 server_addr, PROTO_UDP),
507 kRelayCredentials, 0,
508 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 }
510 RelayPort* CreateGturnPort(const SocketAddress& addr,
511 ProtocolType int_proto, ProtocolType ext_proto) {
512 RelayPort* port = CreateGturnPort(addr);
513 SocketAddress addrs[] =
514 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
515 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
516 return port;
517 }
518 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700519 // TODO(pthatcher): Remove GTURN.
520 return RelayPort::Create(main_, &socket_factory_, &network_,
521 addr.ipaddr(), 0, 0,
522 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000523 // TODO: Add an external address for ext_proto, so that the
524 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000525 }
526 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
527 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700528 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000529 }
530 static const char* StunName(NATType type) {
531 switch (type) {
532 case NAT_OPEN_CONE: return "stun(open cone)";
533 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
534 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
535 case NAT_SYMMETRIC: return "stun(symmetric)";
536 default: return "stun(?)";
537 }
538 }
539 static const char* RelayName(RelayType type, ProtocolType proto) {
540 if (type == RELAY_TURN) {
541 switch (proto) {
542 case PROTO_UDP: return "turn(udp)";
543 case PROTO_TCP: return "turn(tcp)";
544 case PROTO_SSLTCP: return "turn(ssltcp)";
545 default: return "turn(?)";
546 }
547 } else {
548 switch (proto) {
549 case PROTO_UDP: return "gturn(udp)";
550 case PROTO_TCP: return "gturn(tcp)";
551 case PROTO_SSLTCP: return "gturn(ssltcp)";
552 default: return "gturn(?)";
553 }
554 }
555 }
556
557 void TestCrossFamilyPorts(int type);
558
Peter Thatcherb8b01432015-07-07 16:45:53 -0700559 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
560
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000561 // This does all the work and then deletes |port1| and |port2|.
562 void TestConnectivity(const char* name1, Port* port1,
563 const char* name2, Port* port2,
564 bool accept, bool same_addr1,
565 bool same_addr2, bool possible);
566
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700567 // This connects the provided channels which have already started. |ch1|
568 // should have its Connection created (either through CreateConnection() or
569 // TCP reconnecting mechanism before entering this function.
570 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
571 ASSERT_TRUE(ch1->conn());
572 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
573 ch1->Ping();
574 WAIT(!ch2->remote_address().IsNil(), kTimeout);
575
576 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700577 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700578 ch2->Ping();
579 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
580 kTimeout);
581 }
582
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583 // This connects and disconnects the provided channels in the same sequence as
584 // TestConnectivity with all options set to |true|. It does not delete either
585 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700586 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
587 // Acquire addresses.
588 ch1->Start();
589 ch2->Start();
590
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700591 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700592 ConnectStartedChannels(ch1, ch2);
593
594 // Destroy the connections.
595 ch1->Stop();
596 ch2->Stop();
597 }
598
599 // This disconnects both end's Connection and make sure ch2 ready for new
600 // connection.
601 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700602 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
603 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
604 ASSERT_TRUE(
605 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
606 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700607
608 // Wait for both OnClose are delivered.
609 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
610 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
611
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700612 // Ensure redundant SignalClose events on TcpConnection won't break tcp
613 // reconnection. Chromium will fire SignalClose for all outstanding IPC
614 // packets during reconnection.
615 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
616 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
617
618 // Speed up destroying ch2's connection such that the test is ready to
619 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700620 ch2->conn()->Destroy();
621 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
622 }
623
624 void TestTcpReconnect(bool ping_after_disconnected,
625 bool send_after_disconnected) {
626 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700627 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700628 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700629 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700630
631 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
632 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
633
634 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700635 TestChannel ch1(port1);
636 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700637 EXPECT_EQ(0, ch1.complete_count());
638 EXPECT_EQ(0, ch2.complete_count());
639
640 ch1.Start();
641 ch2.Start();
642 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
643 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
644
645 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700646 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700647 ConnectStartedChannels(&ch1, &ch2);
648
649 // Shorten the timeout period.
650 const int kTcpReconnectTimeout = kTimeout;
651 static_cast<TCPConnection*>(ch1.conn())
652 ->set_reconnection_timeout(kTcpReconnectTimeout);
653 static_cast<TCPConnection*>(ch2.conn())
654 ->set_reconnection_timeout(kTcpReconnectTimeout);
655
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700656 EXPECT_FALSE(ch1.connection_ready_to_send());
657 EXPECT_FALSE(ch2.connection_ready_to_send());
658
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700659 // Once connected, disconnect them.
660 DisconnectTcpTestChannels(&ch1, &ch2);
661
662 if (send_after_disconnected || ping_after_disconnected) {
663 if (send_after_disconnected) {
664 // First SendData after disconnect should fail but will trigger
665 // reconnect.
666 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
667 }
668
669 if (ping_after_disconnected) {
670 // Ping should trigger reconnect.
671 ch1.Ping();
672 }
673
674 // Wait for channel's outgoing TCPConnection connected.
675 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
676
677 // Verify that we could still connect channels.
678 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700679 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
680 kTcpReconnectTimeout);
681 // Channel2 is the passive one so a new connection is created during
682 // reconnect. This new connection should never have issued EWOULDBLOCK
683 // hence the connection_ready_to_send() should be false.
684 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700685 } else {
686 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700687 // Since the reconnection never happens, the connections should have been
688 // destroyed after the timeout.
689 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
690 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700691 }
692
693 // Tear down and ensure that goes smoothly.
694 ch1.Stop();
695 ch2.Stop();
696 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
697 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
698 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000700 IceMessage* CreateStunMessage(int type) {
701 IceMessage* msg = new IceMessage();
702 msg->SetType(type);
703 msg->SetTransactionID("TESTTESTTEST");
704 return msg;
705 }
706 IceMessage* CreateStunMessageWithUsername(int type,
707 const std::string& username) {
708 IceMessage* msg = CreateStunMessage(type);
709 msg->AddAttribute(
710 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
711 return msg;
712 }
713 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
714 const std::string& username,
715 const std::string& password) {
716 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
717 addr.ipaddr(), 0, 0, username, password);
718 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
719 return port;
720 }
721 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
722 const std::string& username,
723 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000724 cricket::IceRole role,
725 int tiebreaker) {
726 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000727 port->SetIceRole(role);
728 port->SetIceTiebreaker(tiebreaker);
729 return port;
730 }
731
732 void OnRoleConflict(PortInterface* port) {
733 role_conflict_ = true;
734 }
735 bool role_conflict() const { return role_conflict_; }
736
737 void ConnectToSignalDestroyed(PortInterface* port) {
738 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
739 }
740
741 void OnDestroyed(PortInterface* port) {
742 destroyed_ = true;
743 }
744 bool destroyed() const { return destroyed_; }
745
746 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
747 return &nat_socket_factory1_;
748 }
749
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700750 protected:
751 rtc::VirtualSocketServer* vss() { return ss_.get(); }
752
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 private:
754 rtc::Thread* main_;
755 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
756 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
757 rtc::SocketServerScope ss_scope_;
758 rtc::Network network_;
759 rtc::BasicPacketSocketFactory socket_factory_;
760 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
761 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
762 rtc::NATSocketFactory nat_factory1_;
763 rtc::NATSocketFactory nat_factory2_;
764 rtc::BasicPacketSocketFactory nat_socket_factory1_;
765 rtc::BasicPacketSocketFactory nat_socket_factory2_;
766 scoped_ptr<TestStunServer> stun_server_;
767 TestTurnServer turn_server_;
768 TestRelayServer relay_server_;
769 std::string username_;
770 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771 bool role_conflict_;
772 bool destroyed_;
773};
774
775void PortTest::TestConnectivity(const char* name1, Port* port1,
776 const char* name2, Port* port2,
777 bool accept, bool same_addr1,
778 bool same_addr2, bool possible) {
779 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
780 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
781 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
782
783 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700784 TestChannel ch1(port1);
785 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786 EXPECT_EQ(0, ch1.complete_count());
787 EXPECT_EQ(0, ch2.complete_count());
788
789 // Acquire addresses.
790 ch1.Start();
791 ch2.Start();
792 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
793 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
794
795 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700796 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000797 ASSERT_TRUE(ch1.conn() != NULL);
798 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
799 ch1.Ping();
800 WAIT(!ch2.remote_address().IsNil(), kTimeout);
801
802 if (accept) {
803 // We are able to send a ping from src to dst. This is the case when
804 // sending to UDP ports and cone NATs.
805 EXPECT_TRUE(ch1.remote_address().IsNil());
806 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
807
808 // Ensure the ping came from the same address used for src.
809 // This is the case unless the source NAT was symmetric.
810 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
811 EXPECT_TRUE(same_addr2);
812
813 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700814 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000815 ASSERT_TRUE(ch2.conn() != NULL);
816 ch2.Ping();
817 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
818 kTimeout);
819 } else {
820 // We can't send a ping from src to dst, so flip it around. This will happen
821 // when the destination NAT is addr/port restricted or symmetric.
822 EXPECT_TRUE(ch1.remote_address().IsNil());
823 EXPECT_TRUE(ch2.remote_address().IsNil());
824
825 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700826 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827 ASSERT_TRUE(ch2.conn() != NULL);
828 ch2.Ping();
829 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
830
831 if (same_addr1 && same_addr2) {
832 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700833 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
835
836 // First connection may not be writable if the first ping did not get
837 // through. So we will have to do another.
838 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
839 ch1.Ping();
840 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
841 kTimeout);
842 }
843 } else if (!same_addr1 && possible) {
844 // The new ping went to the candidate address, but that address was bad.
845 // This will happen when the source NAT is symmetric.
846 EXPECT_TRUE(ch1.remote_address().IsNil());
847 EXPECT_TRUE(ch2.remote_address().IsNil());
848
849 // However, since we have now sent a ping to the source IP, we should be
850 // able to get a ping from it. This gives us the real source address.
851 ch1.Ping();
852 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700853 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854 EXPECT_TRUE(ch1.remote_address().IsNil());
855
856 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700857 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000858 ASSERT_TRUE(ch2.conn() != NULL);
859 ch2.Ping();
860 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
861 kTimeout);
862 } else if (!same_addr2 && possible) {
863 // The new ping came in, but from an unexpected address. This will happen
864 // when the destination NAT is symmetric.
865 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700866 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000867
868 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700869 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 ch1.Ping();
871 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
872 kTimeout);
873 } else { // (!possible)
874 // There should be s no way for the pings to reach each other. Check it.
875 EXPECT_TRUE(ch1.remote_address().IsNil());
876 EXPECT_TRUE(ch2.remote_address().IsNil());
877 ch1.Ping();
878 WAIT(!ch2.remote_address().IsNil(), kTimeout);
879 EXPECT_TRUE(ch1.remote_address().IsNil());
880 EXPECT_TRUE(ch2.remote_address().IsNil());
881 }
882 }
883
884 // Everything should be good, unless we know the situation is impossible.
885 ASSERT_TRUE(ch1.conn() != NULL);
886 ASSERT_TRUE(ch2.conn() != NULL);
887 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700888 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700890 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
892 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700893 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000894 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700895 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000896 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
897 }
898
899 // Tear down and ensure that goes smoothly.
900 ch1.Stop();
901 ch2.Stop();
902 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
903 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
904}
905
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906class FakePacketSocketFactory : public rtc::PacketSocketFactory {
907 public:
908 FakePacketSocketFactory()
909 : next_udp_socket_(NULL),
910 next_server_tcp_socket_(NULL),
911 next_client_tcp_socket_(NULL) {
912 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000913 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000915 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200916 uint16_t min_port,
917 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 EXPECT_TRUE(next_udp_socket_ != NULL);
919 AsyncPacketSocket* result = next_udp_socket_;
920 next_udp_socket_ = NULL;
921 return result;
922 }
923
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000924 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200925 uint16_t min_port,
926 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000927 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000928 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
929 AsyncPacketSocket* result = next_server_tcp_socket_;
930 next_server_tcp_socket_ = NULL;
931 return result;
932 }
933
934 // TODO: |proxy_info| and |user_agent| should be set
935 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000936 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
937 const SocketAddress& remote_address,
938 const rtc::ProxyInfo& proxy_info,
939 const std::string& user_agent,
940 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
942 AsyncPacketSocket* result = next_client_tcp_socket_;
943 next_client_tcp_socket_ = NULL;
944 return result;
945 }
946
947 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
948 next_udp_socket_ = next_udp_socket;
949 }
950 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
951 next_server_tcp_socket_ = next_server_tcp_socket;
952 }
953 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
954 next_client_tcp_socket_ = next_client_tcp_socket;
955 }
956 rtc::AsyncResolverInterface* CreateAsyncResolver() {
957 return NULL;
958 }
959
960 private:
961 AsyncPacketSocket* next_udp_socket_;
962 AsyncPacketSocket* next_server_tcp_socket_;
963 AsyncPacketSocket* next_client_tcp_socket_;
964};
965
966class FakeAsyncPacketSocket : public AsyncPacketSocket {
967 public:
968 // Returns current local address. Address may be set to NULL if the
969 // socket is not bound yet (GetState() returns STATE_BINDING).
970 virtual SocketAddress GetLocalAddress() const {
971 return SocketAddress();
972 }
973
974 // Returns remote address. Returns zeroes if this is not a client TCP socket.
975 virtual SocketAddress GetRemoteAddress() const {
976 return SocketAddress();
977 }
978
979 // Send a packet.
980 virtual int Send(const void *pv, size_t cb,
981 const rtc::PacketOptions& options) {
982 return static_cast<int>(cb);
983 }
984 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
985 const rtc::PacketOptions& options) {
986 return static_cast<int>(cb);
987 }
988 virtual int Close() {
989 return 0;
990 }
991
992 virtual State GetState() const { return state_; }
993 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
994 virtual int SetOption(Socket::Option opt, int value) { return 0; }
995 virtual int GetError() const { return 0; }
996 virtual void SetError(int error) { }
997
998 void set_state(State state) { state_ = state; }
999
1000 private:
1001 State state_;
1002};
1003
1004// Local -> XXXX
1005TEST_F(PortTest, TestLocalToLocal) {
1006 TestLocalToLocal();
1007}
1008
1009TEST_F(PortTest, TestLocalToConeNat) {
1010 TestLocalToStun(NAT_OPEN_CONE);
1011}
1012
1013TEST_F(PortTest, TestLocalToARNat) {
1014 TestLocalToStun(NAT_ADDR_RESTRICTED);
1015}
1016
1017TEST_F(PortTest, TestLocalToPRNat) {
1018 TestLocalToStun(NAT_PORT_RESTRICTED);
1019}
1020
1021TEST_F(PortTest, TestLocalToSymNat) {
1022 TestLocalToStun(NAT_SYMMETRIC);
1023}
1024
1025// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1026TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1027 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1028}
1029
1030TEST_F(PortTest, TestLocalToGturn) {
1031 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1032}
1033
1034TEST_F(PortTest, TestLocalToTcpGturn) {
1035 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1036}
1037
1038TEST_F(PortTest, TestLocalToSslTcpGturn) {
1039 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1040}
1041
1042// Cone NAT -> XXXX
1043TEST_F(PortTest, TestConeNatToLocal) {
1044 TestStunToLocal(NAT_OPEN_CONE);
1045}
1046
1047TEST_F(PortTest, TestConeNatToConeNat) {
1048 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1049}
1050
1051TEST_F(PortTest, TestConeNatToARNat) {
1052 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1053}
1054
1055TEST_F(PortTest, TestConeNatToPRNat) {
1056 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1057}
1058
1059TEST_F(PortTest, TestConeNatToSymNat) {
1060 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1061}
1062
1063TEST_F(PortTest, TestConeNatToTurn) {
1064 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1065}
1066
1067TEST_F(PortTest, TestConeNatToGturn) {
1068 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1069}
1070
1071TEST_F(PortTest, TestConeNatToTcpGturn) {
1072 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1073}
1074
1075// Address-restricted NAT -> XXXX
1076TEST_F(PortTest, TestARNatToLocal) {
1077 TestStunToLocal(NAT_ADDR_RESTRICTED);
1078}
1079
1080TEST_F(PortTest, TestARNatToConeNat) {
1081 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1082}
1083
1084TEST_F(PortTest, TestARNatToARNat) {
1085 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1086}
1087
1088TEST_F(PortTest, TestARNatToPRNat) {
1089 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1090}
1091
1092TEST_F(PortTest, TestARNatToSymNat) {
1093 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1094}
1095
1096TEST_F(PortTest, TestARNatToTurn) {
1097 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1098}
1099
1100TEST_F(PortTest, TestARNatToGturn) {
1101 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1102}
1103
1104TEST_F(PortTest, TestARNATNatToTcpGturn) {
1105 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1106}
1107
1108// Port-restricted NAT -> XXXX
1109TEST_F(PortTest, TestPRNatToLocal) {
1110 TestStunToLocal(NAT_PORT_RESTRICTED);
1111}
1112
1113TEST_F(PortTest, TestPRNatToConeNat) {
1114 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1115}
1116
1117TEST_F(PortTest, TestPRNatToARNat) {
1118 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1119}
1120
1121TEST_F(PortTest, TestPRNatToPRNat) {
1122 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1123}
1124
1125TEST_F(PortTest, TestPRNatToSymNat) {
1126 // Will "fail"
1127 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1128}
1129
1130TEST_F(PortTest, TestPRNatToTurn) {
1131 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1132}
1133
1134TEST_F(PortTest, TestPRNatToGturn) {
1135 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1136}
1137
1138TEST_F(PortTest, TestPRNatToTcpGturn) {
1139 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1140}
1141
1142// Symmetric NAT -> XXXX
1143TEST_F(PortTest, TestSymNatToLocal) {
1144 TestStunToLocal(NAT_SYMMETRIC);
1145}
1146
1147TEST_F(PortTest, TestSymNatToConeNat) {
1148 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1149}
1150
1151TEST_F(PortTest, TestSymNatToARNat) {
1152 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1153}
1154
1155TEST_F(PortTest, TestSymNatToPRNat) {
1156 // Will "fail"
1157 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1158}
1159
1160TEST_F(PortTest, TestSymNatToSymNat) {
1161 // Will "fail"
1162 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1163}
1164
1165TEST_F(PortTest, TestSymNatToTurn) {
1166 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1167}
1168
1169TEST_F(PortTest, TestSymNatToGturn) {
1170 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1171}
1172
1173TEST_F(PortTest, TestSymNatToTcpGturn) {
1174 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1175}
1176
1177// Outbound TCP -> XXXX
1178TEST_F(PortTest, TestTcpToTcp) {
1179 TestTcpToTcp();
1180}
1181
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001182TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1183 TestTcpReconnect(false /* ping */, true /* send */);
1184}
1185
1186TEST_F(PortTest, TestTcpReconnectOnPing) {
1187 TestTcpReconnect(true /* ping */, false /* send */);
1188}
1189
1190TEST_F(PortTest, TestTcpReconnectTimeout) {
1191 TestTcpReconnect(false /* ping */, false /* send */);
1192}
1193
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001194// Test when TcpConnection never connects, the OnClose() will be called to
1195// destroy the connection.
1196TEST_F(PortTest, TestTcpNeverConnect) {
1197 Port* port1 = CreateTcpPort(kLocalAddr1);
1198 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1199 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1200
1201 // Set up a channel and ensure the port will be deleted.
1202 TestChannel ch1(port1);
1203 EXPECT_EQ(0, ch1.complete_count());
1204
1205 ch1.Start();
1206 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1207
1208 rtc::scoped_ptr<rtc::AsyncSocket> server(
1209 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1210 // Bind but not listen.
1211 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1212
1213 Candidate c = GetCandidate(port1);
1214 c.set_address(server->GetLocalAddress());
1215
1216 ch1.CreateConnection(c);
1217 EXPECT_TRUE(ch1.conn());
1218 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1219}
1220
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221/* TODO: Enable these once testrelayserver can accept external TCP.
1222TEST_F(PortTest, TestTcpToTcpRelay) {
1223 TestTcpToRelay(PROTO_TCP);
1224}
1225
1226TEST_F(PortTest, TestTcpToSslTcpRelay) {
1227 TestTcpToRelay(PROTO_SSLTCP);
1228}
1229*/
1230
1231// Outbound SSLTCP -> XXXX
1232/* TODO: Enable these once testrelayserver can accept external SSL.
1233TEST_F(PortTest, TestSslTcpToTcpRelay) {
1234 TestSslTcpToRelay(PROTO_TCP);
1235}
1236
1237TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1238 TestSslTcpToRelay(PROTO_SSLTCP);
1239}
1240*/
1241
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001242// Test that a connection will be dead and deleted if
1243// i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1244// since it was created, or
1245// ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1246// milliseconds since last receiving.
1247TEST_F(PortTest, TestConnectionDead) {
1248 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1249 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1250 TestChannel ch1(port1);
1251 TestChannel ch2(port2);
1252 // Acquire address.
1253 ch1.Start();
1254 ch2.Start();
1255 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1256 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
1257
honghaiz37389b42016-01-04 21:57:33 -08001258 // Test case that the connection has never received anything.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001259 uint32_t before_created = rtc::Time();
1260 ch1.CreateConnection(GetCandidate(port2));
1261 uint32_t after_created = rtc::Time();
1262 Connection* conn = ch1.conn();
1263 ASSERT(conn != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001264 // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned.
1265 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1266 rtc::Thread::Current()->ProcessMessages(0);
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001267 EXPECT_TRUE(ch1.conn() != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001268 // It is not dead if it is before MIN_CONNECTION_LIFETIME and pruned.
1269 conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1270 conn->Prune();
1271 rtc::Thread::Current()->ProcessMessages(0);
1272 EXPECT_TRUE(ch1.conn() != nullptr);
1273 // It will be dead after MIN_CONNECTION_LIFETIME and pruned.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001274 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1275 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1276
honghaiz37389b42016-01-04 21:57:33 -08001277 // Test case that the connection has received something.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001278 // Create a connection again and receive a ping.
1279 ch1.CreateConnection(GetCandidate(port2));
1280 conn = ch1.conn();
1281 ASSERT(conn != nullptr);
1282 uint32_t before_last_receiving = rtc::Time();
1283 conn->ReceivedPing();
1284 uint32_t after_last_receiving = rtc::Time();
1285 // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1286 conn->UpdateState(
1287 before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1288 rtc::Thread::Current()->ProcessMessages(100);
1289 EXPECT_TRUE(ch1.conn() != nullptr);
1290 conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1291 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1292}
1293
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001294// This test case verifies standard ICE features in STUN messages. Currently it
1295// verifies Message Integrity attribute in STUN messages and username in STUN
1296// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001297TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001298 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1299 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1300 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001301 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1302 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1303 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001304 // Same parameters as TestLocalToLocal above.
1305 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1306}
1307
1308// This test is trying to validate a successful and failure scenario in a
1309// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1310// should remain equal to the request generated by the port and role of port
1311// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001312TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313 rtc::scoped_ptr<TestPort> lport(
1314 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001315 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1316 lport->SetIceTiebreaker(kTiebreaker1);
1317 lport->PrepareAddress();
1318 ASSERT_FALSE(lport->Candidates().empty());
1319 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1320 Port::ORIGIN_MESSAGE);
1321 conn->Ping(0);
1322
1323 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1324 IceMessage* msg = lport->last_stun_msg();
1325 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1326 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1327 lport->last_stun_buf()->Length(),
1328 rtc::PacketTime());
1329 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1330 msg = lport->last_stun_msg();
1331 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1332
1333 // If the tiebreaker value is different from port, we expect a error
1334 // response.
1335 lport->Reset();
1336 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001337 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001338 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1339 Port::ORIGIN_MESSAGE);
1340 conn1->Ping(0);
1341
1342 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1343 msg = lport->last_stun_msg();
1344 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1345 rtc::scoped_ptr<IceMessage> modified_req(
1346 CreateStunMessage(STUN_BINDING_REQUEST));
1347 const StunByteStringAttribute* username_attr = msg->GetByteString(
1348 STUN_ATTR_USERNAME);
1349 modified_req->AddAttribute(new StunByteStringAttribute(
1350 STUN_ATTR_USERNAME, username_attr->GetString()));
1351 // To make sure we receive error response, adding tiebreaker less than
1352 // what's present in request.
1353 modified_req->AddAttribute(new StunUInt64Attribute(
1354 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1355 modified_req->AddMessageIntegrity("lpass");
1356 modified_req->AddFingerprint();
1357
1358 lport->Reset();
1359 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1360 WriteStunMessage(modified_req.get(), buf.get());
1361 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1362 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1363 msg = lport->last_stun_msg();
1364 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1365}
1366
1367// This test verifies role conflict signal is received when there is
1368// conflict in the role. In this case both ports are in controlling and
1369// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1370// value of tiebreaker, when it receives ping request from |rport| it will
1371// send role conflict signal.
1372TEST_F(PortTest, TestIceRoleConflict) {
1373 rtc::scoped_ptr<TestPort> lport(
1374 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001375 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1376 lport->SetIceTiebreaker(kTiebreaker1);
1377 rtc::scoped_ptr<TestPort> rport(
1378 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1380 rport->SetIceTiebreaker(kTiebreaker2);
1381
1382 lport->PrepareAddress();
1383 rport->PrepareAddress();
1384 ASSERT_FALSE(lport->Candidates().empty());
1385 ASSERT_FALSE(rport->Candidates().empty());
1386 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1387 Port::ORIGIN_MESSAGE);
1388 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1389 Port::ORIGIN_MESSAGE);
1390 rconn->Ping(0);
1391
1392 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1393 IceMessage* msg = rport->last_stun_msg();
1394 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1395 // Send rport binding request to lport.
1396 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1397 rport->last_stun_buf()->Length(),
1398 rtc::PacketTime());
1399
1400 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1401 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1402 EXPECT_TRUE(role_conflict());
1403}
1404
1405TEST_F(PortTest, TestTcpNoDelay) {
1406 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001407 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001408 int option_value = -1;
1409 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1410 &option_value);
1411 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1412 ASSERT_EQ(1, option_value);
1413 delete port1;
1414}
1415
1416TEST_F(PortTest, TestDelayedBindingUdp) {
1417 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1418 FakePacketSocketFactory socket_factory;
1419
1420 socket_factory.set_next_udp_socket(socket);
1421 scoped_ptr<UDPPort> port(
1422 CreateUdpPort(kLocalAddr1, &socket_factory));
1423
1424 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1425 port->PrepareAddress();
1426
1427 EXPECT_EQ(0U, port->Candidates().size());
1428 socket->SignalAddressReady(socket, kLocalAddr2);
1429
1430 EXPECT_EQ(1U, port->Candidates().size());
1431}
1432
1433TEST_F(PortTest, TestDelayedBindingTcp) {
1434 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1435 FakePacketSocketFactory socket_factory;
1436
1437 socket_factory.set_next_server_tcp_socket(socket);
1438 scoped_ptr<TCPPort> port(
1439 CreateTcpPort(kLocalAddr1, &socket_factory));
1440
1441 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1442 port->PrepareAddress();
1443
1444 EXPECT_EQ(0U, port->Candidates().size());
1445 socket->SignalAddressReady(socket, kLocalAddr2);
1446
1447 EXPECT_EQ(1U, port->Candidates().size());
1448}
1449
1450void PortTest::TestCrossFamilyPorts(int type) {
1451 FakePacketSocketFactory factory;
1452 scoped_ptr<Port> ports[4];
1453 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1454 SocketAddress("192.168.1.4", 0),
1455 SocketAddress("2001:db8::1", 0),
1456 SocketAddress("2001:db8::2", 0)};
1457 for (int i = 0; i < 4; i++) {
1458 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1459 if (type == SOCK_DGRAM) {
1460 factory.set_next_udp_socket(socket);
1461 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1462 } else if (type == SOCK_STREAM) {
1463 factory.set_next_server_tcp_socket(socket);
1464 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1465 }
1466 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1467 socket->SignalAddressReady(socket, addresses[i]);
1468 ports[i]->PrepareAddress();
1469 }
1470
1471 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1472 if (type == SOCK_STREAM) {
1473 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1474 factory.set_next_client_tcp_socket(clientsocket);
1475 }
1476 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1477 Port::ORIGIN_MESSAGE);
1478 EXPECT_TRUE(NULL == c);
1479 EXPECT_EQ(0U, ports[0]->connections().size());
1480 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1481 Port::ORIGIN_MESSAGE);
1482 EXPECT_FALSE(NULL == c);
1483 EXPECT_EQ(1U, ports[0]->connections().size());
1484
1485 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1486 if (type == SOCK_STREAM) {
1487 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1488 factory.set_next_client_tcp_socket(clientsocket);
1489 }
1490 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1491 Port::ORIGIN_MESSAGE);
1492 EXPECT_TRUE(NULL == c);
1493 EXPECT_EQ(0U, ports[2]->connections().size());
1494 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1495 Port::ORIGIN_MESSAGE);
1496 EXPECT_FALSE(NULL == c);
1497 EXPECT_EQ(1U, ports[2]->connections().size());
1498}
1499
1500TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1501 TestCrossFamilyPorts(SOCK_STREAM);
1502}
1503
1504TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1505 TestCrossFamilyPorts(SOCK_DGRAM);
1506}
1507
Peter Thatcherb8b01432015-07-07 16:45:53 -07001508void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1509 Connection* c = p1->CreateConnection(GetCandidate(p2),
1510 Port::ORIGIN_MESSAGE);
1511 if (can_connect) {
1512 EXPECT_FALSE(NULL == c);
1513 EXPECT_EQ(1U, p1->connections().size());
1514 } else {
1515 EXPECT_TRUE(NULL == c);
1516 EXPECT_EQ(0U, p1->connections().size());
1517 }
1518}
1519
1520TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1521 FakePacketSocketFactory factory;
1522 scoped_ptr<Port> ports[4];
1523 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1524 SocketAddress("fe80::1", 0),
1525 SocketAddress("fe80::2", 0),
1526 SocketAddress("::1", 0)};
1527 for (int i = 0; i < 4; i++) {
1528 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1529 factory.set_next_udp_socket(socket);
1530 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1531 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1532 socket->SignalAddressReady(socket, addresses[i]);
1533 ports[i]->PrepareAddress();
1534 }
1535
1536 Port* standard = ports[0].get();
1537 Port* link_local1 = ports[1].get();
1538 Port* link_local2 = ports[2].get();
1539 Port* localhost = ports[3].get();
1540
1541 ExpectPortsCanConnect(false, link_local1, standard);
1542 ExpectPortsCanConnect(false, standard, link_local1);
1543 ExpectPortsCanConnect(false, link_local1, localhost);
1544 ExpectPortsCanConnect(false, localhost, link_local1);
1545
1546 ExpectPortsCanConnect(true, link_local1, link_local2);
1547 ExpectPortsCanConnect(true, localhost, standard);
1548 ExpectPortsCanConnect(true, standard, localhost);
1549}
1550
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001551// This test verifies DSCP value set through SetOption interface can be
1552// get through DefaultDscpValue.
1553TEST_F(PortTest, TestDefaultDscpValue) {
1554 int dscp;
1555 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1556 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1557 rtc::DSCP_CS6));
1558 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1559 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1560 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1561 rtc::DSCP_AF31));
1562 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1563 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1564 rtc::scoped_ptr<StunPort> stunport(
1565 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1566 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1567 rtc::DSCP_AF41));
1568 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1569 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1570 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1571 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1572 // Socket is created in PrepareAddress.
1573 turnport1->PrepareAddress();
1574 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1575 rtc::DSCP_CS7));
1576 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1577 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1578 // This will verify correct value returned without the socket.
1579 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1580 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1581 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1582 rtc::DSCP_CS6));
1583 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1584 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1585}
1586
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001587// Test sending STUN messages.
1588TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001589 rtc::scoped_ptr<TestPort> lport(
1590 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1591 rtc::scoped_ptr<TestPort> rport(
1592 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001593 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1594 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001595 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1596 rport->SetIceTiebreaker(kTiebreaker2);
1597
1598 // Send a fake ping from lport to rport.
1599 lport->PrepareAddress();
1600 rport->PrepareAddress();
1601 ASSERT_FALSE(rport->Candidates().empty());
1602 Connection* lconn = lport->CreateConnection(
1603 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1604 Connection* rconn = rport->CreateConnection(
1605 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1606 lconn->Ping(0);
1607
1608 // Check that it's a proper BINDING-REQUEST.
1609 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1610 IceMessage* msg = lport->last_stun_msg();
1611 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1612 EXPECT_FALSE(msg->IsLegacy());
1613 const StunByteStringAttribute* username_attr =
1614 msg->GetByteString(STUN_ATTR_USERNAME);
1615 ASSERT_TRUE(username_attr != NULL);
1616 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1617 ASSERT_TRUE(priority_attr != NULL);
1618 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1619 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1620 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1621 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1622 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1623 "rpass"));
1624 const StunUInt64Attribute* ice_controlling_attr =
1625 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1626 ASSERT_TRUE(ice_controlling_attr != NULL);
1627 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1628 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1629 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1630 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1631 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1632 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1633
1634 // Request should not include ping count.
1635 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1636
1637 // Save a copy of the BINDING-REQUEST for use below.
1638 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1639
1640 // Respond with a BINDING-RESPONSE.
1641 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1642 msg = rport->last_stun_msg();
1643 ASSERT_TRUE(msg != NULL);
1644 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1645
1646
1647 EXPECT_FALSE(msg->IsLegacy());
1648 const StunAddressAttribute* addr_attr = msg->GetAddress(
1649 STUN_ATTR_XOR_MAPPED_ADDRESS);
1650 ASSERT_TRUE(addr_attr != NULL);
1651 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1652 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1653 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1654 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1655 "rpass"));
1656 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1657 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1658 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1659 // No USERNAME or PRIORITY in ICE responses.
1660 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1661 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1662 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1663 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1664 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1665 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1666
1667 // Response should not include ping count.
1668 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1669
1670 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1671 // but we can do it here.
1672 rport->SendBindingErrorResponse(request.get(),
1673 lport->Candidates()[0].address(),
1674 STUN_ERROR_SERVER_ERROR,
1675 STUN_ERROR_REASON_SERVER_ERROR);
1676 msg = rport->last_stun_msg();
1677 ASSERT_TRUE(msg != NULL);
1678 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1679 EXPECT_FALSE(msg->IsLegacy());
1680 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1681 ASSERT_TRUE(error_attr != NULL);
1682 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1683 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1684 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1685 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1686 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1687 "rpass"));
1688 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1689 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1690 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1691 // No USERNAME with ICE.
1692 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1693 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1694
1695 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1696 // and (incremented) RETRANSMIT_COUNT attributes.
1697 rport->Reset();
1698 rport->set_send_retransmit_count_attribute(true);
1699 rconn->Ping(0);
1700 rconn->Ping(0);
1701 rconn->Ping(0);
1702 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1703 msg = rport->last_stun_msg();
1704 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1705 const StunUInt64Attribute* ice_controlled_attr =
1706 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1707 ASSERT_TRUE(ice_controlled_attr != NULL);
1708 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1709 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1710
1711 // Request should include ping count.
1712 const StunUInt32Attribute* retransmit_attr =
1713 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1714 ASSERT_TRUE(retransmit_attr != NULL);
1715 EXPECT_EQ(2U, retransmit_attr->value());
1716
1717 // Respond with a BINDING-RESPONSE.
1718 request.reset(CopyStunMessage(msg));
1719 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1720 msg = lport->last_stun_msg();
1721
1722 // Response should include same ping count.
1723 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1724 ASSERT_TRUE(retransmit_attr != NULL);
1725 EXPECT_EQ(2U, retransmit_attr->value());
1726}
1727
1728TEST_F(PortTest, TestUseCandidateAttribute) {
1729 rtc::scoped_ptr<TestPort> lport(
1730 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1731 rtc::scoped_ptr<TestPort> rport(
1732 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001733 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1734 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001735 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1736 rport->SetIceTiebreaker(kTiebreaker2);
1737
1738 // Send a fake ping from lport to rport.
1739 lport->PrepareAddress();
1740 rport->PrepareAddress();
1741 ASSERT_FALSE(rport->Candidates().empty());
1742 Connection* lconn = lport->CreateConnection(
1743 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1744 lconn->Ping(0);
1745 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1746 IceMessage* msg = lport->last_stun_msg();
1747 const StunUInt64Attribute* ice_controlling_attr =
1748 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1749 ASSERT_TRUE(ice_controlling_attr != NULL);
1750 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1751 STUN_ATTR_USE_CANDIDATE);
1752 ASSERT_TRUE(use_candidate_attr != NULL);
1753}
1754
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001755// Test handling STUN messages.
1756TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001757 // Our port will act as the "remote" port.
1758 rtc::scoped_ptr<TestPort> port(
1759 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001760
1761 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1762 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1763 rtc::SocketAddress addr(kLocalAddr1);
1764 std::string username;
1765
1766 // BINDING-REQUEST from local to remote with valid ICE username,
1767 // MESSAGE-INTEGRITY, and FINGERPRINT.
1768 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1769 "rfrag:lfrag"));
1770 in_msg->AddMessageIntegrity("rpass");
1771 in_msg->AddFingerprint();
1772 WriteStunMessage(in_msg.get(), buf.get());
1773 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1774 out_msg.accept(), &username));
1775 EXPECT_TRUE(out_msg.get() != NULL);
1776 EXPECT_EQ("lfrag", username);
1777
1778 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1779 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1780 in_msg->AddAttribute(
1781 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1782 in_msg->AddMessageIntegrity("rpass");
1783 in_msg->AddFingerprint();
1784 WriteStunMessage(in_msg.get(), buf.get());
1785 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1786 out_msg.accept(), &username));
1787 EXPECT_TRUE(out_msg.get() != NULL);
1788 EXPECT_EQ("", username);
1789
1790 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1791 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1792 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1793 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1794 in_msg->AddFingerprint();
1795 WriteStunMessage(in_msg.get(), buf.get());
1796 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1797 out_msg.accept(), &username));
1798 EXPECT_TRUE(out_msg.get() != NULL);
1799 EXPECT_EQ("", username);
1800 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1801 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1802 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1803 out_msg->GetErrorCode()->reason());
1804}
1805
guoweisd12140a2015-09-10 13:32:11 -07001806// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001807TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001808 rtc::scoped_ptr<TestPort> port(
1809 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001810
1811 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1812 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1813 rtc::SocketAddress addr(kLocalAddr1);
1814 std::string username;
1815
1816 // BINDING-REQUEST with no username.
1817 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1818 in_msg->AddMessageIntegrity("rpass");
1819 in_msg->AddFingerprint();
1820 WriteStunMessage(in_msg.get(), buf.get());
1821 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1822 out_msg.accept(), &username));
1823 EXPECT_TRUE(out_msg.get() == NULL);
1824 EXPECT_EQ("", username);
1825 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1826
1827 // BINDING-REQUEST with empty username.
1828 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1829 in_msg->AddMessageIntegrity("rpass");
1830 in_msg->AddFingerprint();
1831 WriteStunMessage(in_msg.get(), buf.get());
1832 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1833 out_msg.accept(), &username));
1834 EXPECT_TRUE(out_msg.get() == NULL);
1835 EXPECT_EQ("", username);
1836 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1837
1838 // BINDING-REQUEST with too-short username.
1839 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1840 in_msg->AddMessageIntegrity("rpass");
1841 in_msg->AddFingerprint();
1842 WriteStunMessage(in_msg.get(), buf.get());
1843 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1844 out_msg.accept(), &username));
1845 EXPECT_TRUE(out_msg.get() == NULL);
1846 EXPECT_EQ("", username);
1847 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1848
1849 // BINDING-REQUEST with reversed username.
1850 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1851 "lfrag:rfrag"));
1852 in_msg->AddMessageIntegrity("rpass");
1853 in_msg->AddFingerprint();
1854 WriteStunMessage(in_msg.get(), buf.get());
1855 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1856 out_msg.accept(), &username));
1857 EXPECT_TRUE(out_msg.get() == NULL);
1858 EXPECT_EQ("", username);
1859 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1860
1861 // BINDING-REQUEST with garbage username.
1862 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1863 "abcd:efgh"));
1864 in_msg->AddMessageIntegrity("rpass");
1865 in_msg->AddFingerprint();
1866 WriteStunMessage(in_msg.get(), buf.get());
1867 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1868 out_msg.accept(), &username));
1869 EXPECT_TRUE(out_msg.get() == NULL);
1870 EXPECT_EQ("", username);
1871 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1872}
1873
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001874// Test handling STUN messages with missing or malformed M-I.
1875TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001876 // Our port will act as the "remote" port.
1877 rtc::scoped_ptr<TestPort> port(
1878 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001879
1880 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1881 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1882 rtc::SocketAddress addr(kLocalAddr1);
1883 std::string username;
1884
1885 // BINDING-REQUEST from local to remote with valid ICE username and
1886 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1887 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1888 "rfrag:lfrag"));
1889 in_msg->AddFingerprint();
1890 WriteStunMessage(in_msg.get(), buf.get());
1891 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1892 out_msg.accept(), &username));
1893 EXPECT_TRUE(out_msg.get() == NULL);
1894 EXPECT_EQ("", username);
1895 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1896
1897 // BINDING-REQUEST from local to remote with valid ICE username and
1898 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1899 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1900 "rfrag:lfrag"));
1901 in_msg->AddMessageIntegrity("invalid");
1902 in_msg->AddFingerprint();
1903 WriteStunMessage(in_msg.get(), buf.get());
1904 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1905 out_msg.accept(), &username));
1906 EXPECT_TRUE(out_msg.get() == NULL);
1907 EXPECT_EQ("", username);
1908 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1909
1910 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1911 // by the Connection, not the Port, since they require the remote username.
1912 // Change this test to pass in data via Connection::OnReadPacket instead.
1913}
1914
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001915// Test handling STUN messages with missing or malformed FINGERPRINT.
1916TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001917 // Our port will act as the "remote" port.
1918 rtc::scoped_ptr<TestPort> port(
1919 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001920
1921 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1922 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1923 rtc::SocketAddress addr(kLocalAddr1);
1924 std::string username;
1925
1926 // BINDING-REQUEST from local to remote with valid ICE username and
1927 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1928 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1929 "rfrag:lfrag"));
1930 in_msg->AddMessageIntegrity("rpass");
1931 WriteStunMessage(in_msg.get(), buf.get());
1932 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1933 out_msg.accept(), &username));
1934 EXPECT_EQ(0, port->last_stun_error_code());
1935
1936 // Now, add a fingerprint, but munge the message so it's not valid.
1937 in_msg->AddFingerprint();
1938 in_msg->SetTransactionID("TESTTESTBADD");
1939 WriteStunMessage(in_msg.get(), buf.get());
1940 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1941 out_msg.accept(), &username));
1942 EXPECT_EQ(0, port->last_stun_error_code());
1943
1944 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1945 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1946 in_msg->AddAttribute(
1947 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1948 in_msg->AddMessageIntegrity("rpass");
1949 WriteStunMessage(in_msg.get(), buf.get());
1950 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1951 out_msg.accept(), &username));
1952 EXPECT_EQ(0, port->last_stun_error_code());
1953
1954 // Now, add a fingerprint, but munge the message so it's not valid.
1955 in_msg->AddFingerprint();
1956 in_msg->SetTransactionID("TESTTESTBADD");
1957 WriteStunMessage(in_msg.get(), buf.get());
1958 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1959 out_msg.accept(), &username));
1960 EXPECT_EQ(0, port->last_stun_error_code());
1961
1962 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1963 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1964 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1965 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1966 in_msg->AddMessageIntegrity("rpass");
1967 WriteStunMessage(in_msg.get(), buf.get());
1968 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1969 out_msg.accept(), &username));
1970 EXPECT_EQ(0, port->last_stun_error_code());
1971
1972 // Now, add a fingerprint, but munge the message so it's not valid.
1973 in_msg->AddFingerprint();
1974 in_msg->SetTransactionID("TESTTESTBADD");
1975 WriteStunMessage(in_msg.get(), buf.get());
1976 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1977 out_msg.accept(), &username));
1978 EXPECT_EQ(0, port->last_stun_error_code());
1979}
1980
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001981// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001982// indications are allowed only to the connection which is in read mode.
1983TEST_F(PortTest, TestHandleStunBindingIndication) {
1984 rtc::scoped_ptr<TestPort> lport(
1985 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001986 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1987 lport->SetIceTiebreaker(kTiebreaker1);
1988
1989 // Verifying encoding and decoding STUN indication message.
1990 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1991 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1992 rtc::SocketAddress addr(kLocalAddr1);
1993 std::string username;
1994
1995 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
1996 in_msg->AddFingerprint();
1997 WriteStunMessage(in_msg.get(), buf.get());
1998 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
1999 out_msg.accept(), &username));
2000 EXPECT_TRUE(out_msg.get() != NULL);
2001 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2002 EXPECT_EQ("", username);
2003
2004 // Verify connection can handle STUN indication and updates
2005 // last_ping_received.
2006 rtc::scoped_ptr<TestPort> rport(
2007 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002008 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2009 rport->SetIceTiebreaker(kTiebreaker2);
2010
2011 lport->PrepareAddress();
2012 rport->PrepareAddress();
2013 ASSERT_FALSE(lport->Candidates().empty());
2014 ASSERT_FALSE(rport->Candidates().empty());
2015
2016 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2017 Port::ORIGIN_MESSAGE);
2018 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2019 Port::ORIGIN_MESSAGE);
2020 rconn->Ping(0);
2021
2022 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2023 IceMessage* msg = rport->last_stun_msg();
2024 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2025 // Send rport binding request to lport.
2026 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
2027 rport->last_stun_buf()->Length(),
2028 rtc::PacketTime());
2029 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2030 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
Peter Boström0c4e06b2015-10-07 12:23:21 +02002031 uint32_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002032
2033 // Adding a delay of 100ms.
2034 rtc::Thread::Current()->ProcessMessages(100);
2035 // Pinging lconn using stun indication message.
2036 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
Peter Boström0c4e06b2015-10-07 12:23:21 +02002037 uint32_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002038 EXPECT_GT(last_ping_received2, last_ping_received1);
2039}
2040
2041TEST_F(PortTest, TestComputeCandidatePriority) {
2042 rtc::scoped_ptr<TestPort> port(
2043 CreateTestPort(kLocalAddr1, "name", "pass"));
2044 port->set_type_preference(90);
2045 port->set_component(177);
2046 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2047 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2048 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2049 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2050 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2051 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2052 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2053 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2054 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2055 // These should all be:
2056 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002057 uint32_t expected_priority_v4 = 1509957199U;
2058 uint32_t expected_priority_v6 = 1509959759U;
2059 uint32_t expected_priority_ula = 1509962319U;
2060 uint32_t expected_priority_v4mapped = expected_priority_v4;
2061 uint32_t expected_priority_v4compat = 1509949775U;
2062 uint32_t expected_priority_6to4 = 1509954639U;
2063 uint32_t expected_priority_teredo = 1509952079U;
2064 uint32_t expected_priority_sitelocal = 1509949775U;
2065 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002066 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2067 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2068 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2069 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2070 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2071 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2072 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2073 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2074 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2075}
2076
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002077// In the case of shared socket, one port may be shared by local and stun.
2078// Test that candidates with different types will have different foundation.
2079TEST_F(PortTest, TestFoundation) {
2080 rtc::scoped_ptr<TestPort> testport(
2081 CreateTestPort(kLocalAddr1, "name", "pass"));
2082 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2083 LOCAL_PORT_TYPE,
2084 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2085 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2086 STUN_PORT_TYPE,
2087 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2088 EXPECT_NE(testport->Candidates()[0].foundation(),
2089 testport->Candidates()[1].foundation());
2090}
2091
2092// This test verifies the foundation of different types of ICE candidates.
2093TEST_F(PortTest, TestCandidateFoundation) {
2094 rtc::scoped_ptr<rtc::NATServer> nat_server(
2095 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2096 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2097 udpport1->PrepareAddress();
2098 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2099 udpport2->PrepareAddress();
2100 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2101 udpport2->Candidates()[0].foundation());
2102 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2103 tcpport1->PrepareAddress();
2104 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2105 tcpport2->PrepareAddress();
2106 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2107 tcpport2->Candidates()[0].foundation());
2108 rtc::scoped_ptr<Port> stunport(
2109 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2110 stunport->PrepareAddress();
2111 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2112 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2113 stunport->Candidates()[0].foundation());
2114 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2115 stunport->Candidates()[0].foundation());
2116 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2117 stunport->Candidates()[0].foundation());
2118 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2119 stunport->Candidates()[0].foundation());
2120 // Verify GTURN candidate foundation.
2121 rtc::scoped_ptr<RelayPort> relayport(
2122 CreateGturnPort(kLocalAddr1));
2123 relayport->AddServerAddress(
2124 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2125 relayport->PrepareAddress();
2126 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2127 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2128 relayport->Candidates()[0].foundation());
2129 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2130 relayport->Candidates()[0].foundation());
2131 // Verifying TURN candidate foundation.
2132 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2133 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2134 turnport1->PrepareAddress();
2135 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2136 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2137 turnport1->Candidates()[0].foundation());
2138 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2139 turnport1->Candidates()[0].foundation());
2140 EXPECT_NE(stunport->Candidates()[0].foundation(),
2141 turnport1->Candidates()[0].foundation());
2142 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2143 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2144 turnport2->PrepareAddress();
2145 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2146 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2147 turnport2->Candidates()[0].foundation());
2148
2149 // Running a second turn server, to get different base IP address.
2150 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2151 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2152 TestTurnServer turn_server2(
2153 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2154 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2155 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2156 kTurnUdpIntAddr2));
2157 turnport3->PrepareAddress();
2158 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2159 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2160 turnport2->Candidates()[0].foundation());
2161}
2162
2163// This test verifies the related addresses of different types of
2164// ICE candiates.
2165TEST_F(PortTest, TestCandidateRelatedAddress) {
2166 rtc::scoped_ptr<rtc::NATServer> nat_server(
2167 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2168 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2169 udpport->PrepareAddress();
2170 // For UDPPort, related address will be empty.
2171 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2172 // Testing related address for stun candidates.
2173 // For stun candidate related address must be equal to the base
2174 // socket address.
2175 rtc::scoped_ptr<StunPort> stunport(
2176 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2177 stunport->PrepareAddress();
2178 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2179 // Check STUN candidate address.
2180 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2181 kNatAddr1.ipaddr());
2182 // Check STUN candidate related address.
2183 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2184 stunport->GetLocalAddress());
2185 // Verifying the related address for the GTURN candidates.
2186 // NOTE: In case of GTURN related address will be equal to the mapped
2187 // address, but address(mapped) will not be XOR.
2188 rtc::scoped_ptr<RelayPort> relayport(
2189 CreateGturnPort(kLocalAddr1));
2190 relayport->AddServerAddress(
2191 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2192 relayport->PrepareAddress();
2193 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2194 // For Gturn related address is set to "0.0.0.0:0"
2195 EXPECT_EQ(rtc::SocketAddress(),
2196 relayport->Candidates()[0].related_address());
2197 // Verifying the related address for TURN candidate.
2198 // For TURN related address must be equal to the mapped address.
2199 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2200 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2201 turnport->PrepareAddress();
2202 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2203 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2204 turnport->Candidates()[0].address().ipaddr());
2205 EXPECT_EQ(kNatAddr1.ipaddr(),
2206 turnport->Candidates()[0].related_address().ipaddr());
2207}
2208
2209// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002210TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002211 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002212 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002213 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002214 cand2.set_priority(1);
2215 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002216}
2217
2218// Test the Connection priority is calculated correctly.
2219TEST_F(PortTest, TestConnectionPriority) {
2220 rtc::scoped_ptr<TestPort> lport(
2221 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2222 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2223 rtc::scoped_ptr<TestPort> rport(
2224 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2225 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2226 lport->set_component(123);
2227 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2228 rport->set_component(23);
2229 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2230
2231 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2232 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2233
2234 // RFC 5245
2235 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2236 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2237 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2238 Connection* lconn = lport->CreateConnection(
2239 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2240#if defined(WEBRTC_WIN)
2241 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2242#else
2243 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2244#endif
2245
2246 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2247 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2248 Connection* rconn = rport->CreateConnection(
2249 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2250#if defined(WEBRTC_WIN)
2251 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2252#else
2253 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2254#endif
2255}
2256
2257TEST_F(PortTest, TestWritableState) {
2258 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002259 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002260 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002261 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002262
2263 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002264 TestChannel ch1(port1);
2265 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002266
2267 // Acquire addresses.
2268 ch1.Start();
2269 ch2.Start();
2270 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2271 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2272
2273 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002274 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002275 ASSERT_TRUE(ch1.conn() != NULL);
2276 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2277 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2278 ch1.Ping();
2279 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2280
2281 // Data should be unsendable until the connection is accepted.
2282 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002283 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002284 rtc::PacketOptions options;
2285 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2286
2287 // Accept the connection to return the binding response, transition to
2288 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002289 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002290 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2291 kTimeout);
2292 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2293
2294 // Ask the connection to update state as if enough time has passed to lose
2295 // full writability and 5 pings went unresponded to. We'll accomplish the
2296 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002297 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002298 ch1.Ping(i);
2299 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002300 uint32_t unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002301 ch1.conn()->UpdateState(unreliable_timeout_delay);
2302 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2303
2304 // Data should be able to be sent in this state.
2305 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2306
2307 // And now allow the other side to process the pings and send binding
2308 // responses.
2309 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2310 kTimeout);
2311
2312 // Wait long enough for a full timeout (past however long we've already
2313 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002314 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002315 ch1.Ping(unreliable_timeout_delay + i);
2316 }
2317 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2318 500u);
2319 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2320
2321 // Now that the connection has completely timed out, data send should fail.
2322 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2323
2324 ch1.Stop();
2325 ch2.Stop();
2326}
2327
2328TEST_F(PortTest, TestTimeoutForNeverWritable) {
2329 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002330 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002331 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002332 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002333
2334 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002335 TestChannel ch1(port1);
2336 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002337
2338 // Acquire addresses.
2339 ch1.Start();
2340 ch2.Start();
2341
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002342 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002343 ASSERT_TRUE(ch1.conn() != NULL);
2344 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2345
2346 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002347 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002348 ch1.Ping(i);
2349 }
2350 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2351 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2352}
2353
2354// This test verifies the connection setup between ICEMODE_FULL
2355// and ICEMODE_LITE.
2356// In this test |ch1| behaves like FULL mode client and we have created
2357// port which responds to the ping message just like LITE client.
2358TEST_F(PortTest, TestIceLiteConnectivity) {
2359 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002360 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002361 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2362
2363 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002364 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002365 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2366 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002367 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002368 ch1.SetIceMode(ICEMODE_FULL);
2369
2370 // Start gathering candidates.
2371 ch1.Start();
2372 ice_lite_port->PrepareAddress();
2373
2374 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2375 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2376
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002377 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002378 ASSERT_TRUE(ch1.conn() != NULL);
2379 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2380
2381 // Send ping from full mode client.
2382 // This ping must not have USE_CANDIDATE_ATTR.
2383 ch1.Ping();
2384
2385 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2386 // from port.
2387 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2388 IceMessage* msg = ice_full_port->last_stun_msg();
2389 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2390
2391 // Respond with a BINDING-RESPONSE from litemode client.
2392 // NOTE: Ideally we should't create connection at this stage from lite
2393 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2394 // But we need a connection to send a response message.
2395 ice_lite_port->CreateConnection(
2396 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2397 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2398 ice_lite_port->SendBindingResponse(
2399 request.get(), ice_full_port->Candidates()[0].address());
2400
2401 // Feeding the respone message from litemode to the full mode connection.
2402 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2403 ice_lite_port->last_stun_buf()->Length(),
2404 rtc::PacketTime());
2405 // Verifying full mode connection becomes writable from the response.
2406 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2407 kTimeout);
2408 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2409
2410 // Clear existing stun messsages. Otherwise we will process old stun
2411 // message right after we send ping.
2412 ice_full_port->Reset();
2413 // Send ping. This must have USE_CANDIDATE_ATTR.
2414 ch1.Ping();
2415 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2416 msg = ice_full_port->last_stun_msg();
2417 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2418 ch1.Stop();
2419}
2420
2421// This test case verifies that the CONTROLLING port does not time out.
2422TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002423 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2424 ConnectToSignalDestroyed(port1);
2425 port1->set_timeout_delay(10); // milliseconds
2426 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2427 port1->SetIceTiebreaker(kTiebreaker1);
2428
2429 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2430 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2431 port2->SetIceTiebreaker(kTiebreaker2);
2432
2433 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002434 TestChannel ch1(port1);
2435 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002436
2437 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002438 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002439
2440 // After the connection is destroyed, the port should not be destroyed.
2441 rtc::Thread::Current()->ProcessMessages(kTimeout);
2442 EXPECT_FALSE(destroyed());
2443}
2444
2445// This test case verifies that the CONTROLLED port does time out, but only
2446// after connectivity is lost.
2447TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002448 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2449 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2450 port1->SetIceTiebreaker(kTiebreaker1);
2451
2452 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2453 ConnectToSignalDestroyed(port2);
2454 port2->set_timeout_delay(10); // milliseconds
2455 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2456 port2->SetIceTiebreaker(kTiebreaker2);
2457
2458 // The connection must not be destroyed before a connection is attempted.
2459 EXPECT_FALSE(destroyed());
2460
2461 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2462 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2463
2464 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002465 TestChannel ch1(port1);
2466 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002467
2468 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002469 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002470
2471 // The controlled port should be destroyed after 10 milliseconds.
2472 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2473}
honghaizd0b31432015-09-30 12:42:17 -07002474
2475// This test case verifies that if the role of a port changes from controlled
2476// to controlling after all connections fail, the port will not be destroyed.
2477TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2478 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2479 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2480 port1->SetIceTiebreaker(kTiebreaker1);
2481
2482 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2483 ConnectToSignalDestroyed(port2);
2484 port2->set_timeout_delay(10); // milliseconds
2485 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2486 port2->SetIceTiebreaker(kTiebreaker2);
2487
2488 // The connection must not be destroyed before a connection is attempted.
2489 EXPECT_FALSE(destroyed());
2490
2491 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2492 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2493
2494 // Set up channels and ensure both ports will be deleted.
2495 TestChannel ch1(port1);
2496 TestChannel ch2(port2);
2497
2498 // Simulate a connection that succeeds, and then is destroyed.
2499 StartConnectAndStopChannels(&ch1, &ch2);
2500 // Switch the role after all connections are destroyed.
2501 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2502 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2503 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2504
2505 // After the connection is destroyed, the port should not be destroyed.
2506 rtc::Thread::Current()->ProcessMessages(kTimeout);
2507 EXPECT_FALSE(destroyed());
2508}
Honghai Zhangf9945b22015-12-15 12:20:13 -08002509
2510TEST_F(PortTest, TestSupportsProtocol) {
2511 rtc::scoped_ptr<Port> udp_port(CreateUdpPort(kLocalAddr1));
2512 EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2513 EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2514
2515 rtc::scoped_ptr<Port> stun_port(
2516 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2517 EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2518 EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2519
2520 rtc::scoped_ptr<Port> tcp_port(CreateTcpPort(kLocalAddr1));
2521 EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2522 EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
2523 EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2524
2525 rtc::scoped_ptr<Port> turn_port(
2526 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2527 EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2528 EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2529}