blob: d27be2944275995d46b9433328f54d248831be4b [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/basicpacketsocketfactory.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012#include "webrtc/p2p/base/relayport.h"
13#include "webrtc/p2p/base/stunport.h"
14#include "webrtc/p2p/base/tcpport.h"
15#include "webrtc/p2p/base/testrelayserver.h"
16#include "webrtc/p2p/base/teststunserver.h"
17#include "webrtc/p2p/base/testturnserver.h"
18#include "webrtc/p2p/base/transport.h"
19#include "webrtc/p2p/base/turnport.h"
tfarina5237aaf2015-11-10 23:44:30 -080020#include "webrtc/base/arraysize.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000021#include "webrtc/base/crc32.h"
22#include "webrtc/base/gunit.h"
23#include "webrtc/base/helpers.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/natserver.h"
26#include "webrtc/base/natsocketfactory.h"
27#include "webrtc/base/physicalsocketserver.h"
28#include "webrtc/base/scoped_ptr.h"
29#include "webrtc/base/socketaddress.h"
30#include "webrtc/base/ssladapter.h"
31#include "webrtc/base/stringutils.h"
32#include "webrtc/base/thread.h"
33#include "webrtc/base/virtualsocketserver.h"
34
35using rtc::AsyncPacketSocket;
36using rtc::ByteBuffer;
37using rtc::NATType;
38using rtc::NAT_OPEN_CONE;
39using rtc::NAT_ADDR_RESTRICTED;
40using rtc::NAT_PORT_RESTRICTED;
41using rtc::NAT_SYMMETRIC;
42using rtc::PacketSocketFactory;
43using rtc::scoped_ptr;
44using rtc::Socket;
45using rtc::SocketAddress;
46using namespace cricket;
47
48static const int kTimeout = 1000;
49static const SocketAddress kLocalAddr1("192.168.1.2", 0);
50static const SocketAddress kLocalAddr2("192.168.1.3", 0);
deadbeefc5d0d952015-07-16 10:22:21 -070051static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
52static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_UDP_PORT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
54static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
55static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
56static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
57static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
58static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
59static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
60static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
Honghai Zhang80f1db92016-01-27 11:54:45 -080061static const SocketAddress kTurnTcpIntAddr("99.99.99.4", 5010);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000062static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
63static const RelayCredentials kRelayCredentials("test", "test");
64
65// TODO: Update these when RFC5245 is completely supported.
66// Magic value of 30 is from RFC3484, for IPv4 addresses.
Peter Boström0c4e06b2015-10-07 12:23:21 +020067static const uint32_t kDefaultPrflxPriority =
68 ICE_TYPE_PREFERENCE_PRFLX << 24 | 30 << 8 |
69 (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000070
71static const int kTiebreaker1 = 11111;
72static const int kTiebreaker2 = 22222;
73
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070074static const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
75
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000076static Candidate GetCandidate(Port* port) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -070077 assert(port->Candidates().size() >= 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000078 return port->Candidates()[0];
79}
80
81static SocketAddress GetAddress(Port* port) {
82 return GetCandidate(port).address();
83}
84
85static IceMessage* CopyStunMessage(const IceMessage* src) {
86 IceMessage* dst = new IceMessage();
87 ByteBuffer buf;
88 src->Write(&buf);
89 dst->Read(&buf);
90 return dst;
91}
92
93static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
94 buf->Resize(0); // clear out any existing buffer contents
95 return msg->Write(buf);
96}
97
98// Stub port class for testing STUN generation and processing.
99class TestPort : public Port {
100 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000101 TestPort(rtc::Thread* thread,
102 const std::string& type,
103 rtc::PacketSocketFactory* factory,
104 rtc::Network* network,
105 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200106 uint16_t min_port,
107 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000108 const std::string& username_fragment,
109 const std::string& password)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200110 : Port(thread,
111 type,
112 factory,
113 network,
114 ip,
115 min_port,
116 max_port,
117 username_fragment,
118 password) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119 ~TestPort() {}
120
121 // Expose GetStunMessage so that we can test it.
122 using cricket::Port::GetStunMessage;
123
124 // The last StunMessage that was sent on this Port.
125 // TODO: Make these const; requires changes to SendXXXXResponse.
126 ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
127 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
128 int last_stun_error_code() {
129 int code = 0;
130 if (last_stun_msg_) {
131 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
132 if (error_attr) {
133 code = error_attr->code();
134 }
135 }
136 return code;
137 }
138
139 virtual void PrepareAddress() {
140 rtc::SocketAddress addr(ip(), min_port());
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700141 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 ICE_TYPE_PREFERENCE_HOST, 0, true);
143 }
144
Honghai Zhangf9945b22015-12-15 12:20:13 -0800145 virtual bool SupportsProtocol(const std::string& protocol) const {
146 return true;
147 }
148
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149 // Exposed for testing candidate building.
150 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700151 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 type_preference_, 0, false);
153 }
154 void AddCandidateAddress(const rtc::SocketAddress& addr,
155 const rtc::SocketAddress& base_address,
156 const std::string& type,
157 int type_preference,
158 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700159 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 type_preference, 0, final);
161 }
162
163 virtual Connection* CreateConnection(const Candidate& remote_candidate,
164 CandidateOrigin origin) {
165 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
166 AddConnection(conn);
167 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
168 // in STUN binding requests.
169 conn->set_use_candidate_attr(true);
170 return conn;
171 }
172 virtual int SendTo(
173 const void* data, size_t size, const rtc::SocketAddress& addr,
174 const rtc::PacketOptions& options, bool payload) {
175 if (!payload) {
176 IceMessage* msg = new IceMessage;
177 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
178 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
179 if (!msg->Read(buf)) {
180 delete msg;
181 delete buf;
182 return -1;
183 }
184 buf->SetReadPosition(pos);
185 last_stun_buf_.reset(buf);
186 last_stun_msg_.reset(msg);
187 }
188 return static_cast<int>(size);
189 }
190 virtual int SetOption(rtc::Socket::Option opt, int value) {
191 return 0;
192 }
193 virtual int GetOption(rtc::Socket::Option opt, int* value) {
194 return -1;
195 }
196 virtual int GetError() {
197 return 0;
198 }
199 void Reset() {
200 last_stun_buf_.reset();
201 last_stun_msg_.reset();
202 }
203 void set_type_preference(int type_preference) {
204 type_preference_ = type_preference;
205 }
206
207 private:
Stefan Holmer55674ff2016-01-14 15:49:16 +0100208 void OnSentPacket(rtc::AsyncPacketSocket* socket,
209 const rtc::SentPacket& sent_packet) {
210 PortInterface::SignalSentPacket(sent_packet);
211 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
213 rtc::scoped_ptr<IceMessage> last_stun_msg_;
pbos7640ffa2015-11-30 09:16:59 -0800214 int type_preference_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215};
216
217class TestChannel : public sigslot::has_slots<> {
218 public:
219 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700220 TestChannel(Port* p1)
221 : ice_mode_(ICEMODE_FULL),
222 port_(p1),
223 complete_count_(0),
224 conn_(NULL),
225 remote_request_(),
226 nominated_(false) {
227 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
228 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
229 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000230 }
231
232 int complete_count() { return complete_count_; }
233 Connection* conn() { return conn_; }
234 const SocketAddress& remote_address() { return remote_address_; }
235 const std::string remote_fragment() { return remote_frag_; }
236
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700237 void Start() { port_->PrepareAddress(); }
238 void CreateConnection(const Candidate& remote_candidate) {
239 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000240 IceMode remote_ice_mode =
241 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
242 conn_->set_remote_ice_mode(remote_ice_mode);
243 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
244 conn_->SignalStateChange.connect(
245 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700246 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700247 conn_->SignalReadyToSend.connect(this,
248 &TestChannel::OnConnectionReadyToSend);
249 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 }
251 void OnConnectionStateChange(Connection* conn) {
252 if (conn->write_state() == Connection::STATE_WRITABLE) {
253 conn->set_use_candidate_attr(true);
254 nominated_ = true;
255 }
256 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700257 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700259 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700261 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700262 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700263 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 remote_request_.reset();
265 }
266 void Ping() {
267 Ping(0);
268 }
honghaiz34b11eb2016-03-16 08:55:44 -0700269 void Ping(int64_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700271 if (conn_) {
272 conn_->Destroy();
273 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274 }
275
276 void OnPortComplete(Port* port) {
277 complete_count_++;
278 }
279 void SetIceMode(IceMode ice_mode) {
280 ice_mode_ = ice_mode;
281 }
282
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700283 int SendData(const char* data, size_t len) {
284 rtc::PacketOptions options;
285 return conn_->Send(data, len, options);
286 }
287
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
289 ProtocolType proto,
290 IceMessage* msg, const std::string& rf,
291 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700292 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 if (!remote_address_.IsNil()) {
294 ASSERT_EQ(remote_address_, addr);
295 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 const cricket::StunUInt32Attribute* priority_attr =
297 msg->GetUInt32(STUN_ATTR_PRIORITY);
298 const cricket::StunByteStringAttribute* mi_attr =
299 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
300 const cricket::StunUInt32Attribute* fingerprint_attr =
301 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700302 EXPECT_TRUE(priority_attr != NULL);
303 EXPECT_TRUE(mi_attr != NULL);
304 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 remote_address_ = addr;
306 remote_request_.reset(CopyStunMessage(msg));
307 remote_frag_ = rf;
308 }
309
310 void OnDestroyed(Connection* conn) {
311 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700312 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700314 // When the connection is destroyed, also clear these fields so future
315 // connections are possible.
316 remote_request_.reset();
317 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318 }
319
320 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700321 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322 ASSERT_EQ(destroyed_src, port);
323 }
324
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700325 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327 bool nominated() const { return nominated_; }
328
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700329 void set_connection_ready_to_send(bool ready) {
330 connection_ready_to_send_ = ready;
331 }
332 bool connection_ready_to_send() const {
333 return connection_ready_to_send_;
334 }
335
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000336 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700337 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
338 void OnConnectionReadyToSend(Connection* conn) {
339 ASSERT_EQ(conn, conn_);
340 connection_ready_to_send_ = true;
341 }
342
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000343 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700344 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000345
346 int complete_count_;
347 Connection* conn_;
348 SocketAddress remote_address_;
349 rtc::scoped_ptr<StunMessage> remote_request_;
350 std::string remote_frag_;
351 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700352 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353};
354
355class PortTest : public testing::Test, public sigslot::has_slots<> {
356 public:
357 PortTest()
358 : main_(rtc::Thread::Current()),
359 pss_(new rtc::PhysicalSocketServer),
360 ss_(new rtc::VirtualSocketServer(pss_.get())),
361 ss_scope_(ss_.get()),
362 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
363 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700364 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
365 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000366 nat_socket_factory1_(&nat_factory1_),
367 nat_socket_factory2_(&nat_factory2_),
368 stun_server_(TestStunServer::Create(main_, kStunAddr)),
369 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700370 relay_server_(main_,
371 kRelayUdpIntAddr,
372 kRelayUdpExtAddr,
373 kRelayTcpIntAddr,
374 kRelayTcpExtAddr,
375 kRelaySslTcpIntAddr,
376 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000377 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
378 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 role_conflict_(false),
380 destroyed_(false) {
381 network_.AddIP(rtc::IPAddress(INADDR_ANY));
382 }
383
384 protected:
385 void TestLocalToLocal() {
386 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700387 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700389 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
391 }
392 void TestLocalToStun(NATType ntype) {
393 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700394 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
396 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700397 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 TestConnectivity("udp", port1, StunName(ntype), port2,
399 ntype == NAT_OPEN_CONE, true,
400 ntype != NAT_SYMMETRIC, true);
401 }
402 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
403 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700404 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000405 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700406 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
408 rtype == RELAY_GTURN, true, true, true);
409 }
410 void TestStunToLocal(NATType ntype) {
411 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
412 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700413 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700415 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000416 TestConnectivity(StunName(ntype), port1, "udp", port2,
417 true, ntype != NAT_SYMMETRIC, true, true);
418 }
419 void TestStunToStun(NATType ntype1, NATType ntype2) {
420 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
421 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700422 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000423 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
424 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700425 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000426 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
427 ntype2 == NAT_OPEN_CONE,
428 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
429 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
430 }
431 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
432 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
433 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700434 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700436 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000437 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
438 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
439 }
440 void TestTcpToTcp() {
441 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700442 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700444 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
446 }
447 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
448 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700449 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700451 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000452 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
453 rtype == RELAY_GTURN, false, true, true);
454 }
455 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
456 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700457 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700459 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
461 rtype == RELAY_GTURN, false, true, true);
462 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 // helpers for above functions
464 UDPPort* CreateUdpPort(const SocketAddress& addr) {
465 return CreateUdpPort(addr, &socket_factory_);
466 }
467 UDPPort* CreateUdpPort(const SocketAddress& addr,
468 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800469 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
470 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 }
472 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700473 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 }
475 TCPPort* CreateTcpPort(const SocketAddress& addr,
476 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700477 return TCPPort::Create(main_, socket_factory, &network_,
478 addr.ipaddr(), 0, 0, username_, password_,
479 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 }
481 StunPort* CreateStunPort(const SocketAddress& addr,
482 rtc::PacketSocketFactory* factory) {
483 ServerAddresses stun_servers;
484 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700485 return StunPort::Create(main_, factory, &network_,
486 addr.ipaddr(), 0, 0,
487 username_, password_, stun_servers,
488 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 }
490 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
491 ProtocolType int_proto, ProtocolType ext_proto) {
492 if (rtype == RELAY_TURN) {
493 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
494 } else {
495 return CreateGturnPort(addr, int_proto, ext_proto);
496 }
497 }
498 TurnPort* CreateTurnPort(const SocketAddress& addr,
499 PacketSocketFactory* socket_factory,
500 ProtocolType int_proto, ProtocolType ext_proto) {
Honghai Zhang80f1db92016-01-27 11:54:45 -0800501 SocketAddress server_addr =
502 int_proto == PROTO_TCP ? kTurnTcpIntAddr : kTurnUdpIntAddr;
503 return CreateTurnPort(addr, socket_factory, int_proto, ext_proto,
504 server_addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505 }
506 TurnPort* CreateTurnPort(const SocketAddress& addr,
507 PacketSocketFactory* socket_factory,
508 ProtocolType int_proto, ProtocolType ext_proto,
509 const rtc::SocketAddress& server_addr) {
Honghai Zhang80f1db92016-01-27 11:54:45 -0800510 return TurnPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
511 0, username_, password_,
512 ProtocolAddress(server_addr, int_proto),
513 kRelayCredentials, 0, std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000514 }
515 RelayPort* CreateGturnPort(const SocketAddress& addr,
516 ProtocolType int_proto, ProtocolType ext_proto) {
517 RelayPort* port = CreateGturnPort(addr);
518 SocketAddress addrs[] =
519 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
520 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
521 return port;
522 }
523 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700524 // TODO(pthatcher): Remove GTURN.
525 return RelayPort::Create(main_, &socket_factory_, &network_,
526 addr.ipaddr(), 0, 0,
527 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000528 // TODO: Add an external address for ext_proto, so that the
529 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 }
531 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
532 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700533 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000534 }
535 static const char* StunName(NATType type) {
536 switch (type) {
537 case NAT_OPEN_CONE: return "stun(open cone)";
538 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
539 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
540 case NAT_SYMMETRIC: return "stun(symmetric)";
541 default: return "stun(?)";
542 }
543 }
544 static const char* RelayName(RelayType type, ProtocolType proto) {
545 if (type == RELAY_TURN) {
546 switch (proto) {
547 case PROTO_UDP: return "turn(udp)";
548 case PROTO_TCP: return "turn(tcp)";
549 case PROTO_SSLTCP: return "turn(ssltcp)";
550 default: return "turn(?)";
551 }
552 } else {
553 switch (proto) {
554 case PROTO_UDP: return "gturn(udp)";
555 case PROTO_TCP: return "gturn(tcp)";
556 case PROTO_SSLTCP: return "gturn(ssltcp)";
557 default: return "gturn(?)";
558 }
559 }
560 }
561
honghaiza0c44ea2016-03-23 16:07:48 -0700562 void SetNetworkType(rtc::AdapterType adapter_type) {
563 network_.set_type(adapter_type);
564 }
565
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000566 void TestCrossFamilyPorts(int type);
567
Peter Thatcherb8b01432015-07-07 16:45:53 -0700568 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
569
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000570 // This does all the work and then deletes |port1| and |port2|.
571 void TestConnectivity(const char* name1, Port* port1,
572 const char* name2, Port* port2,
573 bool accept, bool same_addr1,
574 bool same_addr2, bool possible);
575
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700576 // This connects the provided channels which have already started. |ch1|
577 // should have its Connection created (either through CreateConnection() or
578 // TCP reconnecting mechanism before entering this function.
579 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
580 ASSERT_TRUE(ch1->conn());
581 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
582 ch1->Ping();
583 WAIT(!ch2->remote_address().IsNil(), kTimeout);
584
585 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700586 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700587 ch2->Ping();
588 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
589 kTimeout);
590 }
591
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 // This connects and disconnects the provided channels in the same sequence as
593 // TestConnectivity with all options set to |true|. It does not delete either
594 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700595 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
596 // Acquire addresses.
597 ch1->Start();
598 ch2->Start();
599
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700600 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700601 ConnectStartedChannels(ch1, ch2);
602
603 // Destroy the connections.
604 ch1->Stop();
605 ch2->Stop();
606 }
607
608 // This disconnects both end's Connection and make sure ch2 ready for new
609 // connection.
610 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700611 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
612 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
613 ASSERT_TRUE(
614 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
615 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700616
617 // Wait for both OnClose are delivered.
618 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
619 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
620
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700621 // Ensure redundant SignalClose events on TcpConnection won't break tcp
622 // reconnection. Chromium will fire SignalClose for all outstanding IPC
623 // packets during reconnection.
624 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
625 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
626
627 // Speed up destroying ch2's connection such that the test is ready to
628 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700629 ch2->conn()->Destroy();
630 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
631 }
632
633 void TestTcpReconnect(bool ping_after_disconnected,
634 bool send_after_disconnected) {
635 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700636 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700637 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700638 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700639
640 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
641 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
642
643 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700644 TestChannel ch1(port1);
645 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700646 EXPECT_EQ(0, ch1.complete_count());
647 EXPECT_EQ(0, ch2.complete_count());
648
649 ch1.Start();
650 ch2.Start();
651 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
652 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
653
654 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700655 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700656 ConnectStartedChannels(&ch1, &ch2);
657
658 // Shorten the timeout period.
659 const int kTcpReconnectTimeout = kTimeout;
660 static_cast<TCPConnection*>(ch1.conn())
661 ->set_reconnection_timeout(kTcpReconnectTimeout);
662 static_cast<TCPConnection*>(ch2.conn())
663 ->set_reconnection_timeout(kTcpReconnectTimeout);
664
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700665 EXPECT_FALSE(ch1.connection_ready_to_send());
666 EXPECT_FALSE(ch2.connection_ready_to_send());
667
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700668 // Once connected, disconnect them.
669 DisconnectTcpTestChannels(&ch1, &ch2);
670
671 if (send_after_disconnected || ping_after_disconnected) {
672 if (send_after_disconnected) {
673 // First SendData after disconnect should fail but will trigger
674 // reconnect.
675 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
676 }
677
678 if (ping_after_disconnected) {
679 // Ping should trigger reconnect.
680 ch1.Ping();
681 }
682
683 // Wait for channel's outgoing TCPConnection connected.
684 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
685
686 // Verify that we could still connect channels.
687 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700688 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
689 kTcpReconnectTimeout);
690 // Channel2 is the passive one so a new connection is created during
691 // reconnect. This new connection should never have issued EWOULDBLOCK
692 // hence the connection_ready_to_send() should be false.
693 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700694 } else {
695 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700696 // Since the reconnection never happens, the connections should have been
697 // destroyed after the timeout.
698 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
699 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700700 }
701
702 // Tear down and ensure that goes smoothly.
703 ch1.Stop();
704 ch2.Stop();
705 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
706 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
707 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000709 IceMessage* CreateStunMessage(int type) {
710 IceMessage* msg = new IceMessage();
711 msg->SetType(type);
712 msg->SetTransactionID("TESTTESTTEST");
713 return msg;
714 }
715 IceMessage* CreateStunMessageWithUsername(int type,
716 const std::string& username) {
717 IceMessage* msg = CreateStunMessage(type);
718 msg->AddAttribute(
719 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
720 return msg;
721 }
722 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
723 const std::string& username,
724 const std::string& password) {
725 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
726 addr.ipaddr(), 0, 0, username, password);
727 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
728 return port;
729 }
730 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
731 const std::string& username,
732 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000733 cricket::IceRole role,
734 int tiebreaker) {
735 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 port->SetIceRole(role);
737 port->SetIceTiebreaker(tiebreaker);
738 return port;
739 }
740
741 void OnRoleConflict(PortInterface* port) {
742 role_conflict_ = true;
743 }
744 bool role_conflict() const { return role_conflict_; }
745
746 void ConnectToSignalDestroyed(PortInterface* port) {
747 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
748 }
749
750 void OnDestroyed(PortInterface* port) {
751 destroyed_ = true;
752 }
753 bool destroyed() const { return destroyed_; }
754
755 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
756 return &nat_socket_factory1_;
757 }
758
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700759 protected:
760 rtc::VirtualSocketServer* vss() { return ss_.get(); }
761
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000762 private:
763 rtc::Thread* main_;
764 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
765 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
766 rtc::SocketServerScope ss_scope_;
767 rtc::Network network_;
768 rtc::BasicPacketSocketFactory socket_factory_;
769 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
770 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
771 rtc::NATSocketFactory nat_factory1_;
772 rtc::NATSocketFactory nat_factory2_;
773 rtc::BasicPacketSocketFactory nat_socket_factory1_;
774 rtc::BasicPacketSocketFactory nat_socket_factory2_;
775 scoped_ptr<TestStunServer> stun_server_;
776 TestTurnServer turn_server_;
777 TestRelayServer relay_server_;
778 std::string username_;
779 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000780 bool role_conflict_;
781 bool destroyed_;
782};
783
784void PortTest::TestConnectivity(const char* name1, Port* port1,
785 const char* name2, Port* port2,
786 bool accept, bool same_addr1,
787 bool same_addr2, bool possible) {
788 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
789 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
790 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
791
792 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700793 TestChannel ch1(port1);
794 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000795 EXPECT_EQ(0, ch1.complete_count());
796 EXPECT_EQ(0, ch2.complete_count());
797
798 // Acquire addresses.
799 ch1.Start();
800 ch2.Start();
801 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
802 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
803
804 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700805 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000806 ASSERT_TRUE(ch1.conn() != NULL);
807 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
808 ch1.Ping();
809 WAIT(!ch2.remote_address().IsNil(), kTimeout);
810
811 if (accept) {
812 // We are able to send a ping from src to dst. This is the case when
813 // sending to UDP ports and cone NATs.
814 EXPECT_TRUE(ch1.remote_address().IsNil());
815 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
816
817 // Ensure the ping came from the same address used for src.
818 // This is the case unless the source NAT was symmetric.
819 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
820 EXPECT_TRUE(same_addr2);
821
822 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700823 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000824 ASSERT_TRUE(ch2.conn() != NULL);
825 ch2.Ping();
826 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
827 kTimeout);
828 } else {
829 // We can't send a ping from src to dst, so flip it around. This will happen
830 // when the destination NAT is addr/port restricted or symmetric.
831 EXPECT_TRUE(ch1.remote_address().IsNil());
832 EXPECT_TRUE(ch2.remote_address().IsNil());
833
834 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700835 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000836 ASSERT_TRUE(ch2.conn() != NULL);
837 ch2.Ping();
838 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
839
840 if (same_addr1 && same_addr2) {
841 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700842 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000843 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
844
845 // First connection may not be writable if the first ping did not get
846 // through. So we will have to do another.
847 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
848 ch1.Ping();
849 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
850 kTimeout);
851 }
852 } else if (!same_addr1 && possible) {
853 // The new ping went to the candidate address, but that address was bad.
854 // This will happen when the source NAT is symmetric.
855 EXPECT_TRUE(ch1.remote_address().IsNil());
856 EXPECT_TRUE(ch2.remote_address().IsNil());
857
858 // However, since we have now sent a ping to the source IP, we should be
859 // able to get a ping from it. This gives us the real source address.
860 ch1.Ping();
861 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700862 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863 EXPECT_TRUE(ch1.remote_address().IsNil());
864
865 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700866 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000867 ASSERT_TRUE(ch2.conn() != NULL);
868 ch2.Ping();
869 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
870 kTimeout);
871 } else if (!same_addr2 && possible) {
872 // The new ping came in, but from an unexpected address. This will happen
873 // when the destination NAT is symmetric.
874 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700875 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876
877 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700878 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 ch1.Ping();
880 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
881 kTimeout);
882 } else { // (!possible)
883 // There should be s no way for the pings to reach each other. Check it.
884 EXPECT_TRUE(ch1.remote_address().IsNil());
885 EXPECT_TRUE(ch2.remote_address().IsNil());
886 ch1.Ping();
887 WAIT(!ch2.remote_address().IsNil(), kTimeout);
888 EXPECT_TRUE(ch1.remote_address().IsNil());
889 EXPECT_TRUE(ch2.remote_address().IsNil());
890 }
891 }
892
893 // Everything should be good, unless we know the situation is impossible.
894 ASSERT_TRUE(ch1.conn() != NULL);
895 ASSERT_TRUE(ch2.conn() != NULL);
896 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700897 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700899 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
901 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700902 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700904 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
906 }
907
908 // Tear down and ensure that goes smoothly.
909 ch1.Stop();
910 ch2.Stop();
911 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
912 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
913}
914
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915class FakePacketSocketFactory : public rtc::PacketSocketFactory {
916 public:
917 FakePacketSocketFactory()
918 : next_udp_socket_(NULL),
919 next_server_tcp_socket_(NULL),
920 next_client_tcp_socket_(NULL) {
921 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000922 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000924 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200925 uint16_t min_port,
926 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 EXPECT_TRUE(next_udp_socket_ != NULL);
928 AsyncPacketSocket* result = next_udp_socket_;
929 next_udp_socket_ = NULL;
930 return result;
931 }
932
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000933 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200934 uint16_t min_port,
935 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000936 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
938 AsyncPacketSocket* result = next_server_tcp_socket_;
939 next_server_tcp_socket_ = NULL;
940 return result;
941 }
942
943 // TODO: |proxy_info| and |user_agent| should be set
944 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000945 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
946 const SocketAddress& remote_address,
947 const rtc::ProxyInfo& proxy_info,
948 const std::string& user_agent,
949 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000950 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
951 AsyncPacketSocket* result = next_client_tcp_socket_;
952 next_client_tcp_socket_ = NULL;
953 return result;
954 }
955
956 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
957 next_udp_socket_ = next_udp_socket;
958 }
959 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
960 next_server_tcp_socket_ = next_server_tcp_socket;
961 }
962 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
963 next_client_tcp_socket_ = next_client_tcp_socket;
964 }
965 rtc::AsyncResolverInterface* CreateAsyncResolver() {
966 return NULL;
967 }
968
969 private:
970 AsyncPacketSocket* next_udp_socket_;
971 AsyncPacketSocket* next_server_tcp_socket_;
972 AsyncPacketSocket* next_client_tcp_socket_;
973};
974
975class FakeAsyncPacketSocket : public AsyncPacketSocket {
976 public:
977 // Returns current local address. Address may be set to NULL if the
978 // socket is not bound yet (GetState() returns STATE_BINDING).
979 virtual SocketAddress GetLocalAddress() const {
980 return SocketAddress();
981 }
982
983 // Returns remote address. Returns zeroes if this is not a client TCP socket.
984 virtual SocketAddress GetRemoteAddress() const {
985 return SocketAddress();
986 }
987
988 // Send a packet.
989 virtual int Send(const void *pv, size_t cb,
990 const rtc::PacketOptions& options) {
991 return static_cast<int>(cb);
992 }
993 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
994 const rtc::PacketOptions& options) {
995 return static_cast<int>(cb);
996 }
997 virtual int Close() {
998 return 0;
999 }
1000
1001 virtual State GetState() const { return state_; }
1002 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
1003 virtual int SetOption(Socket::Option opt, int value) { return 0; }
1004 virtual int GetError() const { return 0; }
1005 virtual void SetError(int error) { }
1006
1007 void set_state(State state) { state_ = state; }
1008
1009 private:
1010 State state_;
1011};
1012
1013// Local -> XXXX
1014TEST_F(PortTest, TestLocalToLocal) {
1015 TestLocalToLocal();
1016}
1017
1018TEST_F(PortTest, TestLocalToConeNat) {
1019 TestLocalToStun(NAT_OPEN_CONE);
1020}
1021
1022TEST_F(PortTest, TestLocalToARNat) {
1023 TestLocalToStun(NAT_ADDR_RESTRICTED);
1024}
1025
1026TEST_F(PortTest, TestLocalToPRNat) {
1027 TestLocalToStun(NAT_PORT_RESTRICTED);
1028}
1029
1030TEST_F(PortTest, TestLocalToSymNat) {
1031 TestLocalToStun(NAT_SYMMETRIC);
1032}
1033
1034// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1035TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1036 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1037}
1038
1039TEST_F(PortTest, TestLocalToGturn) {
1040 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1041}
1042
1043TEST_F(PortTest, TestLocalToTcpGturn) {
1044 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1045}
1046
1047TEST_F(PortTest, TestLocalToSslTcpGturn) {
1048 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1049}
1050
1051// Cone NAT -> XXXX
1052TEST_F(PortTest, TestConeNatToLocal) {
1053 TestStunToLocal(NAT_OPEN_CONE);
1054}
1055
1056TEST_F(PortTest, TestConeNatToConeNat) {
1057 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1058}
1059
1060TEST_F(PortTest, TestConeNatToARNat) {
1061 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1062}
1063
1064TEST_F(PortTest, TestConeNatToPRNat) {
1065 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1066}
1067
1068TEST_F(PortTest, TestConeNatToSymNat) {
1069 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1070}
1071
1072TEST_F(PortTest, TestConeNatToTurn) {
1073 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1074}
1075
1076TEST_F(PortTest, TestConeNatToGturn) {
1077 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1078}
1079
1080TEST_F(PortTest, TestConeNatToTcpGturn) {
1081 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1082}
1083
1084// Address-restricted NAT -> XXXX
1085TEST_F(PortTest, TestARNatToLocal) {
1086 TestStunToLocal(NAT_ADDR_RESTRICTED);
1087}
1088
1089TEST_F(PortTest, TestARNatToConeNat) {
1090 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1091}
1092
1093TEST_F(PortTest, TestARNatToARNat) {
1094 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1095}
1096
1097TEST_F(PortTest, TestARNatToPRNat) {
1098 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1099}
1100
1101TEST_F(PortTest, TestARNatToSymNat) {
1102 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1103}
1104
1105TEST_F(PortTest, TestARNatToTurn) {
1106 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1107}
1108
1109TEST_F(PortTest, TestARNatToGturn) {
1110 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1111}
1112
1113TEST_F(PortTest, TestARNATNatToTcpGturn) {
1114 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1115}
1116
1117// Port-restricted NAT -> XXXX
1118TEST_F(PortTest, TestPRNatToLocal) {
1119 TestStunToLocal(NAT_PORT_RESTRICTED);
1120}
1121
1122TEST_F(PortTest, TestPRNatToConeNat) {
1123 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1124}
1125
1126TEST_F(PortTest, TestPRNatToARNat) {
1127 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1128}
1129
1130TEST_F(PortTest, TestPRNatToPRNat) {
1131 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1132}
1133
1134TEST_F(PortTest, TestPRNatToSymNat) {
1135 // Will "fail"
1136 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1137}
1138
1139TEST_F(PortTest, TestPRNatToTurn) {
1140 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1141}
1142
1143TEST_F(PortTest, TestPRNatToGturn) {
1144 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1145}
1146
1147TEST_F(PortTest, TestPRNatToTcpGturn) {
1148 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1149}
1150
1151// Symmetric NAT -> XXXX
1152TEST_F(PortTest, TestSymNatToLocal) {
1153 TestStunToLocal(NAT_SYMMETRIC);
1154}
1155
1156TEST_F(PortTest, TestSymNatToConeNat) {
1157 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1158}
1159
1160TEST_F(PortTest, TestSymNatToARNat) {
1161 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1162}
1163
1164TEST_F(PortTest, TestSymNatToPRNat) {
1165 // Will "fail"
1166 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1167}
1168
1169TEST_F(PortTest, TestSymNatToSymNat) {
1170 // Will "fail"
1171 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1172}
1173
1174TEST_F(PortTest, TestSymNatToTurn) {
1175 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1176}
1177
1178TEST_F(PortTest, TestSymNatToGturn) {
1179 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1180}
1181
1182TEST_F(PortTest, TestSymNatToTcpGturn) {
1183 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1184}
1185
1186// Outbound TCP -> XXXX
1187TEST_F(PortTest, TestTcpToTcp) {
1188 TestTcpToTcp();
1189}
1190
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001191TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1192 TestTcpReconnect(false /* ping */, true /* send */);
1193}
1194
1195TEST_F(PortTest, TestTcpReconnectOnPing) {
1196 TestTcpReconnect(true /* ping */, false /* send */);
1197}
1198
1199TEST_F(PortTest, TestTcpReconnectTimeout) {
1200 TestTcpReconnect(false /* ping */, false /* send */);
1201}
1202
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001203// Test when TcpConnection never connects, the OnClose() will be called to
1204// destroy the connection.
1205TEST_F(PortTest, TestTcpNeverConnect) {
1206 Port* port1 = CreateTcpPort(kLocalAddr1);
1207 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1208 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1209
1210 // Set up a channel and ensure the port will be deleted.
1211 TestChannel ch1(port1);
1212 EXPECT_EQ(0, ch1.complete_count());
1213
1214 ch1.Start();
1215 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1216
1217 rtc::scoped_ptr<rtc::AsyncSocket> server(
1218 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1219 // Bind but not listen.
1220 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1221
1222 Candidate c = GetCandidate(port1);
1223 c.set_address(server->GetLocalAddress());
1224
1225 ch1.CreateConnection(c);
1226 EXPECT_TRUE(ch1.conn());
1227 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1228}
1229
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001230/* TODO: Enable these once testrelayserver can accept external TCP.
1231TEST_F(PortTest, TestTcpToTcpRelay) {
1232 TestTcpToRelay(PROTO_TCP);
1233}
1234
1235TEST_F(PortTest, TestTcpToSslTcpRelay) {
1236 TestTcpToRelay(PROTO_SSLTCP);
1237}
1238*/
1239
1240// Outbound SSLTCP -> XXXX
1241/* TODO: Enable these once testrelayserver can accept external SSL.
1242TEST_F(PortTest, TestSslTcpToTcpRelay) {
1243 TestSslTcpToRelay(PROTO_TCP);
1244}
1245
1246TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1247 TestSslTcpToRelay(PROTO_SSLTCP);
1248}
1249*/
1250
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001251// Test that a connection will be dead and deleted if
1252// i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1253// since it was created, or
1254// ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1255// milliseconds since last receiving.
1256TEST_F(PortTest, TestConnectionDead) {
1257 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1258 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1259 TestChannel ch1(port1);
1260 TestChannel ch2(port2);
1261 // Acquire address.
1262 ch1.Start();
1263 ch2.Start();
1264 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1265 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
1266
honghaiz37389b42016-01-04 21:57:33 -08001267 // Test case that the connection has never received anything.
honghaiz34b11eb2016-03-16 08:55:44 -07001268 int64_t before_created = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001269 ch1.CreateConnection(GetCandidate(port2));
honghaiz34b11eb2016-03-16 08:55:44 -07001270 int64_t after_created = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001271 Connection* conn = ch1.conn();
1272 ASSERT(conn != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001273 // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned.
1274 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1275 rtc::Thread::Current()->ProcessMessages(0);
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001276 EXPECT_TRUE(ch1.conn() != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001277 // It is not dead if it is before MIN_CONNECTION_LIFETIME and pruned.
1278 conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1279 conn->Prune();
1280 rtc::Thread::Current()->ProcessMessages(0);
1281 EXPECT_TRUE(ch1.conn() != nullptr);
1282 // It will be dead after MIN_CONNECTION_LIFETIME and pruned.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001283 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1284 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1285
honghaiz37389b42016-01-04 21:57:33 -08001286 // Test case that the connection has received something.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001287 // Create a connection again and receive a ping.
1288 ch1.CreateConnection(GetCandidate(port2));
1289 conn = ch1.conn();
1290 ASSERT(conn != nullptr);
honghaiz34b11eb2016-03-16 08:55:44 -07001291 int64_t before_last_receiving = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001292 conn->ReceivedPing();
honghaiz34b11eb2016-03-16 08:55:44 -07001293 int64_t after_last_receiving = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001294 // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1295 conn->UpdateState(
1296 before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1297 rtc::Thread::Current()->ProcessMessages(100);
1298 EXPECT_TRUE(ch1.conn() != nullptr);
1299 conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1300 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1301}
1302
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001303// This test case verifies standard ICE features in STUN messages. Currently it
1304// verifies Message Integrity attribute in STUN messages and username in STUN
1305// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001306TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1308 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1309 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1311 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1312 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313 // Same parameters as TestLocalToLocal above.
1314 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1315}
1316
1317// This test is trying to validate a successful and failure scenario in a
1318// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1319// should remain equal to the request generated by the port and role of port
1320// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001321TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 rtc::scoped_ptr<TestPort> lport(
1323 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001324 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1325 lport->SetIceTiebreaker(kTiebreaker1);
1326 lport->PrepareAddress();
1327 ASSERT_FALSE(lport->Candidates().empty());
1328 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1329 Port::ORIGIN_MESSAGE);
1330 conn->Ping(0);
1331
1332 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1333 IceMessage* msg = lport->last_stun_msg();
1334 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1335 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1336 lport->last_stun_buf()->Length(),
1337 rtc::PacketTime());
1338 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1339 msg = lport->last_stun_msg();
1340 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1341
1342 // If the tiebreaker value is different from port, we expect a error
1343 // response.
1344 lport->Reset();
1345 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001346 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001347 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1348 Port::ORIGIN_MESSAGE);
1349 conn1->Ping(0);
1350
1351 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1352 msg = lport->last_stun_msg();
1353 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1354 rtc::scoped_ptr<IceMessage> modified_req(
1355 CreateStunMessage(STUN_BINDING_REQUEST));
1356 const StunByteStringAttribute* username_attr = msg->GetByteString(
1357 STUN_ATTR_USERNAME);
1358 modified_req->AddAttribute(new StunByteStringAttribute(
1359 STUN_ATTR_USERNAME, username_attr->GetString()));
1360 // To make sure we receive error response, adding tiebreaker less than
1361 // what's present in request.
1362 modified_req->AddAttribute(new StunUInt64Attribute(
1363 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1364 modified_req->AddMessageIntegrity("lpass");
1365 modified_req->AddFingerprint();
1366
1367 lport->Reset();
1368 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1369 WriteStunMessage(modified_req.get(), buf.get());
1370 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1371 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1372 msg = lport->last_stun_msg();
1373 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1374}
1375
1376// This test verifies role conflict signal is received when there is
1377// conflict in the role. In this case both ports are in controlling and
1378// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1379// value of tiebreaker, when it receives ping request from |rport| it will
1380// send role conflict signal.
1381TEST_F(PortTest, TestIceRoleConflict) {
1382 rtc::scoped_ptr<TestPort> lport(
1383 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1385 lport->SetIceTiebreaker(kTiebreaker1);
1386 rtc::scoped_ptr<TestPort> rport(
1387 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1389 rport->SetIceTiebreaker(kTiebreaker2);
1390
1391 lport->PrepareAddress();
1392 rport->PrepareAddress();
1393 ASSERT_FALSE(lport->Candidates().empty());
1394 ASSERT_FALSE(rport->Candidates().empty());
1395 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1396 Port::ORIGIN_MESSAGE);
1397 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1398 Port::ORIGIN_MESSAGE);
1399 rconn->Ping(0);
1400
1401 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1402 IceMessage* msg = rport->last_stun_msg();
1403 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1404 // Send rport binding request to lport.
1405 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1406 rport->last_stun_buf()->Length(),
1407 rtc::PacketTime());
1408
1409 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1410 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1411 EXPECT_TRUE(role_conflict());
1412}
1413
1414TEST_F(PortTest, TestTcpNoDelay) {
1415 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001416 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417 int option_value = -1;
1418 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1419 &option_value);
1420 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1421 ASSERT_EQ(1, option_value);
1422 delete port1;
1423}
1424
1425TEST_F(PortTest, TestDelayedBindingUdp) {
1426 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1427 FakePacketSocketFactory socket_factory;
1428
1429 socket_factory.set_next_udp_socket(socket);
1430 scoped_ptr<UDPPort> port(
1431 CreateUdpPort(kLocalAddr1, &socket_factory));
1432
1433 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1434 port->PrepareAddress();
1435
1436 EXPECT_EQ(0U, port->Candidates().size());
1437 socket->SignalAddressReady(socket, kLocalAddr2);
1438
1439 EXPECT_EQ(1U, port->Candidates().size());
1440}
1441
1442TEST_F(PortTest, TestDelayedBindingTcp) {
1443 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1444 FakePacketSocketFactory socket_factory;
1445
1446 socket_factory.set_next_server_tcp_socket(socket);
1447 scoped_ptr<TCPPort> port(
1448 CreateTcpPort(kLocalAddr1, &socket_factory));
1449
1450 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1451 port->PrepareAddress();
1452
1453 EXPECT_EQ(0U, port->Candidates().size());
1454 socket->SignalAddressReady(socket, kLocalAddr2);
1455
1456 EXPECT_EQ(1U, port->Candidates().size());
1457}
1458
1459void PortTest::TestCrossFamilyPorts(int type) {
1460 FakePacketSocketFactory factory;
1461 scoped_ptr<Port> ports[4];
1462 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1463 SocketAddress("192.168.1.4", 0),
1464 SocketAddress("2001:db8::1", 0),
1465 SocketAddress("2001:db8::2", 0)};
1466 for (int i = 0; i < 4; i++) {
1467 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1468 if (type == SOCK_DGRAM) {
1469 factory.set_next_udp_socket(socket);
1470 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1471 } else if (type == SOCK_STREAM) {
1472 factory.set_next_server_tcp_socket(socket);
1473 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1474 }
1475 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1476 socket->SignalAddressReady(socket, addresses[i]);
1477 ports[i]->PrepareAddress();
1478 }
1479
1480 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1481 if (type == SOCK_STREAM) {
1482 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1483 factory.set_next_client_tcp_socket(clientsocket);
1484 }
1485 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1486 Port::ORIGIN_MESSAGE);
1487 EXPECT_TRUE(NULL == c);
1488 EXPECT_EQ(0U, ports[0]->connections().size());
1489 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1490 Port::ORIGIN_MESSAGE);
1491 EXPECT_FALSE(NULL == c);
1492 EXPECT_EQ(1U, ports[0]->connections().size());
1493
1494 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1495 if (type == SOCK_STREAM) {
1496 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1497 factory.set_next_client_tcp_socket(clientsocket);
1498 }
1499 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1500 Port::ORIGIN_MESSAGE);
1501 EXPECT_TRUE(NULL == c);
1502 EXPECT_EQ(0U, ports[2]->connections().size());
1503 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1504 Port::ORIGIN_MESSAGE);
1505 EXPECT_FALSE(NULL == c);
1506 EXPECT_EQ(1U, ports[2]->connections().size());
1507}
1508
1509TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1510 TestCrossFamilyPorts(SOCK_STREAM);
1511}
1512
1513TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1514 TestCrossFamilyPorts(SOCK_DGRAM);
1515}
1516
Peter Thatcherb8b01432015-07-07 16:45:53 -07001517void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1518 Connection* c = p1->CreateConnection(GetCandidate(p2),
1519 Port::ORIGIN_MESSAGE);
1520 if (can_connect) {
1521 EXPECT_FALSE(NULL == c);
1522 EXPECT_EQ(1U, p1->connections().size());
1523 } else {
1524 EXPECT_TRUE(NULL == c);
1525 EXPECT_EQ(0U, p1->connections().size());
1526 }
1527}
1528
1529TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1530 FakePacketSocketFactory factory;
1531 scoped_ptr<Port> ports[4];
1532 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1533 SocketAddress("fe80::1", 0),
1534 SocketAddress("fe80::2", 0),
1535 SocketAddress("::1", 0)};
1536 for (int i = 0; i < 4; i++) {
1537 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1538 factory.set_next_udp_socket(socket);
1539 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1540 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1541 socket->SignalAddressReady(socket, addresses[i]);
1542 ports[i]->PrepareAddress();
1543 }
1544
1545 Port* standard = ports[0].get();
1546 Port* link_local1 = ports[1].get();
1547 Port* link_local2 = ports[2].get();
1548 Port* localhost = ports[3].get();
1549
1550 ExpectPortsCanConnect(false, link_local1, standard);
1551 ExpectPortsCanConnect(false, standard, link_local1);
1552 ExpectPortsCanConnect(false, link_local1, localhost);
1553 ExpectPortsCanConnect(false, localhost, link_local1);
1554
1555 ExpectPortsCanConnect(true, link_local1, link_local2);
1556 ExpectPortsCanConnect(true, localhost, standard);
1557 ExpectPortsCanConnect(true, standard, localhost);
1558}
1559
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001560// This test verifies DSCP value set through SetOption interface can be
1561// get through DefaultDscpValue.
1562TEST_F(PortTest, TestDefaultDscpValue) {
1563 int dscp;
1564 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1565 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1566 rtc::DSCP_CS6));
1567 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1568 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1569 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1570 rtc::DSCP_AF31));
1571 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1572 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1573 rtc::scoped_ptr<StunPort> stunport(
1574 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1575 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1576 rtc::DSCP_AF41));
1577 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1578 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1579 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1580 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1581 // Socket is created in PrepareAddress.
1582 turnport1->PrepareAddress();
1583 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1584 rtc::DSCP_CS7));
1585 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1586 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1587 // This will verify correct value returned without the socket.
1588 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1589 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1590 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1591 rtc::DSCP_CS6));
1592 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1593 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1594}
1595
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001596// Test sending STUN messages.
1597TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001598 rtc::scoped_ptr<TestPort> lport(
1599 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1600 rtc::scoped_ptr<TestPort> rport(
1601 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001602 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1603 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001604 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1605 rport->SetIceTiebreaker(kTiebreaker2);
1606
1607 // Send a fake ping from lport to rport.
1608 lport->PrepareAddress();
1609 rport->PrepareAddress();
1610 ASSERT_FALSE(rport->Candidates().empty());
1611 Connection* lconn = lport->CreateConnection(
1612 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1613 Connection* rconn = rport->CreateConnection(
1614 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1615 lconn->Ping(0);
1616
1617 // Check that it's a proper BINDING-REQUEST.
1618 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1619 IceMessage* msg = lport->last_stun_msg();
1620 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1621 EXPECT_FALSE(msg->IsLegacy());
1622 const StunByteStringAttribute* username_attr =
1623 msg->GetByteString(STUN_ATTR_USERNAME);
1624 ASSERT_TRUE(username_attr != NULL);
1625 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1626 ASSERT_TRUE(priority_attr != NULL);
1627 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1628 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1629 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1630 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1631 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1632 "rpass"));
1633 const StunUInt64Attribute* ice_controlling_attr =
1634 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1635 ASSERT_TRUE(ice_controlling_attr != NULL);
1636 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1637 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1638 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1639 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1640 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1641 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1642
1643 // Request should not include ping count.
1644 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1645
1646 // Save a copy of the BINDING-REQUEST for use below.
1647 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1648
1649 // Respond with a BINDING-RESPONSE.
1650 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1651 msg = rport->last_stun_msg();
1652 ASSERT_TRUE(msg != NULL);
1653 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1654
1655
1656 EXPECT_FALSE(msg->IsLegacy());
1657 const StunAddressAttribute* addr_attr = msg->GetAddress(
1658 STUN_ATTR_XOR_MAPPED_ADDRESS);
1659 ASSERT_TRUE(addr_attr != NULL);
1660 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1661 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1662 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1663 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1664 "rpass"));
1665 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1666 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1667 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1668 // No USERNAME or PRIORITY in ICE responses.
1669 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1670 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1671 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1672 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1673 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1674 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1675
1676 // Response should not include ping count.
1677 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1678
1679 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1680 // but we can do it here.
1681 rport->SendBindingErrorResponse(request.get(),
1682 lport->Candidates()[0].address(),
1683 STUN_ERROR_SERVER_ERROR,
1684 STUN_ERROR_REASON_SERVER_ERROR);
1685 msg = rport->last_stun_msg();
1686 ASSERT_TRUE(msg != NULL);
1687 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1688 EXPECT_FALSE(msg->IsLegacy());
1689 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1690 ASSERT_TRUE(error_attr != NULL);
1691 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1692 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1693 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1694 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1695 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1696 "rpass"));
1697 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1698 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1699 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1700 // No USERNAME with ICE.
1701 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1702 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1703
1704 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1705 // and (incremented) RETRANSMIT_COUNT attributes.
1706 rport->Reset();
1707 rport->set_send_retransmit_count_attribute(true);
1708 rconn->Ping(0);
1709 rconn->Ping(0);
1710 rconn->Ping(0);
1711 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1712 msg = rport->last_stun_msg();
1713 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1714 const StunUInt64Attribute* ice_controlled_attr =
1715 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1716 ASSERT_TRUE(ice_controlled_attr != NULL);
1717 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1718 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1719
1720 // Request should include ping count.
1721 const StunUInt32Attribute* retransmit_attr =
1722 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1723 ASSERT_TRUE(retransmit_attr != NULL);
1724 EXPECT_EQ(2U, retransmit_attr->value());
1725
1726 // Respond with a BINDING-RESPONSE.
1727 request.reset(CopyStunMessage(msg));
1728 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1729 msg = lport->last_stun_msg();
1730
1731 // Response should include same ping count.
1732 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1733 ASSERT_TRUE(retransmit_attr != NULL);
1734 EXPECT_EQ(2U, retransmit_attr->value());
1735}
1736
1737TEST_F(PortTest, TestUseCandidateAttribute) {
1738 rtc::scoped_ptr<TestPort> lport(
1739 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1740 rtc::scoped_ptr<TestPort> rport(
1741 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001742 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1743 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001744 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1745 rport->SetIceTiebreaker(kTiebreaker2);
1746
1747 // Send a fake ping from lport to rport.
1748 lport->PrepareAddress();
1749 rport->PrepareAddress();
1750 ASSERT_FALSE(rport->Candidates().empty());
1751 Connection* lconn = lport->CreateConnection(
1752 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1753 lconn->Ping(0);
1754 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1755 IceMessage* msg = lport->last_stun_msg();
1756 const StunUInt64Attribute* ice_controlling_attr =
1757 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1758 ASSERT_TRUE(ice_controlling_attr != NULL);
1759 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1760 STUN_ATTR_USE_CANDIDATE);
1761 ASSERT_TRUE(use_candidate_attr != NULL);
1762}
1763
honghaiza0c44ea2016-03-23 16:07:48 -07001764TEST_F(PortTest, TestNetworkInfoAttribute) {
1765 rtc::scoped_ptr<TestPort> lport(
1766 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1767 // Set the network type for rport to be cellular so its cost will be 999.
1768 SetNetworkType(rtc::ADAPTER_TYPE_CELLULAR);
1769 rtc::scoped_ptr<TestPort> rport(
1770 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1771 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1772 lport->SetIceTiebreaker(kTiebreaker1);
1773 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1774 rport->SetIceTiebreaker(kTiebreaker2);
1775
1776 uint16_t lnetwork_id = 9;
1777 lport->Network()->set_id(lnetwork_id);
1778 // Send a fake ping from lport to rport.
1779 lport->PrepareAddress();
1780 rport->PrepareAddress();
1781 Connection* lconn =
1782 lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1783 lconn->Ping(0);
1784 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1785 IceMessage* msg = lport->last_stun_msg();
1786 const StunUInt32Attribute* network_info_attr =
1787 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1788 ASSERT_TRUE(network_info_attr != NULL);
1789 uint32_t network_info = network_info_attr->value();
1790 EXPECT_EQ(lnetwork_id, network_info >> 16);
1791 // Default network cost is 0.
1792 EXPECT_EQ(0U, network_info & 0xFFFF);
1793
1794 // Send a fake ping from rport to lport.
1795 uint16_t rnetwork_id = 8;
1796 rport->Network()->set_id(rnetwork_id);
1797 Connection* rconn =
1798 rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1799 rconn->Ping(0);
1800 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1801 msg = rport->last_stun_msg();
1802 network_info_attr = msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1803 ASSERT_TRUE(network_info_attr != NULL);
1804 network_info = network_info_attr->value();
1805 EXPECT_EQ(rnetwork_id, network_info >> 16);
1806 EXPECT_EQ(cricket::kMaxNetworkCost, network_info & 0xFFFF);
1807}
1808
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001809// Test handling STUN messages.
1810TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001811 // Our port will act as the "remote" port.
1812 rtc::scoped_ptr<TestPort> port(
1813 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001814
1815 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1816 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1817 rtc::SocketAddress addr(kLocalAddr1);
1818 std::string username;
1819
1820 // BINDING-REQUEST from local to remote with valid ICE username,
1821 // MESSAGE-INTEGRITY, and FINGERPRINT.
1822 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1823 "rfrag:lfrag"));
1824 in_msg->AddMessageIntegrity("rpass");
1825 in_msg->AddFingerprint();
1826 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001827 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1828 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001829 EXPECT_TRUE(out_msg.get() != NULL);
1830 EXPECT_EQ("lfrag", username);
1831
1832 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1833 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1834 in_msg->AddAttribute(
1835 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1836 in_msg->AddMessageIntegrity("rpass");
1837 in_msg->AddFingerprint();
1838 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001839 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1840 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001841 EXPECT_TRUE(out_msg.get() != NULL);
1842 EXPECT_EQ("", username);
1843
1844 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1845 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1846 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1847 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1848 in_msg->AddFingerprint();
1849 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001850 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1851 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001852 EXPECT_TRUE(out_msg.get() != NULL);
1853 EXPECT_EQ("", username);
1854 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1855 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1856 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1857 out_msg->GetErrorCode()->reason());
1858}
1859
guoweisd12140a2015-09-10 13:32:11 -07001860// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001861TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001862 rtc::scoped_ptr<TestPort> port(
1863 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001864
1865 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1866 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1867 rtc::SocketAddress addr(kLocalAddr1);
1868 std::string username;
1869
1870 // BINDING-REQUEST with no username.
1871 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1872 in_msg->AddMessageIntegrity("rpass");
1873 in_msg->AddFingerprint();
1874 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001875 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1876 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001877 EXPECT_TRUE(out_msg.get() == NULL);
1878 EXPECT_EQ("", username);
1879 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1880
1881 // BINDING-REQUEST with empty username.
1882 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1883 in_msg->AddMessageIntegrity("rpass");
1884 in_msg->AddFingerprint();
1885 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001886 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1887 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001888 EXPECT_TRUE(out_msg.get() == NULL);
1889 EXPECT_EQ("", username);
1890 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1891
1892 // BINDING-REQUEST with too-short username.
1893 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1894 in_msg->AddMessageIntegrity("rpass");
1895 in_msg->AddFingerprint();
1896 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001897 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1898 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001899 EXPECT_TRUE(out_msg.get() == NULL);
1900 EXPECT_EQ("", username);
1901 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1902
1903 // BINDING-REQUEST with reversed username.
1904 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1905 "lfrag:rfrag"));
1906 in_msg->AddMessageIntegrity("rpass");
1907 in_msg->AddFingerprint();
1908 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001909 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1910 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001911 EXPECT_TRUE(out_msg.get() == NULL);
1912 EXPECT_EQ("", username);
1913 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1914
1915 // BINDING-REQUEST with garbage username.
1916 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1917 "abcd:efgh"));
1918 in_msg->AddMessageIntegrity("rpass");
1919 in_msg->AddFingerprint();
1920 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001921 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1922 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001923 EXPECT_TRUE(out_msg.get() == NULL);
1924 EXPECT_EQ("", username);
1925 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1926}
1927
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001928// Test handling STUN messages with missing or malformed M-I.
1929TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001930 // Our port will act as the "remote" port.
1931 rtc::scoped_ptr<TestPort> port(
1932 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001933
1934 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1935 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1936 rtc::SocketAddress addr(kLocalAddr1);
1937 std::string username;
1938
1939 // BINDING-REQUEST from local to remote with valid ICE username and
1940 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1941 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1942 "rfrag:lfrag"));
1943 in_msg->AddFingerprint();
1944 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001945 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1946 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001947 EXPECT_TRUE(out_msg.get() == NULL);
1948 EXPECT_EQ("", username);
1949 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1950
1951 // BINDING-REQUEST from local to remote with valid ICE username and
1952 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1953 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1954 "rfrag:lfrag"));
1955 in_msg->AddMessageIntegrity("invalid");
1956 in_msg->AddFingerprint();
1957 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001958 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1959 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001960 EXPECT_TRUE(out_msg.get() == NULL);
1961 EXPECT_EQ("", username);
1962 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1963
1964 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1965 // by the Connection, not the Port, since they require the remote username.
1966 // Change this test to pass in data via Connection::OnReadPacket instead.
1967}
1968
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001969// Test handling STUN messages with missing or malformed FINGERPRINT.
1970TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001971 // Our port will act as the "remote" port.
1972 rtc::scoped_ptr<TestPort> port(
1973 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001974
1975 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1976 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1977 rtc::SocketAddress addr(kLocalAddr1);
1978 std::string username;
1979
1980 // BINDING-REQUEST from local to remote with valid ICE username and
1981 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1982 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1983 "rfrag:lfrag"));
1984 in_msg->AddMessageIntegrity("rpass");
1985 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001986 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1987 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001988 EXPECT_EQ(0, port->last_stun_error_code());
1989
1990 // Now, add a fingerprint, but munge the message so it's not valid.
1991 in_msg->AddFingerprint();
1992 in_msg->SetTransactionID("TESTTESTBADD");
1993 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001994 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1995 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001996 EXPECT_EQ(0, port->last_stun_error_code());
1997
1998 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1999 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
2000 in_msg->AddAttribute(
2001 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
2002 in_msg->AddMessageIntegrity("rpass");
2003 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002004 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2005 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002006 EXPECT_EQ(0, port->last_stun_error_code());
2007
2008 // Now, add a fingerprint, but munge the message so it's not valid.
2009 in_msg->AddFingerprint();
2010 in_msg->SetTransactionID("TESTTESTBADD");
2011 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002012 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2013 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002014 EXPECT_EQ(0, port->last_stun_error_code());
2015
2016 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
2017 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
2018 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
2019 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
2020 in_msg->AddMessageIntegrity("rpass");
2021 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002022 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2023 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002024 EXPECT_EQ(0, port->last_stun_error_code());
2025
2026 // Now, add a fingerprint, but munge the message so it's not valid.
2027 in_msg->AddFingerprint();
2028 in_msg->SetTransactionID("TESTTESTBADD");
2029 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002030 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2031 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002032 EXPECT_EQ(0, port->last_stun_error_code());
2033}
2034
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002035// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002036// indications are allowed only to the connection which is in read mode.
2037TEST_F(PortTest, TestHandleStunBindingIndication) {
2038 rtc::scoped_ptr<TestPort> lport(
2039 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002040 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2041 lport->SetIceTiebreaker(kTiebreaker1);
2042
2043 // Verifying encoding and decoding STUN indication message.
2044 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
2045 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
2046 rtc::SocketAddress addr(kLocalAddr1);
2047 std::string username;
2048
2049 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
2050 in_msg->AddFingerprint();
2051 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002052 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2053 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002054 EXPECT_TRUE(out_msg.get() != NULL);
2055 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2056 EXPECT_EQ("", username);
2057
2058 // Verify connection can handle STUN indication and updates
2059 // last_ping_received.
2060 rtc::scoped_ptr<TestPort> rport(
2061 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002062 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2063 rport->SetIceTiebreaker(kTiebreaker2);
2064
2065 lport->PrepareAddress();
2066 rport->PrepareAddress();
2067 ASSERT_FALSE(lport->Candidates().empty());
2068 ASSERT_FALSE(rport->Candidates().empty());
2069
2070 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2071 Port::ORIGIN_MESSAGE);
2072 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2073 Port::ORIGIN_MESSAGE);
2074 rconn->Ping(0);
2075
2076 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2077 IceMessage* msg = rport->last_stun_msg();
2078 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2079 // Send rport binding request to lport.
2080 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
2081 rport->last_stun_buf()->Length(),
2082 rtc::PacketTime());
2083 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2084 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
honghaiz34b11eb2016-03-16 08:55:44 -07002085 int64_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002086
2087 // Adding a delay of 100ms.
2088 rtc::Thread::Current()->ProcessMessages(100);
2089 // Pinging lconn using stun indication message.
2090 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
honghaiz34b11eb2016-03-16 08:55:44 -07002091 int64_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002092 EXPECT_GT(last_ping_received2, last_ping_received1);
2093}
2094
2095TEST_F(PortTest, TestComputeCandidatePriority) {
2096 rtc::scoped_ptr<TestPort> port(
2097 CreateTestPort(kLocalAddr1, "name", "pass"));
2098 port->set_type_preference(90);
2099 port->set_component(177);
2100 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2101 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2102 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2103 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2104 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2105 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2106 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2107 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2108 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2109 // These should all be:
2110 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002111 uint32_t expected_priority_v4 = 1509957199U;
2112 uint32_t expected_priority_v6 = 1509959759U;
2113 uint32_t expected_priority_ula = 1509962319U;
2114 uint32_t expected_priority_v4mapped = expected_priority_v4;
2115 uint32_t expected_priority_v4compat = 1509949775U;
2116 uint32_t expected_priority_6to4 = 1509954639U;
2117 uint32_t expected_priority_teredo = 1509952079U;
2118 uint32_t expected_priority_sitelocal = 1509949775U;
2119 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002120 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2121 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2122 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2123 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2124 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2125 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2126 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2127 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2128 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2129}
2130
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002131// In the case of shared socket, one port may be shared by local and stun.
2132// Test that candidates with different types will have different foundation.
2133TEST_F(PortTest, TestFoundation) {
2134 rtc::scoped_ptr<TestPort> testport(
2135 CreateTestPort(kLocalAddr1, "name", "pass"));
2136 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2137 LOCAL_PORT_TYPE,
2138 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2139 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2140 STUN_PORT_TYPE,
2141 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2142 EXPECT_NE(testport->Candidates()[0].foundation(),
2143 testport->Candidates()[1].foundation());
2144}
2145
2146// This test verifies the foundation of different types of ICE candidates.
2147TEST_F(PortTest, TestCandidateFoundation) {
2148 rtc::scoped_ptr<rtc::NATServer> nat_server(
2149 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2150 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2151 udpport1->PrepareAddress();
2152 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2153 udpport2->PrepareAddress();
2154 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2155 udpport2->Candidates()[0].foundation());
2156 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2157 tcpport1->PrepareAddress();
2158 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2159 tcpport2->PrepareAddress();
2160 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2161 tcpport2->Candidates()[0].foundation());
2162 rtc::scoped_ptr<Port> stunport(
2163 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2164 stunport->PrepareAddress();
2165 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2166 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2167 stunport->Candidates()[0].foundation());
2168 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2169 stunport->Candidates()[0].foundation());
2170 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2171 stunport->Candidates()[0].foundation());
2172 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2173 stunport->Candidates()[0].foundation());
2174 // Verify GTURN candidate foundation.
2175 rtc::scoped_ptr<RelayPort> relayport(
2176 CreateGturnPort(kLocalAddr1));
2177 relayport->AddServerAddress(
2178 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2179 relayport->PrepareAddress();
2180 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2181 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2182 relayport->Candidates()[0].foundation());
2183 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2184 relayport->Candidates()[0].foundation());
2185 // Verifying TURN candidate foundation.
2186 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2187 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2188 turnport1->PrepareAddress();
2189 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2190 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2191 turnport1->Candidates()[0].foundation());
2192 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2193 turnport1->Candidates()[0].foundation());
2194 EXPECT_NE(stunport->Candidates()[0].foundation(),
2195 turnport1->Candidates()[0].foundation());
2196 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2197 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2198 turnport2->PrepareAddress();
2199 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2200 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2201 turnport2->Candidates()[0].foundation());
2202
2203 // Running a second turn server, to get different base IP address.
2204 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2205 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2206 TestTurnServer turn_server2(
2207 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2208 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2209 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2210 kTurnUdpIntAddr2));
2211 turnport3->PrepareAddress();
2212 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2213 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2214 turnport2->Candidates()[0].foundation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08002215
2216 // Start a TCP turn server, and check that two turn candidates have
2217 // different foundations if their relay protocols are different.
2218 TestTurnServer turn_server3(rtc::Thread::Current(), kTurnTcpIntAddr,
2219 kTurnUdpExtAddr, PROTO_TCP);
2220 rtc::scoped_ptr<Port> turnport4(
2221 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_TCP, PROTO_UDP));
2222 turnport4->PrepareAddress();
2223 ASSERT_EQ_WAIT(1U, turnport4->Candidates().size(), kTimeout);
2224 EXPECT_NE(turnport2->Candidates()[0].foundation(),
2225 turnport4->Candidates()[0].foundation());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002226}
2227
2228// This test verifies the related addresses of different types of
2229// ICE candiates.
2230TEST_F(PortTest, TestCandidateRelatedAddress) {
2231 rtc::scoped_ptr<rtc::NATServer> nat_server(
2232 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2233 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2234 udpport->PrepareAddress();
2235 // For UDPPort, related address will be empty.
2236 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2237 // Testing related address for stun candidates.
2238 // For stun candidate related address must be equal to the base
2239 // socket address.
2240 rtc::scoped_ptr<StunPort> stunport(
2241 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2242 stunport->PrepareAddress();
2243 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2244 // Check STUN candidate address.
2245 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2246 kNatAddr1.ipaddr());
2247 // Check STUN candidate related address.
2248 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2249 stunport->GetLocalAddress());
2250 // Verifying the related address for the GTURN candidates.
2251 // NOTE: In case of GTURN related address will be equal to the mapped
2252 // address, but address(mapped) will not be XOR.
2253 rtc::scoped_ptr<RelayPort> relayport(
2254 CreateGturnPort(kLocalAddr1));
2255 relayport->AddServerAddress(
2256 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2257 relayport->PrepareAddress();
2258 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2259 // For Gturn related address is set to "0.0.0.0:0"
2260 EXPECT_EQ(rtc::SocketAddress(),
2261 relayport->Candidates()[0].related_address());
2262 // Verifying the related address for TURN candidate.
2263 // For TURN related address must be equal to the mapped address.
2264 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2265 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2266 turnport->PrepareAddress();
2267 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2268 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2269 turnport->Candidates()[0].address().ipaddr());
2270 EXPECT_EQ(kNatAddr1.ipaddr(),
2271 turnport->Candidates()[0].related_address().ipaddr());
2272}
2273
2274// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002275TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002276 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002277 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002278 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002279 cand2.set_priority(1);
2280 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002281}
2282
2283// Test the Connection priority is calculated correctly.
2284TEST_F(PortTest, TestConnectionPriority) {
2285 rtc::scoped_ptr<TestPort> lport(
2286 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2287 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2288 rtc::scoped_ptr<TestPort> rport(
2289 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2290 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2291 lport->set_component(123);
2292 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2293 rport->set_component(23);
2294 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2295
2296 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2297 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2298
2299 // RFC 5245
2300 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2301 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2302 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2303 Connection* lconn = lport->CreateConnection(
2304 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2305#if defined(WEBRTC_WIN)
2306 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2307#else
2308 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2309#endif
2310
2311 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2312 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2313 Connection* rconn = rport->CreateConnection(
2314 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2315#if defined(WEBRTC_WIN)
2316 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2317#else
2318 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2319#endif
2320}
2321
2322TEST_F(PortTest, TestWritableState) {
2323 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002324 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002325 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002326 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002327
2328 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002329 TestChannel ch1(port1);
2330 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002331
2332 // Acquire addresses.
2333 ch1.Start();
2334 ch2.Start();
2335 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2336 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2337
2338 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002339 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002340 ASSERT_TRUE(ch1.conn() != NULL);
2341 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2342 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2343 ch1.Ping();
2344 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2345
2346 // Data should be unsendable until the connection is accepted.
2347 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002348 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002349 rtc::PacketOptions options;
2350 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2351
2352 // Accept the connection to return the binding response, transition to
2353 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002354 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002355 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2356 kTimeout);
2357 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2358
2359 // Ask the connection to update state as if enough time has passed to lose
2360 // full writability and 5 pings went unresponded to. We'll accomplish the
2361 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002362 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002363 ch1.Ping(i);
2364 }
honghaiz34b11eb2016-03-16 08:55:44 -07002365 int unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002366 ch1.conn()->UpdateState(unreliable_timeout_delay);
2367 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2368
2369 // Data should be able to be sent in this state.
2370 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2371
2372 // And now allow the other side to process the pings and send binding
2373 // responses.
2374 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2375 kTimeout);
2376
2377 // Wait long enough for a full timeout (past however long we've already
2378 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002379 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002380 ch1.Ping(unreliable_timeout_delay + i);
2381 }
2382 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2383 500u);
2384 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2385
2386 // Now that the connection has completely timed out, data send should fail.
2387 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2388
2389 ch1.Stop();
2390 ch2.Stop();
2391}
2392
2393TEST_F(PortTest, TestTimeoutForNeverWritable) {
2394 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002395 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002396 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002397 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002398
2399 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002400 TestChannel ch1(port1);
2401 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002402
2403 // Acquire addresses.
2404 ch1.Start();
2405 ch2.Start();
2406
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002407 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002408 ASSERT_TRUE(ch1.conn() != NULL);
2409 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2410
2411 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002412 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002413 ch1.Ping(i);
2414 }
2415 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2416 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2417}
2418
2419// This test verifies the connection setup between ICEMODE_FULL
2420// and ICEMODE_LITE.
2421// In this test |ch1| behaves like FULL mode client and we have created
2422// port which responds to the ping message just like LITE client.
2423TEST_F(PortTest, TestIceLiteConnectivity) {
2424 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002425 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002426 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2427
2428 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002429 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002430 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2431 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002432 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002433 ch1.SetIceMode(ICEMODE_FULL);
2434
2435 // Start gathering candidates.
2436 ch1.Start();
2437 ice_lite_port->PrepareAddress();
2438
2439 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2440 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2441
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002442 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002443 ASSERT_TRUE(ch1.conn() != NULL);
2444 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2445
2446 // Send ping from full mode client.
2447 // This ping must not have USE_CANDIDATE_ATTR.
2448 ch1.Ping();
2449
2450 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2451 // from port.
2452 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2453 IceMessage* msg = ice_full_port->last_stun_msg();
2454 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2455
2456 // Respond with a BINDING-RESPONSE from litemode client.
2457 // NOTE: Ideally we should't create connection at this stage from lite
2458 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2459 // But we need a connection to send a response message.
2460 ice_lite_port->CreateConnection(
2461 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2462 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2463 ice_lite_port->SendBindingResponse(
2464 request.get(), ice_full_port->Candidates()[0].address());
2465
2466 // Feeding the respone message from litemode to the full mode connection.
2467 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2468 ice_lite_port->last_stun_buf()->Length(),
2469 rtc::PacketTime());
2470 // Verifying full mode connection becomes writable from the response.
2471 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2472 kTimeout);
2473 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2474
2475 // Clear existing stun messsages. Otherwise we will process old stun
2476 // message right after we send ping.
2477 ice_full_port->Reset();
2478 // Send ping. This must have USE_CANDIDATE_ATTR.
2479 ch1.Ping();
2480 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2481 msg = ice_full_port->last_stun_msg();
2482 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2483 ch1.Stop();
2484}
2485
2486// This test case verifies that the CONTROLLING port does not time out.
2487TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002488 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2489 ConnectToSignalDestroyed(port1);
2490 port1->set_timeout_delay(10); // milliseconds
2491 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2492 port1->SetIceTiebreaker(kTiebreaker1);
2493
2494 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2495 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2496 port2->SetIceTiebreaker(kTiebreaker2);
2497
2498 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002499 TestChannel ch1(port1);
2500 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002501
2502 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002503 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002504
2505 // After the connection is destroyed, the port should not be destroyed.
2506 rtc::Thread::Current()->ProcessMessages(kTimeout);
2507 EXPECT_FALSE(destroyed());
2508}
2509
2510// This test case verifies that the CONTROLLED port does time out, but only
2511// after connectivity is lost.
2512TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002513 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2514 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2515 port1->SetIceTiebreaker(kTiebreaker1);
2516
2517 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2518 ConnectToSignalDestroyed(port2);
2519 port2->set_timeout_delay(10); // milliseconds
2520 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2521 port2->SetIceTiebreaker(kTiebreaker2);
2522
2523 // The connection must not be destroyed before a connection is attempted.
2524 EXPECT_FALSE(destroyed());
2525
2526 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2527 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2528
2529 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002530 TestChannel ch1(port1);
2531 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002532
2533 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002534 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002535
2536 // The controlled port should be destroyed after 10 milliseconds.
2537 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2538}
honghaizd0b31432015-09-30 12:42:17 -07002539
2540// This test case verifies that if the role of a port changes from controlled
2541// to controlling after all connections fail, the port will not be destroyed.
2542TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2543 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2544 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2545 port1->SetIceTiebreaker(kTiebreaker1);
2546
2547 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2548 ConnectToSignalDestroyed(port2);
2549 port2->set_timeout_delay(10); // milliseconds
2550 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2551 port2->SetIceTiebreaker(kTiebreaker2);
2552
2553 // The connection must not be destroyed before a connection is attempted.
2554 EXPECT_FALSE(destroyed());
2555
2556 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2557 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2558
2559 // Set up channels and ensure both ports will be deleted.
2560 TestChannel ch1(port1);
2561 TestChannel ch2(port2);
2562
2563 // Simulate a connection that succeeds, and then is destroyed.
2564 StartConnectAndStopChannels(&ch1, &ch2);
2565 // Switch the role after all connections are destroyed.
2566 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2567 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2568 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2569
2570 // After the connection is destroyed, the port should not be destroyed.
2571 rtc::Thread::Current()->ProcessMessages(kTimeout);
2572 EXPECT_FALSE(destroyed());
2573}
Honghai Zhangf9945b22015-12-15 12:20:13 -08002574
2575TEST_F(PortTest, TestSupportsProtocol) {
2576 rtc::scoped_ptr<Port> udp_port(CreateUdpPort(kLocalAddr1));
2577 EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2578 EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2579
2580 rtc::scoped_ptr<Port> stun_port(
2581 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2582 EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2583 EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2584
2585 rtc::scoped_ptr<Port> tcp_port(CreateTcpPort(kLocalAddr1));
2586 EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2587 EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
2588 EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2589
2590 rtc::scoped_ptr<Port> turn_port(
2591 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2592 EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2593 EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2594}