blob: be5ced97c0b0085170c30dc0715fb3998fb348e5 [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);
Honghai Zhang80f1db92016-01-27 11:54:45 -080061static const SocketAddress kTurnTcpIntAddr("99.99.99.4", 5010);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000062static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
63static const RelayCredentials kRelayCredentials("test", "test");
64
65// TODO: Update these when RFC5245 is completely supported.
66// Magic value of 30 is from RFC3484, for IPv4 addresses.
Peter Boström0c4e06b2015-10-07 12:23:21 +020067static const uint32_t kDefaultPrflxPriority =
68 ICE_TYPE_PREFERENCE_PRFLX << 24 | 30 << 8 |
69 (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000070
71static const int kTiebreaker1 = 11111;
72static const int kTiebreaker2 = 22222;
73
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070074static const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
75
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000076static Candidate GetCandidate(Port* port) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -070077 assert(port->Candidates().size() >= 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000078 return port->Candidates()[0];
79}
80
81static SocketAddress GetAddress(Port* port) {
82 return GetCandidate(port).address();
83}
84
85static IceMessage* CopyStunMessage(const IceMessage* src) {
86 IceMessage* dst = new IceMessage();
87 ByteBuffer buf;
88 src->Write(&buf);
89 dst->Read(&buf);
90 return dst;
91}
92
93static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
94 buf->Resize(0); // clear out any existing buffer contents
95 return msg->Write(buf);
96}
97
98// Stub port class for testing STUN generation and processing.
99class TestPort : public Port {
100 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000101 TestPort(rtc::Thread* thread,
102 const std::string& type,
103 rtc::PacketSocketFactory* factory,
104 rtc::Network* network,
105 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200106 uint16_t min_port,
107 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000108 const std::string& username_fragment,
109 const std::string& password)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200110 : Port(thread,
111 type,
112 factory,
113 network,
114 ip,
115 min_port,
116 max_port,
117 username_fragment,
118 password) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119 ~TestPort() {}
120
121 // Expose GetStunMessage so that we can test it.
122 using cricket::Port::GetStunMessage;
123
124 // The last StunMessage that was sent on this Port.
125 // TODO: Make these const; requires changes to SendXXXXResponse.
126 ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
127 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
128 int last_stun_error_code() {
129 int code = 0;
130 if (last_stun_msg_) {
131 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
132 if (error_attr) {
133 code = error_attr->code();
134 }
135 }
136 return code;
137 }
138
139 virtual void PrepareAddress() {
140 rtc::SocketAddress addr(ip(), min_port());
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700141 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 ICE_TYPE_PREFERENCE_HOST, 0, true);
143 }
144
Honghai Zhangf9945b22015-12-15 12:20:13 -0800145 virtual bool SupportsProtocol(const std::string& protocol) const {
146 return true;
147 }
148
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149 // Exposed for testing candidate building.
150 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700151 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 type_preference_, 0, false);
153 }
154 void AddCandidateAddress(const rtc::SocketAddress& addr,
155 const rtc::SocketAddress& base_address,
156 const std::string& type,
157 int type_preference,
158 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700159 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 type_preference, 0, final);
161 }
162
163 virtual Connection* CreateConnection(const Candidate& remote_candidate,
164 CandidateOrigin origin) {
165 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
166 AddConnection(conn);
167 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
168 // in STUN binding requests.
169 conn->set_use_candidate_attr(true);
170 return conn;
171 }
172 virtual int SendTo(
173 const void* data, size_t size, const rtc::SocketAddress& addr,
174 const rtc::PacketOptions& options, bool payload) {
175 if (!payload) {
176 IceMessage* msg = new IceMessage;
177 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
178 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
179 if (!msg->Read(buf)) {
180 delete msg;
181 delete buf;
182 return -1;
183 }
184 buf->SetReadPosition(pos);
185 last_stun_buf_.reset(buf);
186 last_stun_msg_.reset(msg);
187 }
188 return static_cast<int>(size);
189 }
190 virtual int SetOption(rtc::Socket::Option opt, int value) {
191 return 0;
192 }
193 virtual int GetOption(rtc::Socket::Option opt, int* value) {
194 return -1;
195 }
196 virtual int GetError() {
197 return 0;
198 }
199 void Reset() {
200 last_stun_buf_.reset();
201 last_stun_msg_.reset();
202 }
203 void set_type_preference(int type_preference) {
204 type_preference_ = type_preference;
205 }
206
207 private:
Stefan Holmer55674ff2016-01-14 15:49:16 +0100208 void OnSentPacket(rtc::AsyncPacketSocket* socket,
209 const rtc::SentPacket& sent_packet) {
210 PortInterface::SignalSentPacket(sent_packet);
211 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
213 rtc::scoped_ptr<IceMessage> last_stun_msg_;
pbos7640ffa2015-11-30 09:16:59 -0800214 int type_preference_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215};
216
217class TestChannel : public sigslot::has_slots<> {
218 public:
219 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700220 TestChannel(Port* p1)
221 : ice_mode_(ICEMODE_FULL),
222 port_(p1),
223 complete_count_(0),
224 conn_(NULL),
225 remote_request_(),
226 nominated_(false) {
227 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
228 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
229 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 }
231
232 int complete_count() { return complete_count_; }
233 Connection* conn() { return conn_; }
234 const SocketAddress& remote_address() { return remote_address_; }
235 const std::string remote_fragment() { return remote_frag_; }
236
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700237 void Start() { port_->PrepareAddress(); }
238 void CreateConnection(const Candidate& remote_candidate) {
239 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000240 IceMode remote_ice_mode =
241 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
242 conn_->set_remote_ice_mode(remote_ice_mode);
243 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
244 conn_->SignalStateChange.connect(
245 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700246 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700247 conn_->SignalReadyToSend.connect(this,
248 &TestChannel::OnConnectionReadyToSend);
249 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 }
251 void OnConnectionStateChange(Connection* conn) {
252 if (conn->write_state() == Connection::STATE_WRITABLE) {
253 conn->set_use_candidate_attr(true);
254 nominated_ = true;
255 }
256 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700257 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700259 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700261 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700262 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700263 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 remote_request_.reset();
265 }
266 void Ping() {
267 Ping(0);
268 }
honghaiz34b11eb2016-03-16 08:55:44 -0700269 void Ping(int64_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700271 if (conn_) {
272 conn_->Destroy();
273 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274 }
275
276 void OnPortComplete(Port* port) {
277 complete_count_++;
278 }
279 void SetIceMode(IceMode ice_mode) {
280 ice_mode_ = ice_mode;
281 }
282
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700283 int SendData(const char* data, size_t len) {
284 rtc::PacketOptions options;
285 return conn_->Send(data, len, options);
286 }
287
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
289 ProtocolType proto,
290 IceMessage* msg, const std::string& rf,
291 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700292 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 if (!remote_address_.IsNil()) {
294 ASSERT_EQ(remote_address_, addr);
295 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 const cricket::StunUInt32Attribute* priority_attr =
297 msg->GetUInt32(STUN_ATTR_PRIORITY);
298 const cricket::StunByteStringAttribute* mi_attr =
299 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
300 const cricket::StunUInt32Attribute* fingerprint_attr =
301 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700302 EXPECT_TRUE(priority_attr != NULL);
303 EXPECT_TRUE(mi_attr != NULL);
304 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 remote_address_ = addr;
306 remote_request_.reset(CopyStunMessage(msg));
307 remote_frag_ = rf;
308 }
309
310 void OnDestroyed(Connection* conn) {
311 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700312 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700314 // When the connection is destroyed, also clear these fields so future
315 // connections are possible.
316 remote_request_.reset();
317 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 }
319
320 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700321 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322 ASSERT_EQ(destroyed_src, port);
323 }
324
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700325 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327 bool nominated() const { return nominated_; }
328
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700329 void set_connection_ready_to_send(bool ready) {
330 connection_ready_to_send_ = ready;
331 }
332 bool connection_ready_to_send() const {
333 return connection_ready_to_send_;
334 }
335
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700337 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
338 void OnConnectionReadyToSend(Connection* conn) {
339 ASSERT_EQ(conn, conn_);
340 connection_ready_to_send_ = true;
341 }
342
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000343 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700344 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000345
346 int complete_count_;
347 Connection* conn_;
348 SocketAddress remote_address_;
349 rtc::scoped_ptr<StunMessage> remote_request_;
350 std::string remote_frag_;
351 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700352 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353};
354
355class PortTest : public testing::Test, public sigslot::has_slots<> {
356 public:
357 PortTest()
358 : main_(rtc::Thread::Current()),
359 pss_(new rtc::PhysicalSocketServer),
360 ss_(new rtc::VirtualSocketServer(pss_.get())),
361 ss_scope_(ss_.get()),
362 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
363 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700364 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
365 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000366 nat_socket_factory1_(&nat_factory1_),
367 nat_socket_factory2_(&nat_factory2_),
368 stun_server_(TestStunServer::Create(main_, kStunAddr)),
369 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700370 relay_server_(main_,
371 kRelayUdpIntAddr,
372 kRelayUdpExtAddr,
373 kRelayTcpIntAddr,
374 kRelayTcpExtAddr,
375 kRelaySslTcpIntAddr,
376 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
378 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 role_conflict_(false),
380 destroyed_(false) {
381 network_.AddIP(rtc::IPAddress(INADDR_ANY));
382 }
383
384 protected:
385 void TestLocalToLocal() {
386 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700387 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700389 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
391 }
392 void TestLocalToStun(NATType ntype) {
393 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700394 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
396 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700397 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 TestConnectivity("udp", port1, StunName(ntype), port2,
399 ntype == NAT_OPEN_CONE, true,
400 ntype != NAT_SYMMETRIC, true);
401 }
402 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
403 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700404 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000405 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700406 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
408 rtype == RELAY_GTURN, true, true, true);
409 }
410 void TestStunToLocal(NATType ntype) {
411 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
412 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700413 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700415 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000416 TestConnectivity(StunName(ntype), port1, "udp", port2,
417 true, ntype != NAT_SYMMETRIC, true, true);
418 }
419 void TestStunToStun(NATType ntype1, NATType ntype2) {
420 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
421 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700422 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000423 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
424 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700425 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000426 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
427 ntype2 == NAT_OPEN_CONE,
428 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
429 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
430 }
431 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
432 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
433 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700434 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700436 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000437 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
438 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
439 }
440 void TestTcpToTcp() {
441 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700442 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700444 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
446 }
447 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
448 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700449 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700451 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000452 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
453 rtype == RELAY_GTURN, false, true, true);
454 }
455 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
456 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700457 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700459 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
461 rtype == RELAY_GTURN, false, true, true);
462 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 // helpers for above functions
464 UDPPort* CreateUdpPort(const SocketAddress& addr) {
465 return CreateUdpPort(addr, &socket_factory_);
466 }
467 UDPPort* CreateUdpPort(const SocketAddress& addr,
468 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800469 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
470 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 }
472 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700473 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 }
475 TCPPort* CreateTcpPort(const SocketAddress& addr,
476 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700477 return TCPPort::Create(main_, socket_factory, &network_,
478 addr.ipaddr(), 0, 0, username_, password_,
479 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 }
481 StunPort* CreateStunPort(const SocketAddress& addr,
482 rtc::PacketSocketFactory* factory) {
483 ServerAddresses stun_servers;
484 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700485 return StunPort::Create(main_, factory, &network_,
486 addr.ipaddr(), 0, 0,
487 username_, password_, stun_servers,
488 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 }
490 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
491 ProtocolType int_proto, ProtocolType ext_proto) {
492 if (rtype == RELAY_TURN) {
493 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
494 } else {
495 return CreateGturnPort(addr, int_proto, ext_proto);
496 }
497 }
498 TurnPort* CreateTurnPort(const SocketAddress& addr,
499 PacketSocketFactory* socket_factory,
500 ProtocolType int_proto, ProtocolType ext_proto) {
Honghai Zhang80f1db92016-01-27 11:54:45 -0800501 SocketAddress server_addr =
502 int_proto == PROTO_TCP ? kTurnTcpIntAddr : kTurnUdpIntAddr;
503 return CreateTurnPort(addr, socket_factory, int_proto, ext_proto,
504 server_addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505 }
506 TurnPort* CreateTurnPort(const SocketAddress& addr,
507 PacketSocketFactory* socket_factory,
508 ProtocolType int_proto, ProtocolType ext_proto,
509 const rtc::SocketAddress& server_addr) {
Honghai Zhang80f1db92016-01-27 11:54:45 -0800510 return TurnPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
511 0, username_, password_,
512 ProtocolAddress(server_addr, int_proto),
513 kRelayCredentials, 0, std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000514 }
515 RelayPort* CreateGturnPort(const SocketAddress& addr,
516 ProtocolType int_proto, ProtocolType ext_proto) {
517 RelayPort* port = CreateGturnPort(addr);
518 SocketAddress addrs[] =
519 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
520 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
521 return port;
522 }
523 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700524 // TODO(pthatcher): Remove GTURN.
525 return RelayPort::Create(main_, &socket_factory_, &network_,
526 addr.ipaddr(), 0, 0,
527 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000528 // TODO: Add an external address for ext_proto, so that the
529 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 }
531 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
532 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700533 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000534 }
535 static const char* StunName(NATType type) {
536 switch (type) {
537 case NAT_OPEN_CONE: return "stun(open cone)";
538 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
539 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
540 case NAT_SYMMETRIC: return "stun(symmetric)";
541 default: return "stun(?)";
542 }
543 }
544 static const char* RelayName(RelayType type, ProtocolType proto) {
545 if (type == RELAY_TURN) {
546 switch (proto) {
547 case PROTO_UDP: return "turn(udp)";
548 case PROTO_TCP: return "turn(tcp)";
549 case PROTO_SSLTCP: return "turn(ssltcp)";
550 default: return "turn(?)";
551 }
552 } else {
553 switch (proto) {
554 case PROTO_UDP: return "gturn(udp)";
555 case PROTO_TCP: return "gturn(tcp)";
556 case PROTO_SSLTCP: return "gturn(ssltcp)";
557 default: return "gturn(?)";
558 }
559 }
560 }
561
562 void TestCrossFamilyPorts(int type);
563
Peter Thatcherb8b01432015-07-07 16:45:53 -0700564 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
565
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000566 // This does all the work and then deletes |port1| and |port2|.
567 void TestConnectivity(const char* name1, Port* port1,
568 const char* name2, Port* port2,
569 bool accept, bool same_addr1,
570 bool same_addr2, bool possible);
571
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700572 // This connects the provided channels which have already started. |ch1|
573 // should have its Connection created (either through CreateConnection() or
574 // TCP reconnecting mechanism before entering this function.
575 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
576 ASSERT_TRUE(ch1->conn());
577 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
578 ch1->Ping();
579 WAIT(!ch2->remote_address().IsNil(), kTimeout);
580
581 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700582 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700583 ch2->Ping();
584 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
585 kTimeout);
586 }
587
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000588 // This connects and disconnects the provided channels in the same sequence as
589 // TestConnectivity with all options set to |true|. It does not delete either
590 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700591 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
592 // Acquire addresses.
593 ch1->Start();
594 ch2->Start();
595
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700596 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700597 ConnectStartedChannels(ch1, ch2);
598
599 // Destroy the connections.
600 ch1->Stop();
601 ch2->Stop();
602 }
603
604 // This disconnects both end's Connection and make sure ch2 ready for new
605 // connection.
606 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700607 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
608 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
609 ASSERT_TRUE(
610 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
611 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700612
613 // Wait for both OnClose are delivered.
614 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
615 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
616
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700617 // Ensure redundant SignalClose events on TcpConnection won't break tcp
618 // reconnection. Chromium will fire SignalClose for all outstanding IPC
619 // packets during reconnection.
620 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
621 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
622
623 // Speed up destroying ch2's connection such that the test is ready to
624 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700625 ch2->conn()->Destroy();
626 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
627 }
628
629 void TestTcpReconnect(bool ping_after_disconnected,
630 bool send_after_disconnected) {
631 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700632 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700633 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700634 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700635
636 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
637 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
638
639 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700640 TestChannel ch1(port1);
641 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700642 EXPECT_EQ(0, ch1.complete_count());
643 EXPECT_EQ(0, ch2.complete_count());
644
645 ch1.Start();
646 ch2.Start();
647 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
648 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
649
650 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700651 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700652 ConnectStartedChannels(&ch1, &ch2);
653
654 // Shorten the timeout period.
655 const int kTcpReconnectTimeout = kTimeout;
656 static_cast<TCPConnection*>(ch1.conn())
657 ->set_reconnection_timeout(kTcpReconnectTimeout);
658 static_cast<TCPConnection*>(ch2.conn())
659 ->set_reconnection_timeout(kTcpReconnectTimeout);
660
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700661 EXPECT_FALSE(ch1.connection_ready_to_send());
662 EXPECT_FALSE(ch2.connection_ready_to_send());
663
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700664 // Once connected, disconnect them.
665 DisconnectTcpTestChannels(&ch1, &ch2);
666
667 if (send_after_disconnected || ping_after_disconnected) {
668 if (send_after_disconnected) {
669 // First SendData after disconnect should fail but will trigger
670 // reconnect.
671 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
672 }
673
674 if (ping_after_disconnected) {
675 // Ping should trigger reconnect.
676 ch1.Ping();
677 }
678
679 // Wait for channel's outgoing TCPConnection connected.
680 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
681
682 // Verify that we could still connect channels.
683 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700684 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
685 kTcpReconnectTimeout);
686 // Channel2 is the passive one so a new connection is created during
687 // reconnect. This new connection should never have issued EWOULDBLOCK
688 // hence the connection_ready_to_send() should be false.
689 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700690 } else {
691 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700692 // Since the reconnection never happens, the connections should have been
693 // destroyed after the timeout.
694 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
695 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700696 }
697
698 // Tear down and ensure that goes smoothly.
699 ch1.Stop();
700 ch2.Stop();
701 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
702 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
703 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 IceMessage* CreateStunMessage(int type) {
706 IceMessage* msg = new IceMessage();
707 msg->SetType(type);
708 msg->SetTransactionID("TESTTESTTEST");
709 return msg;
710 }
711 IceMessage* CreateStunMessageWithUsername(int type,
712 const std::string& username) {
713 IceMessage* msg = CreateStunMessage(type);
714 msg->AddAttribute(
715 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
716 return msg;
717 }
718 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
719 const std::string& username,
720 const std::string& password) {
721 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
722 addr.ipaddr(), 0, 0, username, password);
723 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
724 return port;
725 }
726 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
727 const std::string& username,
728 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000729 cricket::IceRole role,
730 int tiebreaker) {
731 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000732 port->SetIceRole(role);
733 port->SetIceTiebreaker(tiebreaker);
734 return port;
735 }
736
737 void OnRoleConflict(PortInterface* port) {
738 role_conflict_ = true;
739 }
740 bool role_conflict() const { return role_conflict_; }
741
742 void ConnectToSignalDestroyed(PortInterface* port) {
743 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
744 }
745
746 void OnDestroyed(PortInterface* port) {
747 destroyed_ = true;
748 }
749 bool destroyed() const { return destroyed_; }
750
751 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
752 return &nat_socket_factory1_;
753 }
754
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700755 protected:
756 rtc::VirtualSocketServer* vss() { return ss_.get(); }
757
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758 private:
759 rtc::Thread* main_;
760 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
761 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
762 rtc::SocketServerScope ss_scope_;
763 rtc::Network network_;
764 rtc::BasicPacketSocketFactory socket_factory_;
765 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
766 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
767 rtc::NATSocketFactory nat_factory1_;
768 rtc::NATSocketFactory nat_factory2_;
769 rtc::BasicPacketSocketFactory nat_socket_factory1_;
770 rtc::BasicPacketSocketFactory nat_socket_factory2_;
771 scoped_ptr<TestStunServer> stun_server_;
772 TestTurnServer turn_server_;
773 TestRelayServer relay_server_;
774 std::string username_;
775 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000776 bool role_conflict_;
777 bool destroyed_;
778};
779
780void PortTest::TestConnectivity(const char* name1, Port* port1,
781 const char* name2, Port* port2,
782 bool accept, bool same_addr1,
783 bool same_addr2, bool possible) {
784 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
785 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
786 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
787
788 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700789 TestChannel ch1(port1);
790 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791 EXPECT_EQ(0, ch1.complete_count());
792 EXPECT_EQ(0, ch2.complete_count());
793
794 // Acquire addresses.
795 ch1.Start();
796 ch2.Start();
797 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
798 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
799
800 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700801 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 ASSERT_TRUE(ch1.conn() != NULL);
803 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
804 ch1.Ping();
805 WAIT(!ch2.remote_address().IsNil(), kTimeout);
806
807 if (accept) {
808 // We are able to send a ping from src to dst. This is the case when
809 // sending to UDP ports and cone NATs.
810 EXPECT_TRUE(ch1.remote_address().IsNil());
811 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
812
813 // Ensure the ping came from the same address used for src.
814 // This is the case unless the source NAT was symmetric.
815 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
816 EXPECT_TRUE(same_addr2);
817
818 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700819 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000820 ASSERT_TRUE(ch2.conn() != NULL);
821 ch2.Ping();
822 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
823 kTimeout);
824 } else {
825 // We can't send a ping from src to dst, so flip it around. This will happen
826 // when the destination NAT is addr/port restricted or symmetric.
827 EXPECT_TRUE(ch1.remote_address().IsNil());
828 EXPECT_TRUE(ch2.remote_address().IsNil());
829
830 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700831 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832 ASSERT_TRUE(ch2.conn() != NULL);
833 ch2.Ping();
834 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
835
836 if (same_addr1 && same_addr2) {
837 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700838 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
840
841 // First connection may not be writable if the first ping did not get
842 // through. So we will have to do another.
843 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
844 ch1.Ping();
845 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
846 kTimeout);
847 }
848 } else if (!same_addr1 && possible) {
849 // The new ping went to the candidate address, but that address was bad.
850 // This will happen when the source NAT is symmetric.
851 EXPECT_TRUE(ch1.remote_address().IsNil());
852 EXPECT_TRUE(ch2.remote_address().IsNil());
853
854 // However, since we have now sent a ping to the source IP, we should be
855 // able to get a ping from it. This gives us the real source address.
856 ch1.Ping();
857 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700858 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859 EXPECT_TRUE(ch1.remote_address().IsNil());
860
861 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700862 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863 ASSERT_TRUE(ch2.conn() != NULL);
864 ch2.Ping();
865 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
866 kTimeout);
867 } else if (!same_addr2 && possible) {
868 // The new ping came in, but from an unexpected address. This will happen
869 // when the destination NAT is symmetric.
870 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700871 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872
873 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700874 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000875 ch1.Ping();
876 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
877 kTimeout);
878 } else { // (!possible)
879 // There should be s no way for the pings to reach each other. Check it.
880 EXPECT_TRUE(ch1.remote_address().IsNil());
881 EXPECT_TRUE(ch2.remote_address().IsNil());
882 ch1.Ping();
883 WAIT(!ch2.remote_address().IsNil(), kTimeout);
884 EXPECT_TRUE(ch1.remote_address().IsNil());
885 EXPECT_TRUE(ch2.remote_address().IsNil());
886 }
887 }
888
889 // Everything should be good, unless we know the situation is impossible.
890 ASSERT_TRUE(ch1.conn() != NULL);
891 ASSERT_TRUE(ch2.conn() != NULL);
892 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700893 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000894 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700895 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000896 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
897 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700898 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000899 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700900 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
902 }
903
904 // Tear down and ensure that goes smoothly.
905 ch1.Stop();
906 ch2.Stop();
907 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
908 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
909}
910
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911class FakePacketSocketFactory : public rtc::PacketSocketFactory {
912 public:
913 FakePacketSocketFactory()
914 : next_udp_socket_(NULL),
915 next_server_tcp_socket_(NULL),
916 next_client_tcp_socket_(NULL) {
917 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000918 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000919
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000920 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200921 uint16_t min_port,
922 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 EXPECT_TRUE(next_udp_socket_ != NULL);
924 AsyncPacketSocket* result = next_udp_socket_;
925 next_udp_socket_ = NULL;
926 return result;
927 }
928
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000929 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200930 uint16_t min_port,
931 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000932 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
934 AsyncPacketSocket* result = next_server_tcp_socket_;
935 next_server_tcp_socket_ = NULL;
936 return result;
937 }
938
939 // TODO: |proxy_info| and |user_agent| should be set
940 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000941 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
942 const SocketAddress& remote_address,
943 const rtc::ProxyInfo& proxy_info,
944 const std::string& user_agent,
945 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
947 AsyncPacketSocket* result = next_client_tcp_socket_;
948 next_client_tcp_socket_ = NULL;
949 return result;
950 }
951
952 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
953 next_udp_socket_ = next_udp_socket;
954 }
955 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
956 next_server_tcp_socket_ = next_server_tcp_socket;
957 }
958 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
959 next_client_tcp_socket_ = next_client_tcp_socket;
960 }
961 rtc::AsyncResolverInterface* CreateAsyncResolver() {
962 return NULL;
963 }
964
965 private:
966 AsyncPacketSocket* next_udp_socket_;
967 AsyncPacketSocket* next_server_tcp_socket_;
968 AsyncPacketSocket* next_client_tcp_socket_;
969};
970
971class FakeAsyncPacketSocket : public AsyncPacketSocket {
972 public:
973 // Returns current local address. Address may be set to NULL if the
974 // socket is not bound yet (GetState() returns STATE_BINDING).
975 virtual SocketAddress GetLocalAddress() const {
976 return SocketAddress();
977 }
978
979 // Returns remote address. Returns zeroes if this is not a client TCP socket.
980 virtual SocketAddress GetRemoteAddress() const {
981 return SocketAddress();
982 }
983
984 // Send a packet.
985 virtual int Send(const void *pv, size_t cb,
986 const rtc::PacketOptions& options) {
987 return static_cast<int>(cb);
988 }
989 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
990 const rtc::PacketOptions& options) {
991 return static_cast<int>(cb);
992 }
993 virtual int Close() {
994 return 0;
995 }
996
997 virtual State GetState() const { return state_; }
998 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
999 virtual int SetOption(Socket::Option opt, int value) { return 0; }
1000 virtual int GetError() const { return 0; }
1001 virtual void SetError(int error) { }
1002
1003 void set_state(State state) { state_ = state; }
1004
1005 private:
1006 State state_;
1007};
1008
1009// Local -> XXXX
1010TEST_F(PortTest, TestLocalToLocal) {
1011 TestLocalToLocal();
1012}
1013
1014TEST_F(PortTest, TestLocalToConeNat) {
1015 TestLocalToStun(NAT_OPEN_CONE);
1016}
1017
1018TEST_F(PortTest, TestLocalToARNat) {
1019 TestLocalToStun(NAT_ADDR_RESTRICTED);
1020}
1021
1022TEST_F(PortTest, TestLocalToPRNat) {
1023 TestLocalToStun(NAT_PORT_RESTRICTED);
1024}
1025
1026TEST_F(PortTest, TestLocalToSymNat) {
1027 TestLocalToStun(NAT_SYMMETRIC);
1028}
1029
1030// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1031TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1032 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1033}
1034
1035TEST_F(PortTest, TestLocalToGturn) {
1036 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1037}
1038
1039TEST_F(PortTest, TestLocalToTcpGturn) {
1040 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1041}
1042
1043TEST_F(PortTest, TestLocalToSslTcpGturn) {
1044 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1045}
1046
1047// Cone NAT -> XXXX
1048TEST_F(PortTest, TestConeNatToLocal) {
1049 TestStunToLocal(NAT_OPEN_CONE);
1050}
1051
1052TEST_F(PortTest, TestConeNatToConeNat) {
1053 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1054}
1055
1056TEST_F(PortTest, TestConeNatToARNat) {
1057 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1058}
1059
1060TEST_F(PortTest, TestConeNatToPRNat) {
1061 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1062}
1063
1064TEST_F(PortTest, TestConeNatToSymNat) {
1065 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1066}
1067
1068TEST_F(PortTest, TestConeNatToTurn) {
1069 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1070}
1071
1072TEST_F(PortTest, TestConeNatToGturn) {
1073 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1074}
1075
1076TEST_F(PortTest, TestConeNatToTcpGturn) {
1077 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1078}
1079
1080// Address-restricted NAT -> XXXX
1081TEST_F(PortTest, TestARNatToLocal) {
1082 TestStunToLocal(NAT_ADDR_RESTRICTED);
1083}
1084
1085TEST_F(PortTest, TestARNatToConeNat) {
1086 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1087}
1088
1089TEST_F(PortTest, TestARNatToARNat) {
1090 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1091}
1092
1093TEST_F(PortTest, TestARNatToPRNat) {
1094 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1095}
1096
1097TEST_F(PortTest, TestARNatToSymNat) {
1098 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1099}
1100
1101TEST_F(PortTest, TestARNatToTurn) {
1102 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1103}
1104
1105TEST_F(PortTest, TestARNatToGturn) {
1106 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1107}
1108
1109TEST_F(PortTest, TestARNATNatToTcpGturn) {
1110 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1111}
1112
1113// Port-restricted NAT -> XXXX
1114TEST_F(PortTest, TestPRNatToLocal) {
1115 TestStunToLocal(NAT_PORT_RESTRICTED);
1116}
1117
1118TEST_F(PortTest, TestPRNatToConeNat) {
1119 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1120}
1121
1122TEST_F(PortTest, TestPRNatToARNat) {
1123 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1124}
1125
1126TEST_F(PortTest, TestPRNatToPRNat) {
1127 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1128}
1129
1130TEST_F(PortTest, TestPRNatToSymNat) {
1131 // Will "fail"
1132 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1133}
1134
1135TEST_F(PortTest, TestPRNatToTurn) {
1136 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1137}
1138
1139TEST_F(PortTest, TestPRNatToGturn) {
1140 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1141}
1142
1143TEST_F(PortTest, TestPRNatToTcpGturn) {
1144 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1145}
1146
1147// Symmetric NAT -> XXXX
1148TEST_F(PortTest, TestSymNatToLocal) {
1149 TestStunToLocal(NAT_SYMMETRIC);
1150}
1151
1152TEST_F(PortTest, TestSymNatToConeNat) {
1153 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1154}
1155
1156TEST_F(PortTest, TestSymNatToARNat) {
1157 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1158}
1159
1160TEST_F(PortTest, TestSymNatToPRNat) {
1161 // Will "fail"
1162 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1163}
1164
1165TEST_F(PortTest, TestSymNatToSymNat) {
1166 // Will "fail"
1167 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1168}
1169
1170TEST_F(PortTest, TestSymNatToTurn) {
1171 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1172}
1173
1174TEST_F(PortTest, TestSymNatToGturn) {
1175 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1176}
1177
1178TEST_F(PortTest, TestSymNatToTcpGturn) {
1179 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1180}
1181
1182// Outbound TCP -> XXXX
1183TEST_F(PortTest, TestTcpToTcp) {
1184 TestTcpToTcp();
1185}
1186
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001187TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1188 TestTcpReconnect(false /* ping */, true /* send */);
1189}
1190
1191TEST_F(PortTest, TestTcpReconnectOnPing) {
1192 TestTcpReconnect(true /* ping */, false /* send */);
1193}
1194
1195TEST_F(PortTest, TestTcpReconnectTimeout) {
1196 TestTcpReconnect(false /* ping */, false /* send */);
1197}
1198
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001199// Test when TcpConnection never connects, the OnClose() will be called to
1200// destroy the connection.
1201TEST_F(PortTest, TestTcpNeverConnect) {
1202 Port* port1 = CreateTcpPort(kLocalAddr1);
1203 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1204 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1205
1206 // Set up a channel and ensure the port will be deleted.
1207 TestChannel ch1(port1);
1208 EXPECT_EQ(0, ch1.complete_count());
1209
1210 ch1.Start();
1211 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1212
1213 rtc::scoped_ptr<rtc::AsyncSocket> server(
1214 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1215 // Bind but not listen.
1216 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1217
1218 Candidate c = GetCandidate(port1);
1219 c.set_address(server->GetLocalAddress());
1220
1221 ch1.CreateConnection(c);
1222 EXPECT_TRUE(ch1.conn());
1223 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1224}
1225
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001226/* TODO: Enable these once testrelayserver can accept external TCP.
1227TEST_F(PortTest, TestTcpToTcpRelay) {
1228 TestTcpToRelay(PROTO_TCP);
1229}
1230
1231TEST_F(PortTest, TestTcpToSslTcpRelay) {
1232 TestTcpToRelay(PROTO_SSLTCP);
1233}
1234*/
1235
1236// Outbound SSLTCP -> XXXX
1237/* TODO: Enable these once testrelayserver can accept external SSL.
1238TEST_F(PortTest, TestSslTcpToTcpRelay) {
1239 TestSslTcpToRelay(PROTO_TCP);
1240}
1241
1242TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1243 TestSslTcpToRelay(PROTO_SSLTCP);
1244}
1245*/
1246
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001247// Test that a connection will be dead and deleted if
1248// i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1249// since it was created, or
1250// ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1251// milliseconds since last receiving.
1252TEST_F(PortTest, TestConnectionDead) {
1253 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1254 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1255 TestChannel ch1(port1);
1256 TestChannel ch2(port2);
1257 // Acquire address.
1258 ch1.Start();
1259 ch2.Start();
1260 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1261 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
1262
honghaiz37389b42016-01-04 21:57:33 -08001263 // Test case that the connection has never received anything.
honghaiz34b11eb2016-03-16 08:55:44 -07001264 int64_t before_created = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001265 ch1.CreateConnection(GetCandidate(port2));
honghaiz34b11eb2016-03-16 08:55:44 -07001266 int64_t after_created = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001267 Connection* conn = ch1.conn();
1268 ASSERT(conn != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001269 // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned.
1270 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1271 rtc::Thread::Current()->ProcessMessages(0);
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001272 EXPECT_TRUE(ch1.conn() != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001273 // It is not dead if it is before MIN_CONNECTION_LIFETIME and pruned.
1274 conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1275 conn->Prune();
1276 rtc::Thread::Current()->ProcessMessages(0);
1277 EXPECT_TRUE(ch1.conn() != nullptr);
1278 // It will be dead after MIN_CONNECTION_LIFETIME and pruned.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001279 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1280 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1281
honghaiz37389b42016-01-04 21:57:33 -08001282 // Test case that the connection has received something.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001283 // Create a connection again and receive a ping.
1284 ch1.CreateConnection(GetCandidate(port2));
1285 conn = ch1.conn();
1286 ASSERT(conn != nullptr);
honghaiz34b11eb2016-03-16 08:55:44 -07001287 int64_t before_last_receiving = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001288 conn->ReceivedPing();
honghaiz34b11eb2016-03-16 08:55:44 -07001289 int64_t after_last_receiving = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001290 // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1291 conn->UpdateState(
1292 before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1293 rtc::Thread::Current()->ProcessMessages(100);
1294 EXPECT_TRUE(ch1.conn() != nullptr);
1295 conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1296 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1297}
1298
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001299// This test case verifies standard ICE features in STUN messages. Currently it
1300// verifies Message Integrity attribute in STUN messages and username in STUN
1301// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001302TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001303 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1304 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1305 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1307 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1308 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001309 // Same parameters as TestLocalToLocal above.
1310 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1311}
1312
1313// This test is trying to validate a successful and failure scenario in a
1314// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1315// should remain equal to the request generated by the port and role of port
1316// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001317TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318 rtc::scoped_ptr<TestPort> lport(
1319 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001320 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1321 lport->SetIceTiebreaker(kTiebreaker1);
1322 lport->PrepareAddress();
1323 ASSERT_FALSE(lport->Candidates().empty());
1324 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1325 Port::ORIGIN_MESSAGE);
1326 conn->Ping(0);
1327
1328 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1329 IceMessage* msg = lport->last_stun_msg();
1330 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1331 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1332 lport->last_stun_buf()->Length(),
1333 rtc::PacketTime());
1334 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1335 msg = lport->last_stun_msg();
1336 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1337
1338 // If the tiebreaker value is different from port, we expect a error
1339 // response.
1340 lport->Reset();
1341 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001342 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001343 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1344 Port::ORIGIN_MESSAGE);
1345 conn1->Ping(0);
1346
1347 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1348 msg = lport->last_stun_msg();
1349 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1350 rtc::scoped_ptr<IceMessage> modified_req(
1351 CreateStunMessage(STUN_BINDING_REQUEST));
1352 const StunByteStringAttribute* username_attr = msg->GetByteString(
1353 STUN_ATTR_USERNAME);
1354 modified_req->AddAttribute(new StunByteStringAttribute(
1355 STUN_ATTR_USERNAME, username_attr->GetString()));
1356 // To make sure we receive error response, adding tiebreaker less than
1357 // what's present in request.
1358 modified_req->AddAttribute(new StunUInt64Attribute(
1359 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1360 modified_req->AddMessageIntegrity("lpass");
1361 modified_req->AddFingerprint();
1362
1363 lport->Reset();
1364 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1365 WriteStunMessage(modified_req.get(), buf.get());
1366 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1367 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1368 msg = lport->last_stun_msg();
1369 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1370}
1371
1372// This test verifies role conflict signal is received when there is
1373// conflict in the role. In this case both ports are in controlling and
1374// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1375// value of tiebreaker, when it receives ping request from |rport| it will
1376// send role conflict signal.
1377TEST_F(PortTest, TestIceRoleConflict) {
1378 rtc::scoped_ptr<TestPort> lport(
1379 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001380 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1381 lport->SetIceTiebreaker(kTiebreaker1);
1382 rtc::scoped_ptr<TestPort> rport(
1383 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1385 rport->SetIceTiebreaker(kTiebreaker2);
1386
1387 lport->PrepareAddress();
1388 rport->PrepareAddress();
1389 ASSERT_FALSE(lport->Candidates().empty());
1390 ASSERT_FALSE(rport->Candidates().empty());
1391 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1392 Port::ORIGIN_MESSAGE);
1393 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1394 Port::ORIGIN_MESSAGE);
1395 rconn->Ping(0);
1396
1397 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1398 IceMessage* msg = rport->last_stun_msg();
1399 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1400 // Send rport binding request to lport.
1401 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1402 rport->last_stun_buf()->Length(),
1403 rtc::PacketTime());
1404
1405 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1406 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1407 EXPECT_TRUE(role_conflict());
1408}
1409
1410TEST_F(PortTest, TestTcpNoDelay) {
1411 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001412 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001413 int option_value = -1;
1414 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1415 &option_value);
1416 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1417 ASSERT_EQ(1, option_value);
1418 delete port1;
1419}
1420
1421TEST_F(PortTest, TestDelayedBindingUdp) {
1422 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1423 FakePacketSocketFactory socket_factory;
1424
1425 socket_factory.set_next_udp_socket(socket);
1426 scoped_ptr<UDPPort> port(
1427 CreateUdpPort(kLocalAddr1, &socket_factory));
1428
1429 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1430 port->PrepareAddress();
1431
1432 EXPECT_EQ(0U, port->Candidates().size());
1433 socket->SignalAddressReady(socket, kLocalAddr2);
1434
1435 EXPECT_EQ(1U, port->Candidates().size());
1436}
1437
1438TEST_F(PortTest, TestDelayedBindingTcp) {
1439 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1440 FakePacketSocketFactory socket_factory;
1441
1442 socket_factory.set_next_server_tcp_socket(socket);
1443 scoped_ptr<TCPPort> port(
1444 CreateTcpPort(kLocalAddr1, &socket_factory));
1445
1446 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1447 port->PrepareAddress();
1448
1449 EXPECT_EQ(0U, port->Candidates().size());
1450 socket->SignalAddressReady(socket, kLocalAddr2);
1451
1452 EXPECT_EQ(1U, port->Candidates().size());
1453}
1454
1455void PortTest::TestCrossFamilyPorts(int type) {
1456 FakePacketSocketFactory factory;
1457 scoped_ptr<Port> ports[4];
1458 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1459 SocketAddress("192.168.1.4", 0),
1460 SocketAddress("2001:db8::1", 0),
1461 SocketAddress("2001:db8::2", 0)};
1462 for (int i = 0; i < 4; i++) {
1463 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1464 if (type == SOCK_DGRAM) {
1465 factory.set_next_udp_socket(socket);
1466 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1467 } else if (type == SOCK_STREAM) {
1468 factory.set_next_server_tcp_socket(socket);
1469 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1470 }
1471 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1472 socket->SignalAddressReady(socket, addresses[i]);
1473 ports[i]->PrepareAddress();
1474 }
1475
1476 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1477 if (type == SOCK_STREAM) {
1478 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1479 factory.set_next_client_tcp_socket(clientsocket);
1480 }
1481 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1482 Port::ORIGIN_MESSAGE);
1483 EXPECT_TRUE(NULL == c);
1484 EXPECT_EQ(0U, ports[0]->connections().size());
1485 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1486 Port::ORIGIN_MESSAGE);
1487 EXPECT_FALSE(NULL == c);
1488 EXPECT_EQ(1U, ports[0]->connections().size());
1489
1490 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1491 if (type == SOCK_STREAM) {
1492 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1493 factory.set_next_client_tcp_socket(clientsocket);
1494 }
1495 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1496 Port::ORIGIN_MESSAGE);
1497 EXPECT_TRUE(NULL == c);
1498 EXPECT_EQ(0U, ports[2]->connections().size());
1499 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1500 Port::ORIGIN_MESSAGE);
1501 EXPECT_FALSE(NULL == c);
1502 EXPECT_EQ(1U, ports[2]->connections().size());
1503}
1504
1505TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1506 TestCrossFamilyPorts(SOCK_STREAM);
1507}
1508
1509TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1510 TestCrossFamilyPorts(SOCK_DGRAM);
1511}
1512
Peter Thatcherb8b01432015-07-07 16:45:53 -07001513void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1514 Connection* c = p1->CreateConnection(GetCandidate(p2),
1515 Port::ORIGIN_MESSAGE);
1516 if (can_connect) {
1517 EXPECT_FALSE(NULL == c);
1518 EXPECT_EQ(1U, p1->connections().size());
1519 } else {
1520 EXPECT_TRUE(NULL == c);
1521 EXPECT_EQ(0U, p1->connections().size());
1522 }
1523}
1524
1525TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1526 FakePacketSocketFactory factory;
1527 scoped_ptr<Port> ports[4];
1528 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1529 SocketAddress("fe80::1", 0),
1530 SocketAddress("fe80::2", 0),
1531 SocketAddress("::1", 0)};
1532 for (int i = 0; i < 4; i++) {
1533 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1534 factory.set_next_udp_socket(socket);
1535 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1536 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1537 socket->SignalAddressReady(socket, addresses[i]);
1538 ports[i]->PrepareAddress();
1539 }
1540
1541 Port* standard = ports[0].get();
1542 Port* link_local1 = ports[1].get();
1543 Port* link_local2 = ports[2].get();
1544 Port* localhost = ports[3].get();
1545
1546 ExpectPortsCanConnect(false, link_local1, standard);
1547 ExpectPortsCanConnect(false, standard, link_local1);
1548 ExpectPortsCanConnect(false, link_local1, localhost);
1549 ExpectPortsCanConnect(false, localhost, link_local1);
1550
1551 ExpectPortsCanConnect(true, link_local1, link_local2);
1552 ExpectPortsCanConnect(true, localhost, standard);
1553 ExpectPortsCanConnect(true, standard, localhost);
1554}
1555
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001556// This test verifies DSCP value set through SetOption interface can be
1557// get through DefaultDscpValue.
1558TEST_F(PortTest, TestDefaultDscpValue) {
1559 int dscp;
1560 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1561 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1562 rtc::DSCP_CS6));
1563 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1564 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1565 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1566 rtc::DSCP_AF31));
1567 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1568 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1569 rtc::scoped_ptr<StunPort> stunport(
1570 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1571 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1572 rtc::DSCP_AF41));
1573 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1574 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1575 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1576 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1577 // Socket is created in PrepareAddress.
1578 turnport1->PrepareAddress();
1579 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1580 rtc::DSCP_CS7));
1581 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1582 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1583 // This will verify correct value returned without the socket.
1584 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1585 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1586 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1587 rtc::DSCP_CS6));
1588 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1589 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1590}
1591
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001592// Test sending STUN messages.
1593TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001594 rtc::scoped_ptr<TestPort> lport(
1595 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1596 rtc::scoped_ptr<TestPort> rport(
1597 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001598 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1599 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001600 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1601 rport->SetIceTiebreaker(kTiebreaker2);
1602
1603 // Send a fake ping from lport to rport.
1604 lport->PrepareAddress();
1605 rport->PrepareAddress();
1606 ASSERT_FALSE(rport->Candidates().empty());
1607 Connection* lconn = lport->CreateConnection(
1608 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1609 Connection* rconn = rport->CreateConnection(
1610 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1611 lconn->Ping(0);
1612
1613 // Check that it's a proper BINDING-REQUEST.
1614 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1615 IceMessage* msg = lport->last_stun_msg();
1616 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1617 EXPECT_FALSE(msg->IsLegacy());
1618 const StunByteStringAttribute* username_attr =
1619 msg->GetByteString(STUN_ATTR_USERNAME);
1620 ASSERT_TRUE(username_attr != NULL);
1621 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1622 ASSERT_TRUE(priority_attr != NULL);
1623 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1624 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1625 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1626 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1627 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1628 "rpass"));
1629 const StunUInt64Attribute* ice_controlling_attr =
1630 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1631 ASSERT_TRUE(ice_controlling_attr != NULL);
1632 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1633 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1634 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1635 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1636 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1637 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1638
1639 // Request should not include ping count.
1640 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1641
1642 // Save a copy of the BINDING-REQUEST for use below.
1643 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1644
1645 // Respond with a BINDING-RESPONSE.
1646 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1647 msg = rport->last_stun_msg();
1648 ASSERT_TRUE(msg != NULL);
1649 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1650
1651
1652 EXPECT_FALSE(msg->IsLegacy());
1653 const StunAddressAttribute* addr_attr = msg->GetAddress(
1654 STUN_ATTR_XOR_MAPPED_ADDRESS);
1655 ASSERT_TRUE(addr_attr != NULL);
1656 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1657 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1658 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1659 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1660 "rpass"));
1661 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1662 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1663 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1664 // No USERNAME or PRIORITY in ICE responses.
1665 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1666 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1667 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1668 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1669 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1670 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1671
1672 // Response should not include ping count.
1673 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1674
1675 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1676 // but we can do it here.
1677 rport->SendBindingErrorResponse(request.get(),
1678 lport->Candidates()[0].address(),
1679 STUN_ERROR_SERVER_ERROR,
1680 STUN_ERROR_REASON_SERVER_ERROR);
1681 msg = rport->last_stun_msg();
1682 ASSERT_TRUE(msg != NULL);
1683 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1684 EXPECT_FALSE(msg->IsLegacy());
1685 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1686 ASSERT_TRUE(error_attr != NULL);
1687 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1688 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1689 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1690 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1691 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1692 "rpass"));
1693 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1694 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1695 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1696 // No USERNAME with ICE.
1697 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1698 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1699
1700 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1701 // and (incremented) RETRANSMIT_COUNT attributes.
1702 rport->Reset();
1703 rport->set_send_retransmit_count_attribute(true);
1704 rconn->Ping(0);
1705 rconn->Ping(0);
1706 rconn->Ping(0);
1707 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1708 msg = rport->last_stun_msg();
1709 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1710 const StunUInt64Attribute* ice_controlled_attr =
1711 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1712 ASSERT_TRUE(ice_controlled_attr != NULL);
1713 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1714 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1715
1716 // Request should include ping count.
1717 const StunUInt32Attribute* retransmit_attr =
1718 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1719 ASSERT_TRUE(retransmit_attr != NULL);
1720 EXPECT_EQ(2U, retransmit_attr->value());
1721
1722 // Respond with a BINDING-RESPONSE.
1723 request.reset(CopyStunMessage(msg));
1724 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1725 msg = lport->last_stun_msg();
1726
1727 // Response should include same ping count.
1728 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1729 ASSERT_TRUE(retransmit_attr != NULL);
1730 EXPECT_EQ(2U, retransmit_attr->value());
1731}
1732
1733TEST_F(PortTest, TestUseCandidateAttribute) {
1734 rtc::scoped_ptr<TestPort> lport(
1735 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1736 rtc::scoped_ptr<TestPort> rport(
1737 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001738 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1739 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001740 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1741 rport->SetIceTiebreaker(kTiebreaker2);
1742
1743 // Send a fake ping from lport to rport.
1744 lport->PrepareAddress();
1745 rport->PrepareAddress();
1746 ASSERT_FALSE(rport->Candidates().empty());
1747 Connection* lconn = lport->CreateConnection(
1748 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1749 lconn->Ping(0);
1750 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1751 IceMessage* msg = lport->last_stun_msg();
1752 const StunUInt64Attribute* ice_controlling_attr =
1753 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1754 ASSERT_TRUE(ice_controlling_attr != NULL);
1755 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1756 STUN_ATTR_USE_CANDIDATE);
1757 ASSERT_TRUE(use_candidate_attr != NULL);
1758}
1759
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001760// Test handling STUN messages.
1761TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001762 // Our port will act as the "remote" port.
1763 rtc::scoped_ptr<TestPort> port(
1764 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001765
1766 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1767 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1768 rtc::SocketAddress addr(kLocalAddr1);
1769 std::string username;
1770
1771 // BINDING-REQUEST from local to remote with valid ICE username,
1772 // MESSAGE-INTEGRITY, and FINGERPRINT.
1773 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1774 "rfrag:lfrag"));
1775 in_msg->AddMessageIntegrity("rpass");
1776 in_msg->AddFingerprint();
1777 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001778 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1779 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001780 EXPECT_TRUE(out_msg.get() != NULL);
1781 EXPECT_EQ("lfrag", username);
1782
1783 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1784 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1785 in_msg->AddAttribute(
1786 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1787 in_msg->AddMessageIntegrity("rpass");
1788 in_msg->AddFingerprint();
1789 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001790 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1791 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001792 EXPECT_TRUE(out_msg.get() != NULL);
1793 EXPECT_EQ("", username);
1794
1795 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1796 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1797 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1798 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1799 in_msg->AddFingerprint();
1800 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001801 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1802 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001803 EXPECT_TRUE(out_msg.get() != NULL);
1804 EXPECT_EQ("", username);
1805 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1806 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1807 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1808 out_msg->GetErrorCode()->reason());
1809}
1810
guoweisd12140a2015-09-10 13:32:11 -07001811// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001812TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001813 rtc::scoped_ptr<TestPort> port(
1814 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001815
1816 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1817 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1818 rtc::SocketAddress addr(kLocalAddr1);
1819 std::string username;
1820
1821 // BINDING-REQUEST with no username.
1822 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1823 in_msg->AddMessageIntegrity("rpass");
1824 in_msg->AddFingerprint();
1825 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001826 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1827 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001828 EXPECT_TRUE(out_msg.get() == NULL);
1829 EXPECT_EQ("", username);
1830 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1831
1832 // BINDING-REQUEST with empty username.
1833 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1834 in_msg->AddMessageIntegrity("rpass");
1835 in_msg->AddFingerprint();
1836 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001837 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1838 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001839 EXPECT_TRUE(out_msg.get() == NULL);
1840 EXPECT_EQ("", username);
1841 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1842
1843 // BINDING-REQUEST with too-short username.
1844 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1845 in_msg->AddMessageIntegrity("rpass");
1846 in_msg->AddFingerprint();
1847 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001848 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1849 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001850 EXPECT_TRUE(out_msg.get() == NULL);
1851 EXPECT_EQ("", username);
1852 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1853
1854 // BINDING-REQUEST with reversed username.
1855 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1856 "lfrag:rfrag"));
1857 in_msg->AddMessageIntegrity("rpass");
1858 in_msg->AddFingerprint();
1859 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001860 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1861 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001862 EXPECT_TRUE(out_msg.get() == NULL);
1863 EXPECT_EQ("", username);
1864 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1865
1866 // BINDING-REQUEST with garbage username.
1867 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1868 "abcd:efgh"));
1869 in_msg->AddMessageIntegrity("rpass");
1870 in_msg->AddFingerprint();
1871 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001872 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1873 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001874 EXPECT_TRUE(out_msg.get() == NULL);
1875 EXPECT_EQ("", username);
1876 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1877}
1878
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001879// Test handling STUN messages with missing or malformed M-I.
1880TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001881 // Our port will act as the "remote" port.
1882 rtc::scoped_ptr<TestPort> port(
1883 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001884
1885 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1886 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1887 rtc::SocketAddress addr(kLocalAddr1);
1888 std::string username;
1889
1890 // BINDING-REQUEST from local to remote with valid ICE username and
1891 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1892 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1893 "rfrag:lfrag"));
1894 in_msg->AddFingerprint();
1895 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001896 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1897 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001898 EXPECT_TRUE(out_msg.get() == NULL);
1899 EXPECT_EQ("", username);
1900 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1901
1902 // BINDING-REQUEST from local to remote with valid ICE username and
1903 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1904 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1905 "rfrag:lfrag"));
1906 in_msg->AddMessageIntegrity("invalid");
1907 in_msg->AddFingerprint();
1908 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001909 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1910 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001911 EXPECT_TRUE(out_msg.get() == NULL);
1912 EXPECT_EQ("", username);
1913 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1914
1915 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1916 // by the Connection, not the Port, since they require the remote username.
1917 // Change this test to pass in data via Connection::OnReadPacket instead.
1918}
1919
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001920// Test handling STUN messages with missing or malformed FINGERPRINT.
1921TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001922 // Our port will act as the "remote" port.
1923 rtc::scoped_ptr<TestPort> port(
1924 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001925
1926 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1927 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1928 rtc::SocketAddress addr(kLocalAddr1);
1929 std::string username;
1930
1931 // BINDING-REQUEST from local to remote with valid ICE username and
1932 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1933 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1934 "rfrag:lfrag"));
1935 in_msg->AddMessageIntegrity("rpass");
1936 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001937 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1938 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001939 EXPECT_EQ(0, port->last_stun_error_code());
1940
1941 // Now, add a fingerprint, but munge the message so it's not valid.
1942 in_msg->AddFingerprint();
1943 in_msg->SetTransactionID("TESTTESTBADD");
1944 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001945 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1946 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001947 EXPECT_EQ(0, port->last_stun_error_code());
1948
1949 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1950 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1951 in_msg->AddAttribute(
1952 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1953 in_msg->AddMessageIntegrity("rpass");
1954 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001955 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1956 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001957 EXPECT_EQ(0, port->last_stun_error_code());
1958
1959 // Now, add a fingerprint, but munge the message so it's not valid.
1960 in_msg->AddFingerprint();
1961 in_msg->SetTransactionID("TESTTESTBADD");
1962 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001963 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1964 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001965 EXPECT_EQ(0, port->last_stun_error_code());
1966
1967 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1968 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1969 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1970 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1971 in_msg->AddMessageIntegrity("rpass");
1972 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001973 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1974 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001975 EXPECT_EQ(0, port->last_stun_error_code());
1976
1977 // Now, add a fingerprint, but munge the message so it's not valid.
1978 in_msg->AddFingerprint();
1979 in_msg->SetTransactionID("TESTTESTBADD");
1980 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001981 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1982 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001983 EXPECT_EQ(0, port->last_stun_error_code());
1984}
1985
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001986// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001987// indications are allowed only to the connection which is in read mode.
1988TEST_F(PortTest, TestHandleStunBindingIndication) {
1989 rtc::scoped_ptr<TestPort> lport(
1990 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001991 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1992 lport->SetIceTiebreaker(kTiebreaker1);
1993
1994 // Verifying encoding and decoding STUN indication message.
1995 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1996 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1997 rtc::SocketAddress addr(kLocalAddr1);
1998 std::string username;
1999
2000 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
2001 in_msg->AddFingerprint();
2002 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002003 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2004 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002005 EXPECT_TRUE(out_msg.get() != NULL);
2006 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2007 EXPECT_EQ("", username);
2008
2009 // Verify connection can handle STUN indication and updates
2010 // last_ping_received.
2011 rtc::scoped_ptr<TestPort> rport(
2012 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002013 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2014 rport->SetIceTiebreaker(kTiebreaker2);
2015
2016 lport->PrepareAddress();
2017 rport->PrepareAddress();
2018 ASSERT_FALSE(lport->Candidates().empty());
2019 ASSERT_FALSE(rport->Candidates().empty());
2020
2021 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2022 Port::ORIGIN_MESSAGE);
2023 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2024 Port::ORIGIN_MESSAGE);
2025 rconn->Ping(0);
2026
2027 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2028 IceMessage* msg = rport->last_stun_msg();
2029 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2030 // Send rport binding request to lport.
2031 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
2032 rport->last_stun_buf()->Length(),
2033 rtc::PacketTime());
2034 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2035 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
honghaiz34b11eb2016-03-16 08:55:44 -07002036 int64_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002037
2038 // Adding a delay of 100ms.
2039 rtc::Thread::Current()->ProcessMessages(100);
2040 // Pinging lconn using stun indication message.
2041 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
honghaiz34b11eb2016-03-16 08:55:44 -07002042 int64_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002043 EXPECT_GT(last_ping_received2, last_ping_received1);
2044}
2045
2046TEST_F(PortTest, TestComputeCandidatePriority) {
2047 rtc::scoped_ptr<TestPort> port(
2048 CreateTestPort(kLocalAddr1, "name", "pass"));
2049 port->set_type_preference(90);
2050 port->set_component(177);
2051 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2052 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2053 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2054 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2055 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2056 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2057 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2058 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2059 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2060 // These should all be:
2061 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002062 uint32_t expected_priority_v4 = 1509957199U;
2063 uint32_t expected_priority_v6 = 1509959759U;
2064 uint32_t expected_priority_ula = 1509962319U;
2065 uint32_t expected_priority_v4mapped = expected_priority_v4;
2066 uint32_t expected_priority_v4compat = 1509949775U;
2067 uint32_t expected_priority_6to4 = 1509954639U;
2068 uint32_t expected_priority_teredo = 1509952079U;
2069 uint32_t expected_priority_sitelocal = 1509949775U;
2070 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002071 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2072 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2073 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2074 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2075 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2076 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2077 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2078 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2079 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2080}
2081
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002082// In the case of shared socket, one port may be shared by local and stun.
2083// Test that candidates with different types will have different foundation.
2084TEST_F(PortTest, TestFoundation) {
2085 rtc::scoped_ptr<TestPort> testport(
2086 CreateTestPort(kLocalAddr1, "name", "pass"));
2087 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2088 LOCAL_PORT_TYPE,
2089 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2090 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2091 STUN_PORT_TYPE,
2092 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2093 EXPECT_NE(testport->Candidates()[0].foundation(),
2094 testport->Candidates()[1].foundation());
2095}
2096
2097// This test verifies the foundation of different types of ICE candidates.
2098TEST_F(PortTest, TestCandidateFoundation) {
2099 rtc::scoped_ptr<rtc::NATServer> nat_server(
2100 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2101 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2102 udpport1->PrepareAddress();
2103 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2104 udpport2->PrepareAddress();
2105 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2106 udpport2->Candidates()[0].foundation());
2107 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2108 tcpport1->PrepareAddress();
2109 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2110 tcpport2->PrepareAddress();
2111 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2112 tcpport2->Candidates()[0].foundation());
2113 rtc::scoped_ptr<Port> stunport(
2114 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2115 stunport->PrepareAddress();
2116 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2117 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2118 stunport->Candidates()[0].foundation());
2119 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2120 stunport->Candidates()[0].foundation());
2121 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2122 stunport->Candidates()[0].foundation());
2123 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2124 stunport->Candidates()[0].foundation());
2125 // Verify GTURN candidate foundation.
2126 rtc::scoped_ptr<RelayPort> relayport(
2127 CreateGturnPort(kLocalAddr1));
2128 relayport->AddServerAddress(
2129 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2130 relayport->PrepareAddress();
2131 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2132 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2133 relayport->Candidates()[0].foundation());
2134 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2135 relayport->Candidates()[0].foundation());
2136 // Verifying TURN candidate foundation.
2137 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2138 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2139 turnport1->PrepareAddress();
2140 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2141 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2142 turnport1->Candidates()[0].foundation());
2143 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2144 turnport1->Candidates()[0].foundation());
2145 EXPECT_NE(stunport->Candidates()[0].foundation(),
2146 turnport1->Candidates()[0].foundation());
2147 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2148 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2149 turnport2->PrepareAddress();
2150 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2151 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2152 turnport2->Candidates()[0].foundation());
2153
2154 // Running a second turn server, to get different base IP address.
2155 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2156 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2157 TestTurnServer turn_server2(
2158 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2159 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2160 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2161 kTurnUdpIntAddr2));
2162 turnport3->PrepareAddress();
2163 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2164 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2165 turnport2->Candidates()[0].foundation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08002166
2167 // Start a TCP turn server, and check that two turn candidates have
2168 // different foundations if their relay protocols are different.
2169 TestTurnServer turn_server3(rtc::Thread::Current(), kTurnTcpIntAddr,
2170 kTurnUdpExtAddr, PROTO_TCP);
2171 rtc::scoped_ptr<Port> turnport4(
2172 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_TCP, PROTO_UDP));
2173 turnport4->PrepareAddress();
2174 ASSERT_EQ_WAIT(1U, turnport4->Candidates().size(), kTimeout);
2175 EXPECT_NE(turnport2->Candidates()[0].foundation(),
2176 turnport4->Candidates()[0].foundation());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002177}
2178
2179// This test verifies the related addresses of different types of
2180// ICE candiates.
2181TEST_F(PortTest, TestCandidateRelatedAddress) {
2182 rtc::scoped_ptr<rtc::NATServer> nat_server(
2183 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2184 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2185 udpport->PrepareAddress();
2186 // For UDPPort, related address will be empty.
2187 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2188 // Testing related address for stun candidates.
2189 // For stun candidate related address must be equal to the base
2190 // socket address.
2191 rtc::scoped_ptr<StunPort> stunport(
2192 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2193 stunport->PrepareAddress();
2194 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2195 // Check STUN candidate address.
2196 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2197 kNatAddr1.ipaddr());
2198 // Check STUN candidate related address.
2199 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2200 stunport->GetLocalAddress());
2201 // Verifying the related address for the GTURN candidates.
2202 // NOTE: In case of GTURN related address will be equal to the mapped
2203 // address, but address(mapped) will not be XOR.
2204 rtc::scoped_ptr<RelayPort> relayport(
2205 CreateGturnPort(kLocalAddr1));
2206 relayport->AddServerAddress(
2207 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2208 relayport->PrepareAddress();
2209 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2210 // For Gturn related address is set to "0.0.0.0:0"
2211 EXPECT_EQ(rtc::SocketAddress(),
2212 relayport->Candidates()[0].related_address());
2213 // Verifying the related address for TURN candidate.
2214 // For TURN related address must be equal to the mapped address.
2215 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2216 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2217 turnport->PrepareAddress();
2218 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2219 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2220 turnport->Candidates()[0].address().ipaddr());
2221 EXPECT_EQ(kNatAddr1.ipaddr(),
2222 turnport->Candidates()[0].related_address().ipaddr());
2223}
2224
2225// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002226TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002227 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002228 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002229 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002230 cand2.set_priority(1);
2231 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002232}
2233
2234// Test the Connection priority is calculated correctly.
2235TEST_F(PortTest, TestConnectionPriority) {
2236 rtc::scoped_ptr<TestPort> lport(
2237 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2238 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2239 rtc::scoped_ptr<TestPort> rport(
2240 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2241 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2242 lport->set_component(123);
2243 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2244 rport->set_component(23);
2245 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2246
2247 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2248 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2249
2250 // RFC 5245
2251 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2252 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2253 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2254 Connection* lconn = lport->CreateConnection(
2255 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2256#if defined(WEBRTC_WIN)
2257 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2258#else
2259 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2260#endif
2261
2262 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2263 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2264 Connection* rconn = rport->CreateConnection(
2265 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2266#if defined(WEBRTC_WIN)
2267 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2268#else
2269 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2270#endif
2271}
2272
2273TEST_F(PortTest, TestWritableState) {
2274 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002275 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002276 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002277 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002278
2279 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002280 TestChannel ch1(port1);
2281 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002282
2283 // Acquire addresses.
2284 ch1.Start();
2285 ch2.Start();
2286 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2287 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2288
2289 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002290 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002291 ASSERT_TRUE(ch1.conn() != NULL);
2292 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2293 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2294 ch1.Ping();
2295 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2296
2297 // Data should be unsendable until the connection is accepted.
2298 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002299 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002300 rtc::PacketOptions options;
2301 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2302
2303 // Accept the connection to return the binding response, transition to
2304 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002305 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002306 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2307 kTimeout);
2308 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2309
2310 // Ask the connection to update state as if enough time has passed to lose
2311 // full writability and 5 pings went unresponded to. We'll accomplish the
2312 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002313 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002314 ch1.Ping(i);
2315 }
honghaiz34b11eb2016-03-16 08:55:44 -07002316 int unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002317 ch1.conn()->UpdateState(unreliable_timeout_delay);
2318 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2319
2320 // Data should be able to be sent in this state.
2321 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2322
2323 // And now allow the other side to process the pings and send binding
2324 // responses.
2325 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2326 kTimeout);
2327
2328 // Wait long enough for a full timeout (past however long we've already
2329 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002330 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002331 ch1.Ping(unreliable_timeout_delay + i);
2332 }
2333 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2334 500u);
2335 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2336
2337 // Now that the connection has completely timed out, data send should fail.
2338 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2339
2340 ch1.Stop();
2341 ch2.Stop();
2342}
2343
2344TEST_F(PortTest, TestTimeoutForNeverWritable) {
2345 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002346 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002347 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002348 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002349
2350 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002351 TestChannel ch1(port1);
2352 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002353
2354 // Acquire addresses.
2355 ch1.Start();
2356 ch2.Start();
2357
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002358 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002359 ASSERT_TRUE(ch1.conn() != NULL);
2360 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2361
2362 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002363 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002364 ch1.Ping(i);
2365 }
2366 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2367 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2368}
2369
2370// This test verifies the connection setup between ICEMODE_FULL
2371// and ICEMODE_LITE.
2372// In this test |ch1| behaves like FULL mode client and we have created
2373// port which responds to the ping message just like LITE client.
2374TEST_F(PortTest, TestIceLiteConnectivity) {
2375 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002376 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002377 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2378
2379 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002380 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002381 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2382 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002383 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002384 ch1.SetIceMode(ICEMODE_FULL);
2385
2386 // Start gathering candidates.
2387 ch1.Start();
2388 ice_lite_port->PrepareAddress();
2389
2390 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2391 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2392
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002393 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002394 ASSERT_TRUE(ch1.conn() != NULL);
2395 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2396
2397 // Send ping from full mode client.
2398 // This ping must not have USE_CANDIDATE_ATTR.
2399 ch1.Ping();
2400
2401 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2402 // from port.
2403 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2404 IceMessage* msg = ice_full_port->last_stun_msg();
2405 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2406
2407 // Respond with a BINDING-RESPONSE from litemode client.
2408 // NOTE: Ideally we should't create connection at this stage from lite
2409 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2410 // But we need a connection to send a response message.
2411 ice_lite_port->CreateConnection(
2412 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2413 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2414 ice_lite_port->SendBindingResponse(
2415 request.get(), ice_full_port->Candidates()[0].address());
2416
2417 // Feeding the respone message from litemode to the full mode connection.
2418 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2419 ice_lite_port->last_stun_buf()->Length(),
2420 rtc::PacketTime());
2421 // Verifying full mode connection becomes writable from the response.
2422 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2423 kTimeout);
2424 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2425
2426 // Clear existing stun messsages. Otherwise we will process old stun
2427 // message right after we send ping.
2428 ice_full_port->Reset();
2429 // Send ping. This must have USE_CANDIDATE_ATTR.
2430 ch1.Ping();
2431 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2432 msg = ice_full_port->last_stun_msg();
2433 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2434 ch1.Stop();
2435}
2436
2437// This test case verifies that the CONTROLLING port does not time out.
2438TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002439 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2440 ConnectToSignalDestroyed(port1);
2441 port1->set_timeout_delay(10); // milliseconds
2442 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2443 port1->SetIceTiebreaker(kTiebreaker1);
2444
2445 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2446 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2447 port2->SetIceTiebreaker(kTiebreaker2);
2448
2449 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002450 TestChannel ch1(port1);
2451 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002452
2453 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002454 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002455
2456 // After the connection is destroyed, the port should not be destroyed.
2457 rtc::Thread::Current()->ProcessMessages(kTimeout);
2458 EXPECT_FALSE(destroyed());
2459}
2460
2461// This test case verifies that the CONTROLLED port does time out, but only
2462// after connectivity is lost.
2463TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002464 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2465 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2466 port1->SetIceTiebreaker(kTiebreaker1);
2467
2468 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2469 ConnectToSignalDestroyed(port2);
2470 port2->set_timeout_delay(10); // milliseconds
2471 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2472 port2->SetIceTiebreaker(kTiebreaker2);
2473
2474 // The connection must not be destroyed before a connection is attempted.
2475 EXPECT_FALSE(destroyed());
2476
2477 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2478 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2479
2480 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002481 TestChannel ch1(port1);
2482 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002483
2484 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002485 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002486
2487 // The controlled port should be destroyed after 10 milliseconds.
2488 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2489}
honghaizd0b31432015-09-30 12:42:17 -07002490
2491// This test case verifies that if the role of a port changes from controlled
2492// to controlling after all connections fail, the port will not be destroyed.
2493TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2494 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2495 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2496 port1->SetIceTiebreaker(kTiebreaker1);
2497
2498 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2499 ConnectToSignalDestroyed(port2);
2500 port2->set_timeout_delay(10); // milliseconds
2501 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2502 port2->SetIceTiebreaker(kTiebreaker2);
2503
2504 // The connection must not be destroyed before a connection is attempted.
2505 EXPECT_FALSE(destroyed());
2506
2507 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2508 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2509
2510 // Set up channels and ensure both ports will be deleted.
2511 TestChannel ch1(port1);
2512 TestChannel ch2(port2);
2513
2514 // Simulate a connection that succeeds, and then is destroyed.
2515 StartConnectAndStopChannels(&ch1, &ch2);
2516 // Switch the role after all connections are destroyed.
2517 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2518 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2519 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2520
2521 // After the connection is destroyed, the port should not be destroyed.
2522 rtc::Thread::Current()->ProcessMessages(kTimeout);
2523 EXPECT_FALSE(destroyed());
2524}
Honghai Zhangf9945b22015-12-15 12:20:13 -08002525
2526TEST_F(PortTest, TestSupportsProtocol) {
2527 rtc::scoped_ptr<Port> udp_port(CreateUdpPort(kLocalAddr1));
2528 EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2529 EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2530
2531 rtc::scoped_ptr<Port> stun_port(
2532 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2533 EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2534 EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2535
2536 rtc::scoped_ptr<Port> tcp_port(CreateTcpPort(kLocalAddr1));
2537 EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2538 EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
2539 EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2540
2541 rtc::scoped_ptr<Port> turn_port(
2542 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2543 EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2544 EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2545}