blob: c3e5df653852c528e0e6abf92ab1837256c71e2a [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"
20#include "webrtc/base/crc32.h"
21#include "webrtc/base/gunit.h"
22#include "webrtc/base/helpers.h"
23#include "webrtc/base/logging.h"
24#include "webrtc/base/natserver.h"
25#include "webrtc/base/natsocketfactory.h"
26#include "webrtc/base/physicalsocketserver.h"
27#include "webrtc/base/scoped_ptr.h"
28#include "webrtc/base/socketaddress.h"
29#include "webrtc/base/ssladapter.h"
30#include "webrtc/base/stringutils.h"
31#include "webrtc/base/thread.h"
32#include "webrtc/base/virtualsocketserver.h"
33
34using rtc::AsyncPacketSocket;
35using rtc::ByteBuffer;
36using rtc::NATType;
37using rtc::NAT_OPEN_CONE;
38using rtc::NAT_ADDR_RESTRICTED;
39using rtc::NAT_PORT_RESTRICTED;
40using rtc::NAT_SYMMETRIC;
41using rtc::PacketSocketFactory;
42using rtc::scoped_ptr;
43using rtc::Socket;
44using rtc::SocketAddress;
45using namespace cricket;
46
47static const int kTimeout = 1000;
48static const SocketAddress kLocalAddr1("192.168.1.2", 0);
49static const SocketAddress kLocalAddr2("192.168.1.3", 0);
deadbeefc5d0d952015-07-16 10:22:21 -070050static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
51static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_UDP_PORT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
53static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
54static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
55static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
56static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
57static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
58static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
59static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
60static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
61static const RelayCredentials kRelayCredentials("test", "test");
62
63// TODO: Update these when RFC5245 is completely supported.
64// Magic value of 30 is from RFC3484, for IPv4 addresses.
Peter Boström0c4e06b2015-10-07 12:23:21 +020065static const uint32_t kDefaultPrflxPriority =
66 ICE_TYPE_PREFERENCE_PRFLX << 24 | 30 << 8 |
67 (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69static const int kTiebreaker1 = 11111;
70static const int kTiebreaker2 = 22222;
71
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070072static const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
73
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000074static Candidate GetCandidate(Port* port) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -070075 assert(port->Candidates().size() >= 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000076 return port->Candidates()[0];
77}
78
79static SocketAddress GetAddress(Port* port) {
80 return GetCandidate(port).address();
81}
82
83static IceMessage* CopyStunMessage(const IceMessage* src) {
84 IceMessage* dst = new IceMessage();
85 ByteBuffer buf;
86 src->Write(&buf);
87 dst->Read(&buf);
88 return dst;
89}
90
91static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
92 buf->Resize(0); // clear out any existing buffer contents
93 return msg->Write(buf);
94}
95
96// Stub port class for testing STUN generation and processing.
97class TestPort : public Port {
98 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +000099 TestPort(rtc::Thread* thread,
100 const std::string& type,
101 rtc::PacketSocketFactory* factory,
102 rtc::Network* network,
103 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200104 uint16_t min_port,
105 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000106 const std::string& username_fragment,
107 const std::string& password)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200108 : Port(thread,
109 type,
110 factory,
111 network,
112 ip,
113 min_port,
114 max_port,
115 username_fragment,
116 password) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000117 ~TestPort() {}
118
119 // Expose GetStunMessage so that we can test it.
120 using cricket::Port::GetStunMessage;
121
122 // The last StunMessage that was sent on this Port.
123 // TODO: Make these const; requires changes to SendXXXXResponse.
124 ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
125 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
126 int last_stun_error_code() {
127 int code = 0;
128 if (last_stun_msg_) {
129 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
130 if (error_attr) {
131 code = error_attr->code();
132 }
133 }
134 return code;
135 }
136
137 virtual void PrepareAddress() {
138 rtc::SocketAddress addr(ip(), min_port());
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700139 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 ICE_TYPE_PREFERENCE_HOST, 0, true);
141 }
142
143 // Exposed for testing candidate building.
144 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700145 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 type_preference_, 0, false);
147 }
148 void AddCandidateAddress(const rtc::SocketAddress& addr,
149 const rtc::SocketAddress& base_address,
150 const std::string& type,
151 int type_preference,
152 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700153 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 type_preference, 0, final);
155 }
156
157 virtual Connection* CreateConnection(const Candidate& remote_candidate,
158 CandidateOrigin origin) {
159 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
160 AddConnection(conn);
161 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
162 // in STUN binding requests.
163 conn->set_use_candidate_attr(true);
164 return conn;
165 }
166 virtual int SendTo(
167 const void* data, size_t size, const rtc::SocketAddress& addr,
168 const rtc::PacketOptions& options, bool payload) {
169 if (!payload) {
170 IceMessage* msg = new IceMessage;
171 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
172 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
173 if (!msg->Read(buf)) {
174 delete msg;
175 delete buf;
176 return -1;
177 }
178 buf->SetReadPosition(pos);
179 last_stun_buf_.reset(buf);
180 last_stun_msg_.reset(msg);
181 }
182 return static_cast<int>(size);
183 }
184 virtual int SetOption(rtc::Socket::Option opt, int value) {
185 return 0;
186 }
187 virtual int GetOption(rtc::Socket::Option opt, int* value) {
188 return -1;
189 }
190 virtual int GetError() {
191 return 0;
192 }
193 void Reset() {
194 last_stun_buf_.reset();
195 last_stun_msg_.reset();
196 }
197 void set_type_preference(int type_preference) {
198 type_preference_ = type_preference;
199 }
200
201 private:
202 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
203 rtc::scoped_ptr<IceMessage> last_stun_msg_;
204 int type_preference_;
205};
206
207class TestChannel : public sigslot::has_slots<> {
208 public:
209 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700210 TestChannel(Port* p1)
211 : ice_mode_(ICEMODE_FULL),
212 port_(p1),
213 complete_count_(0),
214 conn_(NULL),
215 remote_request_(),
216 nominated_(false) {
217 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
218 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
219 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 }
221
222 int complete_count() { return complete_count_; }
223 Connection* conn() { return conn_; }
224 const SocketAddress& remote_address() { return remote_address_; }
225 const std::string remote_fragment() { return remote_frag_; }
226
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700227 void Start() { port_->PrepareAddress(); }
228 void CreateConnection(const Candidate& remote_candidate) {
229 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 IceMode remote_ice_mode =
231 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
232 conn_->set_remote_ice_mode(remote_ice_mode);
233 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
234 conn_->SignalStateChange.connect(
235 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700236 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700237 conn_->SignalReadyToSend.connect(this,
238 &TestChannel::OnConnectionReadyToSend);
239 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000240 }
241 void OnConnectionStateChange(Connection* conn) {
242 if (conn->write_state() == Connection::STATE_WRITABLE) {
243 conn->set_use_candidate_attr(true);
244 nominated_ = true;
245 }
246 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700247 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000248 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700249 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700251 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700252 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700253 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000254 remote_request_.reset();
255 }
256 void Ping() {
257 Ping(0);
258 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200259 void Ping(uint32_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700261 if (conn_) {
262 conn_->Destroy();
263 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 }
265
266 void OnPortComplete(Port* port) {
267 complete_count_++;
268 }
269 void SetIceMode(IceMode ice_mode) {
270 ice_mode_ = ice_mode;
271 }
272
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700273 int SendData(const char* data, size_t len) {
274 rtc::PacketOptions options;
275 return conn_->Send(data, len, options);
276 }
277
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000278 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
279 ProtocolType proto,
280 IceMessage* msg, const std::string& rf,
281 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700282 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 if (!remote_address_.IsNil()) {
284 ASSERT_EQ(remote_address_, addr);
285 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 const cricket::StunUInt32Attribute* priority_attr =
287 msg->GetUInt32(STUN_ATTR_PRIORITY);
288 const cricket::StunByteStringAttribute* mi_attr =
289 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
290 const cricket::StunUInt32Attribute* fingerprint_attr =
291 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700292 EXPECT_TRUE(priority_attr != NULL);
293 EXPECT_TRUE(mi_attr != NULL);
294 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 remote_address_ = addr;
296 remote_request_.reset(CopyStunMessage(msg));
297 remote_frag_ = rf;
298 }
299
300 void OnDestroyed(Connection* conn) {
301 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700302 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000303 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700304 // When the connection is destroyed, also clear these fields so future
305 // connections are possible.
306 remote_request_.reset();
307 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 }
309
310 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700311 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000312 ASSERT_EQ(destroyed_src, port);
313 }
314
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700315 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700316
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000317 bool nominated() const { return nominated_; }
318
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700319 void set_connection_ready_to_send(bool ready) {
320 connection_ready_to_send_ = ready;
321 }
322 bool connection_ready_to_send() const {
323 return connection_ready_to_send_;
324 }
325
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700327 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
328 void OnConnectionReadyToSend(Connection* conn) {
329 ASSERT_EQ(conn, conn_);
330 connection_ready_to_send_ = true;
331 }
332
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000333 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700334 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000335
336 int complete_count_;
337 Connection* conn_;
338 SocketAddress remote_address_;
339 rtc::scoped_ptr<StunMessage> remote_request_;
340 std::string remote_frag_;
341 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700342 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000343};
344
345class PortTest : public testing::Test, public sigslot::has_slots<> {
346 public:
347 PortTest()
348 : main_(rtc::Thread::Current()),
349 pss_(new rtc::PhysicalSocketServer),
350 ss_(new rtc::VirtualSocketServer(pss_.get())),
351 ss_scope_(ss_.get()),
352 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
353 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700354 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
355 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 nat_socket_factory1_(&nat_factory1_),
357 nat_socket_factory2_(&nat_factory2_),
358 stun_server_(TestStunServer::Create(main_, kStunAddr)),
359 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700360 relay_server_(main_,
361 kRelayUdpIntAddr,
362 kRelayUdpExtAddr,
363 kRelayTcpIntAddr,
364 kRelayTcpExtAddr,
365 kRelaySslTcpIntAddr,
366 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
368 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000369 role_conflict_(false),
370 destroyed_(false) {
371 network_.AddIP(rtc::IPAddress(INADDR_ANY));
372 }
373
374 protected:
375 void TestLocalToLocal() {
376 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700377 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700379 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
381 }
382 void TestLocalToStun(NATType ntype) {
383 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700384 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000385 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
386 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700387 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 TestConnectivity("udp", port1, StunName(ntype), port2,
389 ntype == NAT_OPEN_CONE, true,
390 ntype != NAT_SYMMETRIC, true);
391 }
392 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
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 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700396 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000397 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
398 rtype == RELAY_GTURN, true, true, true);
399 }
400 void TestStunToLocal(NATType ntype) {
401 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
402 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700403 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700405 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000406 TestConnectivity(StunName(ntype), port1, "udp", port2,
407 true, ntype != NAT_SYMMETRIC, true, true);
408 }
409 void TestStunToStun(NATType ntype1, NATType ntype2) {
410 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
411 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700412 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
414 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700415 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000416 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
417 ntype2 == NAT_OPEN_CONE,
418 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
419 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
420 }
421 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
422 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
423 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700424 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000425 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700426 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000427 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
428 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
429 }
430 void TestTcpToTcp() {
431 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700432 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000433 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700434 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
436 }
437 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
438 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700439 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700441 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
443 rtype == RELAY_GTURN, false, true, true);
444 }
445 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
446 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700447 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700449 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
451 rtype == RELAY_GTURN, false, true, true);
452 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 // helpers for above functions
454 UDPPort* CreateUdpPort(const SocketAddress& addr) {
455 return CreateUdpPort(addr, &socket_factory_);
456 }
457 UDPPort* CreateUdpPort(const SocketAddress& addr,
458 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800459 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
460 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 }
462 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700463 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464 }
465 TCPPort* CreateTcpPort(const SocketAddress& addr,
466 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700467 return TCPPort::Create(main_, socket_factory, &network_,
468 addr.ipaddr(), 0, 0, username_, password_,
469 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000470 }
471 StunPort* CreateStunPort(const SocketAddress& addr,
472 rtc::PacketSocketFactory* factory) {
473 ServerAddresses stun_servers;
474 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700475 return StunPort::Create(main_, factory, &network_,
476 addr.ipaddr(), 0, 0,
477 username_, password_, stun_servers,
478 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 }
480 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
481 ProtocolType int_proto, ProtocolType ext_proto) {
482 if (rtype == RELAY_TURN) {
483 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
484 } else {
485 return CreateGturnPort(addr, int_proto, ext_proto);
486 }
487 }
488 TurnPort* CreateTurnPort(const SocketAddress& addr,
489 PacketSocketFactory* socket_factory,
490 ProtocolType int_proto, ProtocolType ext_proto) {
491 return CreateTurnPort(addr, socket_factory,
492 int_proto, ext_proto, kTurnUdpIntAddr);
493 }
494 TurnPort* CreateTurnPort(const SocketAddress& addr,
495 PacketSocketFactory* socket_factory,
496 ProtocolType int_proto, ProtocolType ext_proto,
497 const rtc::SocketAddress& server_addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700498 return TurnPort::Create(main_, socket_factory, &network_,
499 addr.ipaddr(), 0, 0,
500 username_, password_, ProtocolAddress(
501 server_addr, PROTO_UDP),
502 kRelayCredentials, 0,
503 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504 }
505 RelayPort* CreateGturnPort(const SocketAddress& addr,
506 ProtocolType int_proto, ProtocolType ext_proto) {
507 RelayPort* port = CreateGturnPort(addr);
508 SocketAddress addrs[] =
509 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
510 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
511 return port;
512 }
513 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700514 // TODO(pthatcher): Remove GTURN.
515 return RelayPort::Create(main_, &socket_factory_, &network_,
516 addr.ipaddr(), 0, 0,
517 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000518 // TODO: Add an external address for ext_proto, so that the
519 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000520 }
521 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
522 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700523 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000524 }
525 static const char* StunName(NATType type) {
526 switch (type) {
527 case NAT_OPEN_CONE: return "stun(open cone)";
528 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
529 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
530 case NAT_SYMMETRIC: return "stun(symmetric)";
531 default: return "stun(?)";
532 }
533 }
534 static const char* RelayName(RelayType type, ProtocolType proto) {
535 if (type == RELAY_TURN) {
536 switch (proto) {
537 case PROTO_UDP: return "turn(udp)";
538 case PROTO_TCP: return "turn(tcp)";
539 case PROTO_SSLTCP: return "turn(ssltcp)";
540 default: return "turn(?)";
541 }
542 } else {
543 switch (proto) {
544 case PROTO_UDP: return "gturn(udp)";
545 case PROTO_TCP: return "gturn(tcp)";
546 case PROTO_SSLTCP: return "gturn(ssltcp)";
547 default: return "gturn(?)";
548 }
549 }
550 }
551
552 void TestCrossFamilyPorts(int type);
553
Peter Thatcherb8b01432015-07-07 16:45:53 -0700554 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
555
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 // This does all the work and then deletes |port1| and |port2|.
557 void TestConnectivity(const char* name1, Port* port1,
558 const char* name2, Port* port2,
559 bool accept, bool same_addr1,
560 bool same_addr2, bool possible);
561
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700562 // This connects the provided channels which have already started. |ch1|
563 // should have its Connection created (either through CreateConnection() or
564 // TCP reconnecting mechanism before entering this function.
565 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
566 ASSERT_TRUE(ch1->conn());
567 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
568 ch1->Ping();
569 WAIT(!ch2->remote_address().IsNil(), kTimeout);
570
571 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700572 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700573 ch2->Ping();
574 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
575 kTimeout);
576 }
577
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000578 // This connects and disconnects the provided channels in the same sequence as
579 // TestConnectivity with all options set to |true|. It does not delete either
580 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700581 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
582 // Acquire addresses.
583 ch1->Start();
584 ch2->Start();
585
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700586 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700587 ConnectStartedChannels(ch1, ch2);
588
589 // Destroy the connections.
590 ch1->Stop();
591 ch2->Stop();
592 }
593
594 // This disconnects both end's Connection and make sure ch2 ready for new
595 // connection.
596 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700597 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
598 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
599 ASSERT_TRUE(
600 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
601 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700602
603 // Wait for both OnClose are delivered.
604 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
605 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
606
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700607 // Ensure redundant SignalClose events on TcpConnection won't break tcp
608 // reconnection. Chromium will fire SignalClose for all outstanding IPC
609 // packets during reconnection.
610 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
611 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
612
613 // Speed up destroying ch2's connection such that the test is ready to
614 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700615 ch2->conn()->Destroy();
616 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
617 }
618
619 void TestTcpReconnect(bool ping_after_disconnected,
620 bool send_after_disconnected) {
621 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700622 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700623 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700624 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700625
626 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
627 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
628
629 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700630 TestChannel ch1(port1);
631 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700632 EXPECT_EQ(0, ch1.complete_count());
633 EXPECT_EQ(0, ch2.complete_count());
634
635 ch1.Start();
636 ch2.Start();
637 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
638 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
639
640 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700641 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700642 ConnectStartedChannels(&ch1, &ch2);
643
644 // Shorten the timeout period.
645 const int kTcpReconnectTimeout = kTimeout;
646 static_cast<TCPConnection*>(ch1.conn())
647 ->set_reconnection_timeout(kTcpReconnectTimeout);
648 static_cast<TCPConnection*>(ch2.conn())
649 ->set_reconnection_timeout(kTcpReconnectTimeout);
650
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700651 EXPECT_FALSE(ch1.connection_ready_to_send());
652 EXPECT_FALSE(ch2.connection_ready_to_send());
653
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700654 // Once connected, disconnect them.
655 DisconnectTcpTestChannels(&ch1, &ch2);
656
657 if (send_after_disconnected || ping_after_disconnected) {
658 if (send_after_disconnected) {
659 // First SendData after disconnect should fail but will trigger
660 // reconnect.
661 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
662 }
663
664 if (ping_after_disconnected) {
665 // Ping should trigger reconnect.
666 ch1.Ping();
667 }
668
669 // Wait for channel's outgoing TCPConnection connected.
670 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
671
672 // Verify that we could still connect channels.
673 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700674 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
675 kTcpReconnectTimeout);
676 // Channel2 is the passive one so a new connection is created during
677 // reconnect. This new connection should never have issued EWOULDBLOCK
678 // hence the connection_ready_to_send() should be false.
679 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700680 } else {
681 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700682 // Since the reconnection never happens, the connections should have been
683 // destroyed after the timeout.
684 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
685 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700686 }
687
688 // Tear down and ensure that goes smoothly.
689 ch1.Stop();
690 ch2.Stop();
691 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
692 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
693 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000694
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695 IceMessage* CreateStunMessage(int type) {
696 IceMessage* msg = new IceMessage();
697 msg->SetType(type);
698 msg->SetTransactionID("TESTTESTTEST");
699 return msg;
700 }
701 IceMessage* CreateStunMessageWithUsername(int type,
702 const std::string& username) {
703 IceMessage* msg = CreateStunMessage(type);
704 msg->AddAttribute(
705 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
706 return msg;
707 }
708 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
709 const std::string& username,
710 const std::string& password) {
711 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
712 addr.ipaddr(), 0, 0, username, password);
713 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
714 return port;
715 }
716 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
717 const std::string& username,
718 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719 cricket::IceRole role,
720 int tiebreaker) {
721 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722 port->SetIceRole(role);
723 port->SetIceTiebreaker(tiebreaker);
724 return port;
725 }
726
727 void OnRoleConflict(PortInterface* port) {
728 role_conflict_ = true;
729 }
730 bool role_conflict() const { return role_conflict_; }
731
732 void ConnectToSignalDestroyed(PortInterface* port) {
733 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
734 }
735
736 void OnDestroyed(PortInterface* port) {
737 destroyed_ = true;
738 }
739 bool destroyed() const { return destroyed_; }
740
741 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
742 return &nat_socket_factory1_;
743 }
744
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700745 protected:
746 rtc::VirtualSocketServer* vss() { return ss_.get(); }
747
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748 private:
749 rtc::Thread* main_;
750 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
751 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
752 rtc::SocketServerScope ss_scope_;
753 rtc::Network network_;
754 rtc::BasicPacketSocketFactory socket_factory_;
755 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
756 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
757 rtc::NATSocketFactory nat_factory1_;
758 rtc::NATSocketFactory nat_factory2_;
759 rtc::BasicPacketSocketFactory nat_socket_factory1_;
760 rtc::BasicPacketSocketFactory nat_socket_factory2_;
761 scoped_ptr<TestStunServer> stun_server_;
762 TestTurnServer turn_server_;
763 TestRelayServer relay_server_;
764 std::string username_;
765 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000766 bool role_conflict_;
767 bool destroyed_;
768};
769
770void PortTest::TestConnectivity(const char* name1, Port* port1,
771 const char* name2, Port* port2,
772 bool accept, bool same_addr1,
773 bool same_addr2, bool possible) {
774 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
775 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
776 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
777
778 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700779 TestChannel ch1(port1);
780 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000781 EXPECT_EQ(0, ch1.complete_count());
782 EXPECT_EQ(0, ch2.complete_count());
783
784 // Acquire addresses.
785 ch1.Start();
786 ch2.Start();
787 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
788 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
789
790 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700791 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792 ASSERT_TRUE(ch1.conn() != NULL);
793 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
794 ch1.Ping();
795 WAIT(!ch2.remote_address().IsNil(), kTimeout);
796
797 if (accept) {
798 // We are able to send a ping from src to dst. This is the case when
799 // sending to UDP ports and cone NATs.
800 EXPECT_TRUE(ch1.remote_address().IsNil());
801 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
802
803 // Ensure the ping came from the same address used for src.
804 // This is the case unless the source NAT was symmetric.
805 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
806 EXPECT_TRUE(same_addr2);
807
808 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700809 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000810 ASSERT_TRUE(ch2.conn() != NULL);
811 ch2.Ping();
812 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
813 kTimeout);
814 } else {
815 // We can't send a ping from src to dst, so flip it around. This will happen
816 // when the destination NAT is addr/port restricted or symmetric.
817 EXPECT_TRUE(ch1.remote_address().IsNil());
818 EXPECT_TRUE(ch2.remote_address().IsNil());
819
820 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700821 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822 ASSERT_TRUE(ch2.conn() != NULL);
823 ch2.Ping();
824 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
825
826 if (same_addr1 && same_addr2) {
827 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700828 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000829 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
830
831 // First connection may not be writable if the first ping did not get
832 // through. So we will have to do another.
833 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
834 ch1.Ping();
835 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
836 kTimeout);
837 }
838 } else if (!same_addr1 && possible) {
839 // The new ping went to the candidate address, but that address was bad.
840 // This will happen when the source NAT is symmetric.
841 EXPECT_TRUE(ch1.remote_address().IsNil());
842 EXPECT_TRUE(ch2.remote_address().IsNil());
843
844 // However, since we have now sent a ping to the source IP, we should be
845 // able to get a ping from it. This gives us the real source address.
846 ch1.Ping();
847 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700848 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 EXPECT_TRUE(ch1.remote_address().IsNil());
850
851 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700852 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 ASSERT_TRUE(ch2.conn() != NULL);
854 ch2.Ping();
855 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
856 kTimeout);
857 } else if (!same_addr2 && possible) {
858 // The new ping came in, but from an unexpected address. This will happen
859 // when the destination NAT is symmetric.
860 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700861 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862
863 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700864 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000865 ch1.Ping();
866 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
867 kTimeout);
868 } else { // (!possible)
869 // There should be s no way for the pings to reach each other. Check it.
870 EXPECT_TRUE(ch1.remote_address().IsNil());
871 EXPECT_TRUE(ch2.remote_address().IsNil());
872 ch1.Ping();
873 WAIT(!ch2.remote_address().IsNil(), kTimeout);
874 EXPECT_TRUE(ch1.remote_address().IsNil());
875 EXPECT_TRUE(ch2.remote_address().IsNil());
876 }
877 }
878
879 // Everything should be good, unless we know the situation is impossible.
880 ASSERT_TRUE(ch1.conn() != NULL);
881 ASSERT_TRUE(ch2.conn() != NULL);
882 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700883 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700885 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000886 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
887 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700888 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700890 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
892 }
893
894 // Tear down and ensure that goes smoothly.
895 ch1.Stop();
896 ch2.Stop();
897 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
898 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
899}
900
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901class FakePacketSocketFactory : public rtc::PacketSocketFactory {
902 public:
903 FakePacketSocketFactory()
904 : next_udp_socket_(NULL),
905 next_server_tcp_socket_(NULL),
906 next_client_tcp_socket_(NULL) {
907 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000908 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000910 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200911 uint16_t min_port,
912 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 EXPECT_TRUE(next_udp_socket_ != NULL);
914 AsyncPacketSocket* result = next_udp_socket_;
915 next_udp_socket_ = NULL;
916 return result;
917 }
918
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000919 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200920 uint16_t min_port,
921 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000922 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
924 AsyncPacketSocket* result = next_server_tcp_socket_;
925 next_server_tcp_socket_ = NULL;
926 return result;
927 }
928
929 // TODO: |proxy_info| and |user_agent| should be set
930 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000931 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
932 const SocketAddress& remote_address,
933 const rtc::ProxyInfo& proxy_info,
934 const std::string& user_agent,
935 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
937 AsyncPacketSocket* result = next_client_tcp_socket_;
938 next_client_tcp_socket_ = NULL;
939 return result;
940 }
941
942 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
943 next_udp_socket_ = next_udp_socket;
944 }
945 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
946 next_server_tcp_socket_ = next_server_tcp_socket;
947 }
948 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
949 next_client_tcp_socket_ = next_client_tcp_socket;
950 }
951 rtc::AsyncResolverInterface* CreateAsyncResolver() {
952 return NULL;
953 }
954
955 private:
956 AsyncPacketSocket* next_udp_socket_;
957 AsyncPacketSocket* next_server_tcp_socket_;
958 AsyncPacketSocket* next_client_tcp_socket_;
959};
960
961class FakeAsyncPacketSocket : public AsyncPacketSocket {
962 public:
963 // Returns current local address. Address may be set to NULL if the
964 // socket is not bound yet (GetState() returns STATE_BINDING).
965 virtual SocketAddress GetLocalAddress() const {
966 return SocketAddress();
967 }
968
969 // Returns remote address. Returns zeroes if this is not a client TCP socket.
970 virtual SocketAddress GetRemoteAddress() const {
971 return SocketAddress();
972 }
973
974 // Send a packet.
975 virtual int Send(const void *pv, size_t cb,
976 const rtc::PacketOptions& options) {
977 return static_cast<int>(cb);
978 }
979 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
980 const rtc::PacketOptions& options) {
981 return static_cast<int>(cb);
982 }
983 virtual int Close() {
984 return 0;
985 }
986
987 virtual State GetState() const { return state_; }
988 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
989 virtual int SetOption(Socket::Option opt, int value) { return 0; }
990 virtual int GetError() const { return 0; }
991 virtual void SetError(int error) { }
992
993 void set_state(State state) { state_ = state; }
994
995 private:
996 State state_;
997};
998
999// Local -> XXXX
1000TEST_F(PortTest, TestLocalToLocal) {
1001 TestLocalToLocal();
1002}
1003
1004TEST_F(PortTest, TestLocalToConeNat) {
1005 TestLocalToStun(NAT_OPEN_CONE);
1006}
1007
1008TEST_F(PortTest, TestLocalToARNat) {
1009 TestLocalToStun(NAT_ADDR_RESTRICTED);
1010}
1011
1012TEST_F(PortTest, TestLocalToPRNat) {
1013 TestLocalToStun(NAT_PORT_RESTRICTED);
1014}
1015
1016TEST_F(PortTest, TestLocalToSymNat) {
1017 TestLocalToStun(NAT_SYMMETRIC);
1018}
1019
1020// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1021TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1022 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1023}
1024
1025TEST_F(PortTest, TestLocalToGturn) {
1026 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1027}
1028
1029TEST_F(PortTest, TestLocalToTcpGturn) {
1030 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1031}
1032
1033TEST_F(PortTest, TestLocalToSslTcpGturn) {
1034 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1035}
1036
1037// Cone NAT -> XXXX
1038TEST_F(PortTest, TestConeNatToLocal) {
1039 TestStunToLocal(NAT_OPEN_CONE);
1040}
1041
1042TEST_F(PortTest, TestConeNatToConeNat) {
1043 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1044}
1045
1046TEST_F(PortTest, TestConeNatToARNat) {
1047 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1048}
1049
1050TEST_F(PortTest, TestConeNatToPRNat) {
1051 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1052}
1053
1054TEST_F(PortTest, TestConeNatToSymNat) {
1055 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1056}
1057
1058TEST_F(PortTest, TestConeNatToTurn) {
1059 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1060}
1061
1062TEST_F(PortTest, TestConeNatToGturn) {
1063 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1064}
1065
1066TEST_F(PortTest, TestConeNatToTcpGturn) {
1067 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1068}
1069
1070// Address-restricted NAT -> XXXX
1071TEST_F(PortTest, TestARNatToLocal) {
1072 TestStunToLocal(NAT_ADDR_RESTRICTED);
1073}
1074
1075TEST_F(PortTest, TestARNatToConeNat) {
1076 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1077}
1078
1079TEST_F(PortTest, TestARNatToARNat) {
1080 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1081}
1082
1083TEST_F(PortTest, TestARNatToPRNat) {
1084 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1085}
1086
1087TEST_F(PortTest, TestARNatToSymNat) {
1088 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1089}
1090
1091TEST_F(PortTest, TestARNatToTurn) {
1092 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1093}
1094
1095TEST_F(PortTest, TestARNatToGturn) {
1096 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1097}
1098
1099TEST_F(PortTest, TestARNATNatToTcpGturn) {
1100 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1101}
1102
1103// Port-restricted NAT -> XXXX
1104TEST_F(PortTest, TestPRNatToLocal) {
1105 TestStunToLocal(NAT_PORT_RESTRICTED);
1106}
1107
1108TEST_F(PortTest, TestPRNatToConeNat) {
1109 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1110}
1111
1112TEST_F(PortTest, TestPRNatToARNat) {
1113 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1114}
1115
1116TEST_F(PortTest, TestPRNatToPRNat) {
1117 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1118}
1119
1120TEST_F(PortTest, TestPRNatToSymNat) {
1121 // Will "fail"
1122 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1123}
1124
1125TEST_F(PortTest, TestPRNatToTurn) {
1126 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1127}
1128
1129TEST_F(PortTest, TestPRNatToGturn) {
1130 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1131}
1132
1133TEST_F(PortTest, TestPRNatToTcpGturn) {
1134 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1135}
1136
1137// Symmetric NAT -> XXXX
1138TEST_F(PortTest, TestSymNatToLocal) {
1139 TestStunToLocal(NAT_SYMMETRIC);
1140}
1141
1142TEST_F(PortTest, TestSymNatToConeNat) {
1143 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1144}
1145
1146TEST_F(PortTest, TestSymNatToARNat) {
1147 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1148}
1149
1150TEST_F(PortTest, TestSymNatToPRNat) {
1151 // Will "fail"
1152 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1153}
1154
1155TEST_F(PortTest, TestSymNatToSymNat) {
1156 // Will "fail"
1157 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1158}
1159
1160TEST_F(PortTest, TestSymNatToTurn) {
1161 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1162}
1163
1164TEST_F(PortTest, TestSymNatToGturn) {
1165 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1166}
1167
1168TEST_F(PortTest, TestSymNatToTcpGturn) {
1169 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1170}
1171
1172// Outbound TCP -> XXXX
1173TEST_F(PortTest, TestTcpToTcp) {
1174 TestTcpToTcp();
1175}
1176
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001177TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1178 TestTcpReconnect(false /* ping */, true /* send */);
1179}
1180
1181TEST_F(PortTest, TestTcpReconnectOnPing) {
1182 TestTcpReconnect(true /* ping */, false /* send */);
1183}
1184
1185TEST_F(PortTest, TestTcpReconnectTimeout) {
1186 TestTcpReconnect(false /* ping */, false /* send */);
1187}
1188
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001189// Test when TcpConnection never connects, the OnClose() will be called to
1190// destroy the connection.
1191TEST_F(PortTest, TestTcpNeverConnect) {
1192 Port* port1 = CreateTcpPort(kLocalAddr1);
1193 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1194 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1195
1196 // Set up a channel and ensure the port will be deleted.
1197 TestChannel ch1(port1);
1198 EXPECT_EQ(0, ch1.complete_count());
1199
1200 ch1.Start();
1201 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1202
1203 rtc::scoped_ptr<rtc::AsyncSocket> server(
1204 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1205 // Bind but not listen.
1206 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1207
1208 Candidate c = GetCandidate(port1);
1209 c.set_address(server->GetLocalAddress());
1210
1211 ch1.CreateConnection(c);
1212 EXPECT_TRUE(ch1.conn());
1213 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1214}
1215
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001216/* TODO: Enable these once testrelayserver can accept external TCP.
1217TEST_F(PortTest, TestTcpToTcpRelay) {
1218 TestTcpToRelay(PROTO_TCP);
1219}
1220
1221TEST_F(PortTest, TestTcpToSslTcpRelay) {
1222 TestTcpToRelay(PROTO_SSLTCP);
1223}
1224*/
1225
1226// Outbound SSLTCP -> XXXX
1227/* TODO: Enable these once testrelayserver can accept external SSL.
1228TEST_F(PortTest, TestSslTcpToTcpRelay) {
1229 TestSslTcpToRelay(PROTO_TCP);
1230}
1231
1232TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1233 TestSslTcpToRelay(PROTO_SSLTCP);
1234}
1235*/
1236
1237// This test case verifies standard ICE features in STUN messages. Currently it
1238// verifies Message Integrity attribute in STUN messages and username in STUN
1239// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001240TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001241 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1242 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1243 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1245 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1246 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001247 // Same parameters as TestLocalToLocal above.
1248 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1249}
1250
1251// This test is trying to validate a successful and failure scenario in a
1252// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1253// should remain equal to the request generated by the port and role of port
1254// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001255TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001256 rtc::scoped_ptr<TestPort> lport(
1257 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001258 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1259 lport->SetIceTiebreaker(kTiebreaker1);
1260 lport->PrepareAddress();
1261 ASSERT_FALSE(lport->Candidates().empty());
1262 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1263 Port::ORIGIN_MESSAGE);
1264 conn->Ping(0);
1265
1266 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1267 IceMessage* msg = lport->last_stun_msg();
1268 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1269 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1270 lport->last_stun_buf()->Length(),
1271 rtc::PacketTime());
1272 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1273 msg = lport->last_stun_msg();
1274 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1275
1276 // If the tiebreaker value is different from port, we expect a error
1277 // response.
1278 lport->Reset();
1279 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001280 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001281 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1282 Port::ORIGIN_MESSAGE);
1283 conn1->Ping(0);
1284
1285 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1286 msg = lport->last_stun_msg();
1287 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1288 rtc::scoped_ptr<IceMessage> modified_req(
1289 CreateStunMessage(STUN_BINDING_REQUEST));
1290 const StunByteStringAttribute* username_attr = msg->GetByteString(
1291 STUN_ATTR_USERNAME);
1292 modified_req->AddAttribute(new StunByteStringAttribute(
1293 STUN_ATTR_USERNAME, username_attr->GetString()));
1294 // To make sure we receive error response, adding tiebreaker less than
1295 // what's present in request.
1296 modified_req->AddAttribute(new StunUInt64Attribute(
1297 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1298 modified_req->AddMessageIntegrity("lpass");
1299 modified_req->AddFingerprint();
1300
1301 lport->Reset();
1302 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1303 WriteStunMessage(modified_req.get(), buf.get());
1304 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1305 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1306 msg = lport->last_stun_msg();
1307 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1308}
1309
1310// This test verifies role conflict signal is received when there is
1311// conflict in the role. In this case both ports are in controlling and
1312// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1313// value of tiebreaker, when it receives ping request from |rport| it will
1314// send role conflict signal.
1315TEST_F(PortTest, TestIceRoleConflict) {
1316 rtc::scoped_ptr<TestPort> lport(
1317 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1319 lport->SetIceTiebreaker(kTiebreaker1);
1320 rtc::scoped_ptr<TestPort> rport(
1321 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1323 rport->SetIceTiebreaker(kTiebreaker2);
1324
1325 lport->PrepareAddress();
1326 rport->PrepareAddress();
1327 ASSERT_FALSE(lport->Candidates().empty());
1328 ASSERT_FALSE(rport->Candidates().empty());
1329 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1330 Port::ORIGIN_MESSAGE);
1331 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1332 Port::ORIGIN_MESSAGE);
1333 rconn->Ping(0);
1334
1335 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1336 IceMessage* msg = rport->last_stun_msg();
1337 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1338 // Send rport binding request to lport.
1339 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1340 rport->last_stun_buf()->Length(),
1341 rtc::PacketTime());
1342
1343 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1344 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1345 EXPECT_TRUE(role_conflict());
1346}
1347
1348TEST_F(PortTest, TestTcpNoDelay) {
1349 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001350 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001351 int option_value = -1;
1352 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1353 &option_value);
1354 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1355 ASSERT_EQ(1, option_value);
1356 delete port1;
1357}
1358
1359TEST_F(PortTest, TestDelayedBindingUdp) {
1360 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1361 FakePacketSocketFactory socket_factory;
1362
1363 socket_factory.set_next_udp_socket(socket);
1364 scoped_ptr<UDPPort> port(
1365 CreateUdpPort(kLocalAddr1, &socket_factory));
1366
1367 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1368 port->PrepareAddress();
1369
1370 EXPECT_EQ(0U, port->Candidates().size());
1371 socket->SignalAddressReady(socket, kLocalAddr2);
1372
1373 EXPECT_EQ(1U, port->Candidates().size());
1374}
1375
1376TEST_F(PortTest, TestDelayedBindingTcp) {
1377 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1378 FakePacketSocketFactory socket_factory;
1379
1380 socket_factory.set_next_server_tcp_socket(socket);
1381 scoped_ptr<TCPPort> port(
1382 CreateTcpPort(kLocalAddr1, &socket_factory));
1383
1384 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1385 port->PrepareAddress();
1386
1387 EXPECT_EQ(0U, port->Candidates().size());
1388 socket->SignalAddressReady(socket, kLocalAddr2);
1389
1390 EXPECT_EQ(1U, port->Candidates().size());
1391}
1392
1393void PortTest::TestCrossFamilyPorts(int type) {
1394 FakePacketSocketFactory factory;
1395 scoped_ptr<Port> ports[4];
1396 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1397 SocketAddress("192.168.1.4", 0),
1398 SocketAddress("2001:db8::1", 0),
1399 SocketAddress("2001:db8::2", 0)};
1400 for (int i = 0; i < 4; i++) {
1401 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1402 if (type == SOCK_DGRAM) {
1403 factory.set_next_udp_socket(socket);
1404 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1405 } else if (type == SOCK_STREAM) {
1406 factory.set_next_server_tcp_socket(socket);
1407 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1408 }
1409 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1410 socket->SignalAddressReady(socket, addresses[i]);
1411 ports[i]->PrepareAddress();
1412 }
1413
1414 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1415 if (type == SOCK_STREAM) {
1416 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1417 factory.set_next_client_tcp_socket(clientsocket);
1418 }
1419 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1420 Port::ORIGIN_MESSAGE);
1421 EXPECT_TRUE(NULL == c);
1422 EXPECT_EQ(0U, ports[0]->connections().size());
1423 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1424 Port::ORIGIN_MESSAGE);
1425 EXPECT_FALSE(NULL == c);
1426 EXPECT_EQ(1U, ports[0]->connections().size());
1427
1428 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1429 if (type == SOCK_STREAM) {
1430 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1431 factory.set_next_client_tcp_socket(clientsocket);
1432 }
1433 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1434 Port::ORIGIN_MESSAGE);
1435 EXPECT_TRUE(NULL == c);
1436 EXPECT_EQ(0U, ports[2]->connections().size());
1437 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1438 Port::ORIGIN_MESSAGE);
1439 EXPECT_FALSE(NULL == c);
1440 EXPECT_EQ(1U, ports[2]->connections().size());
1441}
1442
1443TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1444 TestCrossFamilyPorts(SOCK_STREAM);
1445}
1446
1447TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1448 TestCrossFamilyPorts(SOCK_DGRAM);
1449}
1450
Peter Thatcherb8b01432015-07-07 16:45:53 -07001451void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1452 Connection* c = p1->CreateConnection(GetCandidate(p2),
1453 Port::ORIGIN_MESSAGE);
1454 if (can_connect) {
1455 EXPECT_FALSE(NULL == c);
1456 EXPECT_EQ(1U, p1->connections().size());
1457 } else {
1458 EXPECT_TRUE(NULL == c);
1459 EXPECT_EQ(0U, p1->connections().size());
1460 }
1461}
1462
1463TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1464 FakePacketSocketFactory factory;
1465 scoped_ptr<Port> ports[4];
1466 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1467 SocketAddress("fe80::1", 0),
1468 SocketAddress("fe80::2", 0),
1469 SocketAddress("::1", 0)};
1470 for (int i = 0; i < 4; i++) {
1471 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1472 factory.set_next_udp_socket(socket);
1473 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1474 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1475 socket->SignalAddressReady(socket, addresses[i]);
1476 ports[i]->PrepareAddress();
1477 }
1478
1479 Port* standard = ports[0].get();
1480 Port* link_local1 = ports[1].get();
1481 Port* link_local2 = ports[2].get();
1482 Port* localhost = ports[3].get();
1483
1484 ExpectPortsCanConnect(false, link_local1, standard);
1485 ExpectPortsCanConnect(false, standard, link_local1);
1486 ExpectPortsCanConnect(false, link_local1, localhost);
1487 ExpectPortsCanConnect(false, localhost, link_local1);
1488
1489 ExpectPortsCanConnect(true, link_local1, link_local2);
1490 ExpectPortsCanConnect(true, localhost, standard);
1491 ExpectPortsCanConnect(true, standard, localhost);
1492}
1493
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001494// This test verifies DSCP value set through SetOption interface can be
1495// get through DefaultDscpValue.
1496TEST_F(PortTest, TestDefaultDscpValue) {
1497 int dscp;
1498 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1499 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1500 rtc::DSCP_CS6));
1501 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1502 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1503 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1504 rtc::DSCP_AF31));
1505 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1506 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1507 rtc::scoped_ptr<StunPort> stunport(
1508 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1509 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1510 rtc::DSCP_AF41));
1511 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1512 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1513 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1514 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1515 // Socket is created in PrepareAddress.
1516 turnport1->PrepareAddress();
1517 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1518 rtc::DSCP_CS7));
1519 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1520 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1521 // This will verify correct value returned without the socket.
1522 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1523 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1524 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1525 rtc::DSCP_CS6));
1526 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1527 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1528}
1529
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001530// Test sending STUN messages.
1531TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001532 rtc::scoped_ptr<TestPort> lport(
1533 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1534 rtc::scoped_ptr<TestPort> rport(
1535 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001536 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1537 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001538 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1539 rport->SetIceTiebreaker(kTiebreaker2);
1540
1541 // Send a fake ping from lport to rport.
1542 lport->PrepareAddress();
1543 rport->PrepareAddress();
1544 ASSERT_FALSE(rport->Candidates().empty());
1545 Connection* lconn = lport->CreateConnection(
1546 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1547 Connection* rconn = rport->CreateConnection(
1548 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1549 lconn->Ping(0);
1550
1551 // Check that it's a proper BINDING-REQUEST.
1552 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1553 IceMessage* msg = lport->last_stun_msg();
1554 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1555 EXPECT_FALSE(msg->IsLegacy());
1556 const StunByteStringAttribute* username_attr =
1557 msg->GetByteString(STUN_ATTR_USERNAME);
1558 ASSERT_TRUE(username_attr != NULL);
1559 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1560 ASSERT_TRUE(priority_attr != NULL);
1561 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1562 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1563 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1564 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1565 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1566 "rpass"));
1567 const StunUInt64Attribute* ice_controlling_attr =
1568 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1569 ASSERT_TRUE(ice_controlling_attr != NULL);
1570 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1571 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1572 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1573 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1574 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1575 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1576
1577 // Request should not include ping count.
1578 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1579
1580 // Save a copy of the BINDING-REQUEST for use below.
1581 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1582
1583 // Respond with a BINDING-RESPONSE.
1584 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1585 msg = rport->last_stun_msg();
1586 ASSERT_TRUE(msg != NULL);
1587 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1588
1589
1590 EXPECT_FALSE(msg->IsLegacy());
1591 const StunAddressAttribute* addr_attr = msg->GetAddress(
1592 STUN_ATTR_XOR_MAPPED_ADDRESS);
1593 ASSERT_TRUE(addr_attr != NULL);
1594 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1595 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1596 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1597 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1598 "rpass"));
1599 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1600 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1601 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1602 // No USERNAME or PRIORITY in ICE responses.
1603 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1604 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1605 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1606 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1607 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1608 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1609
1610 // Response should not include ping count.
1611 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1612
1613 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1614 // but we can do it here.
1615 rport->SendBindingErrorResponse(request.get(),
1616 lport->Candidates()[0].address(),
1617 STUN_ERROR_SERVER_ERROR,
1618 STUN_ERROR_REASON_SERVER_ERROR);
1619 msg = rport->last_stun_msg();
1620 ASSERT_TRUE(msg != NULL);
1621 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1622 EXPECT_FALSE(msg->IsLegacy());
1623 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1624 ASSERT_TRUE(error_attr != NULL);
1625 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1626 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1627 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1628 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1629 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1630 "rpass"));
1631 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1632 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1633 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1634 // No USERNAME with ICE.
1635 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1636 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1637
1638 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1639 // and (incremented) RETRANSMIT_COUNT attributes.
1640 rport->Reset();
1641 rport->set_send_retransmit_count_attribute(true);
1642 rconn->Ping(0);
1643 rconn->Ping(0);
1644 rconn->Ping(0);
1645 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1646 msg = rport->last_stun_msg();
1647 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1648 const StunUInt64Attribute* ice_controlled_attr =
1649 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1650 ASSERT_TRUE(ice_controlled_attr != NULL);
1651 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1652 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1653
1654 // Request should include ping count.
1655 const StunUInt32Attribute* retransmit_attr =
1656 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1657 ASSERT_TRUE(retransmit_attr != NULL);
1658 EXPECT_EQ(2U, retransmit_attr->value());
1659
1660 // Respond with a BINDING-RESPONSE.
1661 request.reset(CopyStunMessage(msg));
1662 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1663 msg = lport->last_stun_msg();
1664
1665 // Response should include same ping count.
1666 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1667 ASSERT_TRUE(retransmit_attr != NULL);
1668 EXPECT_EQ(2U, retransmit_attr->value());
1669}
1670
1671TEST_F(PortTest, TestUseCandidateAttribute) {
1672 rtc::scoped_ptr<TestPort> lport(
1673 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1674 rtc::scoped_ptr<TestPort> rport(
1675 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001676 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1677 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001678 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1679 rport->SetIceTiebreaker(kTiebreaker2);
1680
1681 // Send a fake ping from lport to rport.
1682 lport->PrepareAddress();
1683 rport->PrepareAddress();
1684 ASSERT_FALSE(rport->Candidates().empty());
1685 Connection* lconn = lport->CreateConnection(
1686 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1687 lconn->Ping(0);
1688 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1689 IceMessage* msg = lport->last_stun_msg();
1690 const StunUInt64Attribute* ice_controlling_attr =
1691 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1692 ASSERT_TRUE(ice_controlling_attr != NULL);
1693 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1694 STUN_ATTR_USE_CANDIDATE);
1695 ASSERT_TRUE(use_candidate_attr != NULL);
1696}
1697
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001698// Test handling STUN messages.
1699TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001700 // Our port will act as the "remote" port.
1701 rtc::scoped_ptr<TestPort> port(
1702 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001703
1704 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1705 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1706 rtc::SocketAddress addr(kLocalAddr1);
1707 std::string username;
1708
1709 // BINDING-REQUEST from local to remote with valid ICE username,
1710 // MESSAGE-INTEGRITY, and FINGERPRINT.
1711 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1712 "rfrag:lfrag"));
1713 in_msg->AddMessageIntegrity("rpass");
1714 in_msg->AddFingerprint();
1715 WriteStunMessage(in_msg.get(), buf.get());
1716 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1717 out_msg.accept(), &username));
1718 EXPECT_TRUE(out_msg.get() != NULL);
1719 EXPECT_EQ("lfrag", username);
1720
1721 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1722 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1723 in_msg->AddAttribute(
1724 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1725 in_msg->AddMessageIntegrity("rpass");
1726 in_msg->AddFingerprint();
1727 WriteStunMessage(in_msg.get(), buf.get());
1728 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1729 out_msg.accept(), &username));
1730 EXPECT_TRUE(out_msg.get() != NULL);
1731 EXPECT_EQ("", username);
1732
1733 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1734 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1735 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1736 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1737 in_msg->AddFingerprint();
1738 WriteStunMessage(in_msg.get(), buf.get());
1739 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1740 out_msg.accept(), &username));
1741 EXPECT_TRUE(out_msg.get() != NULL);
1742 EXPECT_EQ("", username);
1743 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1744 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1745 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1746 out_msg->GetErrorCode()->reason());
1747}
1748
guoweisd12140a2015-09-10 13:32:11 -07001749// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001750TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001751 rtc::scoped_ptr<TestPort> port(
1752 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001753
1754 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1755 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1756 rtc::SocketAddress addr(kLocalAddr1);
1757 std::string username;
1758
1759 // BINDING-REQUEST with no username.
1760 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1761 in_msg->AddMessageIntegrity("rpass");
1762 in_msg->AddFingerprint();
1763 WriteStunMessage(in_msg.get(), buf.get());
1764 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1765 out_msg.accept(), &username));
1766 EXPECT_TRUE(out_msg.get() == NULL);
1767 EXPECT_EQ("", username);
1768 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1769
1770 // BINDING-REQUEST with empty username.
1771 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1772 in_msg->AddMessageIntegrity("rpass");
1773 in_msg->AddFingerprint();
1774 WriteStunMessage(in_msg.get(), buf.get());
1775 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1776 out_msg.accept(), &username));
1777 EXPECT_TRUE(out_msg.get() == NULL);
1778 EXPECT_EQ("", username);
1779 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1780
1781 // BINDING-REQUEST with too-short username.
1782 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1783 in_msg->AddMessageIntegrity("rpass");
1784 in_msg->AddFingerprint();
1785 WriteStunMessage(in_msg.get(), buf.get());
1786 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1787 out_msg.accept(), &username));
1788 EXPECT_TRUE(out_msg.get() == NULL);
1789 EXPECT_EQ("", username);
1790 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1791
1792 // BINDING-REQUEST with reversed username.
1793 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1794 "lfrag:rfrag"));
1795 in_msg->AddMessageIntegrity("rpass");
1796 in_msg->AddFingerprint();
1797 WriteStunMessage(in_msg.get(), buf.get());
1798 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1799 out_msg.accept(), &username));
1800 EXPECT_TRUE(out_msg.get() == NULL);
1801 EXPECT_EQ("", username);
1802 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1803
1804 // BINDING-REQUEST with garbage username.
1805 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1806 "abcd:efgh"));
1807 in_msg->AddMessageIntegrity("rpass");
1808 in_msg->AddFingerprint();
1809 WriteStunMessage(in_msg.get(), buf.get());
1810 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1811 out_msg.accept(), &username));
1812 EXPECT_TRUE(out_msg.get() == NULL);
1813 EXPECT_EQ("", username);
1814 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1815}
1816
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001817// Test handling STUN messages with missing or malformed M-I.
1818TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001819 // Our port will act as the "remote" port.
1820 rtc::scoped_ptr<TestPort> port(
1821 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001822
1823 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1824 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1825 rtc::SocketAddress addr(kLocalAddr1);
1826 std::string username;
1827
1828 // BINDING-REQUEST from local to remote with valid ICE username and
1829 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1830 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1831 "rfrag:lfrag"));
1832 in_msg->AddFingerprint();
1833 WriteStunMessage(in_msg.get(), buf.get());
1834 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1835 out_msg.accept(), &username));
1836 EXPECT_TRUE(out_msg.get() == NULL);
1837 EXPECT_EQ("", username);
1838 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1839
1840 // BINDING-REQUEST from local to remote with valid ICE username and
1841 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1842 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1843 "rfrag:lfrag"));
1844 in_msg->AddMessageIntegrity("invalid");
1845 in_msg->AddFingerprint();
1846 WriteStunMessage(in_msg.get(), buf.get());
1847 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1848 out_msg.accept(), &username));
1849 EXPECT_TRUE(out_msg.get() == NULL);
1850 EXPECT_EQ("", username);
1851 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1852
1853 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1854 // by the Connection, not the Port, since they require the remote username.
1855 // Change this test to pass in data via Connection::OnReadPacket instead.
1856}
1857
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001858// Test handling STUN messages with missing or malformed FINGERPRINT.
1859TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001860 // Our port will act as the "remote" port.
1861 rtc::scoped_ptr<TestPort> port(
1862 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001863
1864 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1865 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1866 rtc::SocketAddress addr(kLocalAddr1);
1867 std::string username;
1868
1869 // BINDING-REQUEST from local to remote with valid ICE username and
1870 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1871 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1872 "rfrag:lfrag"));
1873 in_msg->AddMessageIntegrity("rpass");
1874 WriteStunMessage(in_msg.get(), buf.get());
1875 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1876 out_msg.accept(), &username));
1877 EXPECT_EQ(0, port->last_stun_error_code());
1878
1879 // Now, add a fingerprint, but munge the message so it's not valid.
1880 in_msg->AddFingerprint();
1881 in_msg->SetTransactionID("TESTTESTBADD");
1882 WriteStunMessage(in_msg.get(), buf.get());
1883 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1884 out_msg.accept(), &username));
1885 EXPECT_EQ(0, port->last_stun_error_code());
1886
1887 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1888 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1889 in_msg->AddAttribute(
1890 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1891 in_msg->AddMessageIntegrity("rpass");
1892 WriteStunMessage(in_msg.get(), buf.get());
1893 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1894 out_msg.accept(), &username));
1895 EXPECT_EQ(0, port->last_stun_error_code());
1896
1897 // Now, add a fingerprint, but munge the message so it's not valid.
1898 in_msg->AddFingerprint();
1899 in_msg->SetTransactionID("TESTTESTBADD");
1900 WriteStunMessage(in_msg.get(), buf.get());
1901 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1902 out_msg.accept(), &username));
1903 EXPECT_EQ(0, port->last_stun_error_code());
1904
1905 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1906 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1907 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1908 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1909 in_msg->AddMessageIntegrity("rpass");
1910 WriteStunMessage(in_msg.get(), buf.get());
1911 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1912 out_msg.accept(), &username));
1913 EXPECT_EQ(0, port->last_stun_error_code());
1914
1915 // Now, add a fingerprint, but munge the message so it's not valid.
1916 in_msg->AddFingerprint();
1917 in_msg->SetTransactionID("TESTTESTBADD");
1918 WriteStunMessage(in_msg.get(), buf.get());
1919 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1920 out_msg.accept(), &username));
1921 EXPECT_EQ(0, port->last_stun_error_code());
1922}
1923
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001924// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001925// indications are allowed only to the connection which is in read mode.
1926TEST_F(PortTest, TestHandleStunBindingIndication) {
1927 rtc::scoped_ptr<TestPort> lport(
1928 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001929 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1930 lport->SetIceTiebreaker(kTiebreaker1);
1931
1932 // Verifying encoding and decoding STUN indication message.
1933 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1934 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1935 rtc::SocketAddress addr(kLocalAddr1);
1936 std::string username;
1937
1938 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
1939 in_msg->AddFingerprint();
1940 WriteStunMessage(in_msg.get(), buf.get());
1941 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
1942 out_msg.accept(), &username));
1943 EXPECT_TRUE(out_msg.get() != NULL);
1944 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
1945 EXPECT_EQ("", username);
1946
1947 // Verify connection can handle STUN indication and updates
1948 // last_ping_received.
1949 rtc::scoped_ptr<TestPort> rport(
1950 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001951 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1952 rport->SetIceTiebreaker(kTiebreaker2);
1953
1954 lport->PrepareAddress();
1955 rport->PrepareAddress();
1956 ASSERT_FALSE(lport->Candidates().empty());
1957 ASSERT_FALSE(rport->Candidates().empty());
1958
1959 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1960 Port::ORIGIN_MESSAGE);
1961 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1962 Port::ORIGIN_MESSAGE);
1963 rconn->Ping(0);
1964
1965 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1966 IceMessage* msg = rport->last_stun_msg();
1967 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1968 // Send rport binding request to lport.
1969 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1970 rport->last_stun_buf()->Length(),
1971 rtc::PacketTime());
1972 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1973 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
Peter Boström0c4e06b2015-10-07 12:23:21 +02001974 uint32_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001975
1976 // Adding a delay of 100ms.
1977 rtc::Thread::Current()->ProcessMessages(100);
1978 // Pinging lconn using stun indication message.
1979 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
Peter Boström0c4e06b2015-10-07 12:23:21 +02001980 uint32_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001981 EXPECT_GT(last_ping_received2, last_ping_received1);
1982}
1983
1984TEST_F(PortTest, TestComputeCandidatePriority) {
1985 rtc::scoped_ptr<TestPort> port(
1986 CreateTestPort(kLocalAddr1, "name", "pass"));
1987 port->set_type_preference(90);
1988 port->set_component(177);
1989 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
1990 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
1991 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
1992 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
1993 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
1994 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
1995 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
1996 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
1997 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
1998 // These should all be:
1999 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002000 uint32_t expected_priority_v4 = 1509957199U;
2001 uint32_t expected_priority_v6 = 1509959759U;
2002 uint32_t expected_priority_ula = 1509962319U;
2003 uint32_t expected_priority_v4mapped = expected_priority_v4;
2004 uint32_t expected_priority_v4compat = 1509949775U;
2005 uint32_t expected_priority_6to4 = 1509954639U;
2006 uint32_t expected_priority_teredo = 1509952079U;
2007 uint32_t expected_priority_sitelocal = 1509949775U;
2008 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002009 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2010 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2011 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2012 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2013 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2014 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2015 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2016 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2017 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2018}
2019
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002020// In the case of shared socket, one port may be shared by local and stun.
2021// Test that candidates with different types will have different foundation.
2022TEST_F(PortTest, TestFoundation) {
2023 rtc::scoped_ptr<TestPort> testport(
2024 CreateTestPort(kLocalAddr1, "name", "pass"));
2025 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2026 LOCAL_PORT_TYPE,
2027 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2028 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2029 STUN_PORT_TYPE,
2030 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2031 EXPECT_NE(testport->Candidates()[0].foundation(),
2032 testport->Candidates()[1].foundation());
2033}
2034
2035// This test verifies the foundation of different types of ICE candidates.
2036TEST_F(PortTest, TestCandidateFoundation) {
2037 rtc::scoped_ptr<rtc::NATServer> nat_server(
2038 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2039 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2040 udpport1->PrepareAddress();
2041 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2042 udpport2->PrepareAddress();
2043 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2044 udpport2->Candidates()[0].foundation());
2045 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2046 tcpport1->PrepareAddress();
2047 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2048 tcpport2->PrepareAddress();
2049 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2050 tcpport2->Candidates()[0].foundation());
2051 rtc::scoped_ptr<Port> stunport(
2052 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2053 stunport->PrepareAddress();
2054 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2055 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2056 stunport->Candidates()[0].foundation());
2057 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2058 stunport->Candidates()[0].foundation());
2059 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2060 stunport->Candidates()[0].foundation());
2061 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2062 stunport->Candidates()[0].foundation());
2063 // Verify GTURN candidate foundation.
2064 rtc::scoped_ptr<RelayPort> relayport(
2065 CreateGturnPort(kLocalAddr1));
2066 relayport->AddServerAddress(
2067 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2068 relayport->PrepareAddress();
2069 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2070 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2071 relayport->Candidates()[0].foundation());
2072 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2073 relayport->Candidates()[0].foundation());
2074 // Verifying TURN candidate foundation.
2075 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2076 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2077 turnport1->PrepareAddress();
2078 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2079 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2080 turnport1->Candidates()[0].foundation());
2081 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2082 turnport1->Candidates()[0].foundation());
2083 EXPECT_NE(stunport->Candidates()[0].foundation(),
2084 turnport1->Candidates()[0].foundation());
2085 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2086 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2087 turnport2->PrepareAddress();
2088 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2089 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2090 turnport2->Candidates()[0].foundation());
2091
2092 // Running a second turn server, to get different base IP address.
2093 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2094 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2095 TestTurnServer turn_server2(
2096 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2097 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2098 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2099 kTurnUdpIntAddr2));
2100 turnport3->PrepareAddress();
2101 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2102 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2103 turnport2->Candidates()[0].foundation());
2104}
2105
2106// This test verifies the related addresses of different types of
2107// ICE candiates.
2108TEST_F(PortTest, TestCandidateRelatedAddress) {
2109 rtc::scoped_ptr<rtc::NATServer> nat_server(
2110 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2111 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2112 udpport->PrepareAddress();
2113 // For UDPPort, related address will be empty.
2114 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2115 // Testing related address for stun candidates.
2116 // For stun candidate related address must be equal to the base
2117 // socket address.
2118 rtc::scoped_ptr<StunPort> stunport(
2119 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2120 stunport->PrepareAddress();
2121 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2122 // Check STUN candidate address.
2123 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2124 kNatAddr1.ipaddr());
2125 // Check STUN candidate related address.
2126 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2127 stunport->GetLocalAddress());
2128 // Verifying the related address for the GTURN candidates.
2129 // NOTE: In case of GTURN related address will be equal to the mapped
2130 // address, but address(mapped) will not be XOR.
2131 rtc::scoped_ptr<RelayPort> relayport(
2132 CreateGturnPort(kLocalAddr1));
2133 relayport->AddServerAddress(
2134 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2135 relayport->PrepareAddress();
2136 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2137 // For Gturn related address is set to "0.0.0.0:0"
2138 EXPECT_EQ(rtc::SocketAddress(),
2139 relayport->Candidates()[0].related_address());
2140 // Verifying the related address for TURN candidate.
2141 // For TURN related address must be equal to the mapped address.
2142 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2143 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2144 turnport->PrepareAddress();
2145 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2146 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2147 turnport->Candidates()[0].address().ipaddr());
2148 EXPECT_EQ(kNatAddr1.ipaddr(),
2149 turnport->Candidates()[0].related_address().ipaddr());
2150}
2151
2152// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002153TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002154 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002155 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002156 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002157 cand2.set_priority(1);
2158 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002159}
2160
2161// Test the Connection priority is calculated correctly.
2162TEST_F(PortTest, TestConnectionPriority) {
2163 rtc::scoped_ptr<TestPort> lport(
2164 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2165 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2166 rtc::scoped_ptr<TestPort> rport(
2167 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2168 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2169 lport->set_component(123);
2170 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2171 rport->set_component(23);
2172 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2173
2174 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2175 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2176
2177 // RFC 5245
2178 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2179 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2180 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2181 Connection* lconn = lport->CreateConnection(
2182 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2183#if defined(WEBRTC_WIN)
2184 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2185#else
2186 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2187#endif
2188
2189 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2190 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2191 Connection* rconn = rport->CreateConnection(
2192 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2193#if defined(WEBRTC_WIN)
2194 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2195#else
2196 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2197#endif
2198}
2199
2200TEST_F(PortTest, TestWritableState) {
2201 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002202 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002203 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002204 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002205
2206 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002207 TestChannel ch1(port1);
2208 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002209
2210 // Acquire addresses.
2211 ch1.Start();
2212 ch2.Start();
2213 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2214 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2215
2216 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002217 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002218 ASSERT_TRUE(ch1.conn() != NULL);
2219 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2220 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2221 ch1.Ping();
2222 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2223
2224 // Data should be unsendable until the connection is accepted.
2225 char data[] = "abcd";
2226 int data_size = ARRAY_SIZE(data);
2227 rtc::PacketOptions options;
2228 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2229
2230 // Accept the connection to return the binding response, transition to
2231 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002232 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002233 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2234 kTimeout);
2235 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2236
2237 // Ask the connection to update state as if enough time has passed to lose
2238 // full writability and 5 pings went unresponded to. We'll accomplish the
2239 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002240 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002241 ch1.Ping(i);
2242 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02002243 uint32_t unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002244 ch1.conn()->UpdateState(unreliable_timeout_delay);
2245 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2246
2247 // Data should be able to be sent in this state.
2248 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2249
2250 // And now allow the other side to process the pings and send binding
2251 // responses.
2252 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2253 kTimeout);
2254
2255 // Wait long enough for a full timeout (past however long we've already
2256 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002257 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002258 ch1.Ping(unreliable_timeout_delay + i);
2259 }
2260 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2261 500u);
2262 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2263
2264 // Now that the connection has completely timed out, data send should fail.
2265 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2266
2267 ch1.Stop();
2268 ch2.Stop();
2269}
2270
2271TEST_F(PortTest, TestTimeoutForNeverWritable) {
2272 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002273 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002274 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002275 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002276
2277 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002278 TestChannel ch1(port1);
2279 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002280
2281 // Acquire addresses.
2282 ch1.Start();
2283 ch2.Start();
2284
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002285 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002286 ASSERT_TRUE(ch1.conn() != NULL);
2287 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2288
2289 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002290 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002291 ch1.Ping(i);
2292 }
2293 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2294 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2295}
2296
2297// This test verifies the connection setup between ICEMODE_FULL
2298// and ICEMODE_LITE.
2299// In this test |ch1| behaves like FULL mode client and we have created
2300// port which responds to the ping message just like LITE client.
2301TEST_F(PortTest, TestIceLiteConnectivity) {
2302 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002303 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002304 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2305
2306 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002307 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002308 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2309 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002310 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002311 ch1.SetIceMode(ICEMODE_FULL);
2312
2313 // Start gathering candidates.
2314 ch1.Start();
2315 ice_lite_port->PrepareAddress();
2316
2317 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2318 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2319
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002320 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002321 ASSERT_TRUE(ch1.conn() != NULL);
2322 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2323
2324 // Send ping from full mode client.
2325 // This ping must not have USE_CANDIDATE_ATTR.
2326 ch1.Ping();
2327
2328 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2329 // from port.
2330 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2331 IceMessage* msg = ice_full_port->last_stun_msg();
2332 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2333
2334 // Respond with a BINDING-RESPONSE from litemode client.
2335 // NOTE: Ideally we should't create connection at this stage from lite
2336 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2337 // But we need a connection to send a response message.
2338 ice_lite_port->CreateConnection(
2339 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2340 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2341 ice_lite_port->SendBindingResponse(
2342 request.get(), ice_full_port->Candidates()[0].address());
2343
2344 // Feeding the respone message from litemode to the full mode connection.
2345 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2346 ice_lite_port->last_stun_buf()->Length(),
2347 rtc::PacketTime());
2348 // Verifying full mode connection becomes writable from the response.
2349 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2350 kTimeout);
2351 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2352
2353 // Clear existing stun messsages. Otherwise we will process old stun
2354 // message right after we send ping.
2355 ice_full_port->Reset();
2356 // Send ping. This must have USE_CANDIDATE_ATTR.
2357 ch1.Ping();
2358 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2359 msg = ice_full_port->last_stun_msg();
2360 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2361 ch1.Stop();
2362}
2363
2364// This test case verifies that the CONTROLLING port does not time out.
2365TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002366 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2367 ConnectToSignalDestroyed(port1);
2368 port1->set_timeout_delay(10); // milliseconds
2369 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2370 port1->SetIceTiebreaker(kTiebreaker1);
2371
2372 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2373 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2374 port2->SetIceTiebreaker(kTiebreaker2);
2375
2376 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002377 TestChannel ch1(port1);
2378 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002379
2380 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002381 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002382
2383 // After the connection is destroyed, the port should not be destroyed.
2384 rtc::Thread::Current()->ProcessMessages(kTimeout);
2385 EXPECT_FALSE(destroyed());
2386}
2387
2388// This test case verifies that the CONTROLLED port does time out, but only
2389// after connectivity is lost.
2390TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002391 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2392 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2393 port1->SetIceTiebreaker(kTiebreaker1);
2394
2395 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2396 ConnectToSignalDestroyed(port2);
2397 port2->set_timeout_delay(10); // milliseconds
2398 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2399 port2->SetIceTiebreaker(kTiebreaker2);
2400
2401 // The connection must not be destroyed before a connection is attempted.
2402 EXPECT_FALSE(destroyed());
2403
2404 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2405 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2406
2407 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002408 TestChannel ch1(port1);
2409 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002410
2411 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002412 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002413
2414 // The controlled port should be destroyed after 10 milliseconds.
2415 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2416}
honghaizd0b31432015-09-30 12:42:17 -07002417
2418// This test case verifies that if the role of a port changes from controlled
2419// to controlling after all connections fail, the port will not be destroyed.
2420TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2421 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2422 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2423 port1->SetIceTiebreaker(kTiebreaker1);
2424
2425 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2426 ConnectToSignalDestroyed(port2);
2427 port2->set_timeout_delay(10); // milliseconds
2428 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2429 port2->SetIceTiebreaker(kTiebreaker2);
2430
2431 // The connection must not be destroyed before a connection is attempted.
2432 EXPECT_FALSE(destroyed());
2433
2434 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2435 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2436
2437 // Set up channels and ensure both ports will be deleted.
2438 TestChannel ch1(port1);
2439 TestChannel ch2(port2);
2440
2441 // Simulate a connection that succeeds, and then is destroyed.
2442 StartConnectAndStopChannels(&ch1, &ch2);
2443 // Switch the role after all connections are destroyed.
2444 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2445 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2446 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2447
2448 // After the connection is destroyed, the port should not be destroyed.
2449 rtc::Thread::Current()->ProcessMessages(kTimeout);
2450 EXPECT_FALSE(destroyed());
2451}