blob: 4c262bc93e04ae08686b2bdde32192cdaa7af588 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/basicpacketsocketfactory.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012#include "webrtc/p2p/base/relayport.h"
13#include "webrtc/p2p/base/stunport.h"
14#include "webrtc/p2p/base/tcpport.h"
15#include "webrtc/p2p/base/testrelayserver.h"
16#include "webrtc/p2p/base/teststunserver.h"
17#include "webrtc/p2p/base/testturnserver.h"
18#include "webrtc/p2p/base/transport.h"
19#include "webrtc/p2p/base/turnport.h"
20#include "webrtc/base/crc32.h"
21#include "webrtc/base/gunit.h"
22#include "webrtc/base/helpers.h"
23#include "webrtc/base/logging.h"
24#include "webrtc/base/natserver.h"
25#include "webrtc/base/natsocketfactory.h"
26#include "webrtc/base/physicalsocketserver.h"
27#include "webrtc/base/scoped_ptr.h"
28#include "webrtc/base/socketaddress.h"
29#include "webrtc/base/ssladapter.h"
30#include "webrtc/base/stringutils.h"
31#include "webrtc/base/thread.h"
32#include "webrtc/base/virtualsocketserver.h"
33
34using rtc::AsyncPacketSocket;
35using rtc::ByteBuffer;
36using rtc::NATType;
37using rtc::NAT_OPEN_CONE;
38using rtc::NAT_ADDR_RESTRICTED;
39using rtc::NAT_PORT_RESTRICTED;
40using rtc::NAT_SYMMETRIC;
41using rtc::PacketSocketFactory;
42using rtc::scoped_ptr;
43using rtc::Socket;
44using rtc::SocketAddress;
45using namespace cricket;
46
47static const int kTimeout = 1000;
48static const SocketAddress kLocalAddr1("192.168.1.2", 0);
49static const SocketAddress kLocalAddr2("192.168.1.3", 0);
deadbeefc5d0d952015-07-16 10:22:21 -070050static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
51static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_UDP_PORT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
53static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
54static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
55static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
56static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
57static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
58static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
59static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
60static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
61static const RelayCredentials kRelayCredentials("test", "test");
62
63// TODO: Update these when RFC5245 is completely supported.
64// Magic value of 30 is from RFC3484, for IPv4 addresses.
65static const uint32 kDefaultPrflxPriority = ICE_TYPE_PREFERENCE_PRFLX << 24 |
66 30 << 8 | (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68static const int kTiebreaker1 = 11111;
69static const int kTiebreaker2 = 22222;
70
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070071static const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
72
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073static Candidate GetCandidate(Port* port) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -070074 assert(port->Candidates().size() >= 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000075 return port->Candidates()[0];
76}
77
78static SocketAddress GetAddress(Port* port) {
79 return GetCandidate(port).address();
80}
81
82static IceMessage* CopyStunMessage(const IceMessage* src) {
83 IceMessage* dst = new IceMessage();
84 ByteBuffer buf;
85 src->Write(&buf);
86 dst->Read(&buf);
87 return dst;
88}
89
90static bool WriteStunMessage(const StunMessage* msg, ByteBuffer* buf) {
91 buf->Resize(0); // clear out any existing buffer contents
92 return msg->Write(buf);
93}
94
95// Stub port class for testing STUN generation and processing.
96class TestPort : public Port {
97 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +000098 TestPort(rtc::Thread* thread,
99 const std::string& type,
100 rtc::PacketSocketFactory* factory,
101 rtc::Network* network,
102 const rtc::IPAddress& ip,
103 uint16 min_port,
104 uint16 max_port,
105 const std::string& username_fragment,
106 const std::string& password)
107 : Port(thread, type, factory, network, ip, min_port, max_port,
108 username_fragment, password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000109 }
110 ~TestPort() {}
111
112 // Expose GetStunMessage so that we can test it.
113 using cricket::Port::GetStunMessage;
114
115 // The last StunMessage that was sent on this Port.
116 // TODO: Make these const; requires changes to SendXXXXResponse.
117 ByteBuffer* last_stun_buf() { return last_stun_buf_.get(); }
118 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
119 int last_stun_error_code() {
120 int code = 0;
121 if (last_stun_msg_) {
122 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
123 if (error_attr) {
124 code = error_attr->code();
125 }
126 }
127 return code;
128 }
129
130 virtual void PrepareAddress() {
131 rtc::SocketAddress addr(ip(), min_port());
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700132 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133 ICE_TYPE_PREFERENCE_HOST, 0, true);
134 }
135
136 // Exposed for testing candidate building.
137 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700138 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 type_preference_, 0, false);
140 }
141 void AddCandidateAddress(const rtc::SocketAddress& addr,
142 const rtc::SocketAddress& base_address,
143 const std::string& type,
144 int type_preference,
145 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700146 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147 type_preference, 0, final);
148 }
149
150 virtual Connection* CreateConnection(const Candidate& remote_candidate,
151 CandidateOrigin origin) {
152 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
153 AddConnection(conn);
154 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
155 // in STUN binding requests.
156 conn->set_use_candidate_attr(true);
157 return conn;
158 }
159 virtual int SendTo(
160 const void* data, size_t size, const rtc::SocketAddress& addr,
161 const rtc::PacketOptions& options, bool payload) {
162 if (!payload) {
163 IceMessage* msg = new IceMessage;
164 ByteBuffer* buf = new ByteBuffer(static_cast<const char*>(data), size);
165 ByteBuffer::ReadPosition pos(buf->GetReadPosition());
166 if (!msg->Read(buf)) {
167 delete msg;
168 delete buf;
169 return -1;
170 }
171 buf->SetReadPosition(pos);
172 last_stun_buf_.reset(buf);
173 last_stun_msg_.reset(msg);
174 }
175 return static_cast<int>(size);
176 }
177 virtual int SetOption(rtc::Socket::Option opt, int value) {
178 return 0;
179 }
180 virtual int GetOption(rtc::Socket::Option opt, int* value) {
181 return -1;
182 }
183 virtual int GetError() {
184 return 0;
185 }
186 void Reset() {
187 last_stun_buf_.reset();
188 last_stun_msg_.reset();
189 }
190 void set_type_preference(int type_preference) {
191 type_preference_ = type_preference;
192 }
193
194 private:
195 rtc::scoped_ptr<ByteBuffer> last_stun_buf_;
196 rtc::scoped_ptr<IceMessage> last_stun_msg_;
197 int type_preference_;
198};
199
200class TestChannel : public sigslot::has_slots<> {
201 public:
202 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700203 TestChannel(Port* p1)
204 : ice_mode_(ICEMODE_FULL),
205 port_(p1),
206 complete_count_(0),
207 conn_(NULL),
208 remote_request_(),
209 nominated_(false) {
210 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
211 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
212 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 }
214
215 int complete_count() { return complete_count_; }
216 Connection* conn() { return conn_; }
217 const SocketAddress& remote_address() { return remote_address_; }
218 const std::string remote_fragment() { return remote_frag_; }
219
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700220 void Start() { port_->PrepareAddress(); }
221 void CreateConnection(const Candidate& remote_candidate) {
222 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000223 IceMode remote_ice_mode =
224 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
225 conn_->set_remote_ice_mode(remote_ice_mode);
226 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
227 conn_->SignalStateChange.connect(
228 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700229 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700230 conn_->SignalReadyToSend.connect(this,
231 &TestChannel::OnConnectionReadyToSend);
232 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233 }
234 void OnConnectionStateChange(Connection* conn) {
235 if (conn->write_state() == Connection::STATE_WRITABLE) {
236 conn->set_use_candidate_attr(true);
237 nominated_ = true;
238 }
239 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700240 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700242 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000243 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700244 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700245 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700246 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247 remote_request_.reset();
248 }
249 void Ping() {
250 Ping(0);
251 }
252 void Ping(uint32 now) {
253 conn_->Ping(now);
254 }
255 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700256 if (conn_) {
257 conn_->Destroy();
258 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259 }
260
261 void OnPortComplete(Port* port) {
262 complete_count_++;
263 }
264 void SetIceMode(IceMode ice_mode) {
265 ice_mode_ = ice_mode;
266 }
267
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700268 int SendData(const char* data, size_t len) {
269 rtc::PacketOptions options;
270 return conn_->Send(data, len, options);
271 }
272
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
274 ProtocolType proto,
275 IceMessage* msg, const std::string& rf,
276 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700277 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000278 if (!remote_address_.IsNil()) {
279 ASSERT_EQ(remote_address_, addr);
280 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000281 const cricket::StunUInt32Attribute* priority_attr =
282 msg->GetUInt32(STUN_ATTR_PRIORITY);
283 const cricket::StunByteStringAttribute* mi_attr =
284 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
285 const cricket::StunUInt32Attribute* fingerprint_attr =
286 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700287 EXPECT_TRUE(priority_attr != NULL);
288 EXPECT_TRUE(mi_attr != NULL);
289 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290 remote_address_ = addr;
291 remote_request_.reset(CopyStunMessage(msg));
292 remote_frag_ = rf;
293 }
294
295 void OnDestroyed(Connection* conn) {
296 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700297 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000298 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700299 // When the connection is destroyed, also clear these fields so future
300 // connections are possible.
301 remote_request_.reset();
302 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000303 }
304
305 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700306 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 ASSERT_EQ(destroyed_src, port);
308 }
309
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700310 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700311
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000312 bool nominated() const { return nominated_; }
313
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700314 void set_connection_ready_to_send(bool ready) {
315 connection_ready_to_send_ = ready;
316 }
317 bool connection_ready_to_send() const {
318 return connection_ready_to_send_;
319 }
320
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700322 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
323 void OnConnectionReadyToSend(Connection* conn) {
324 ASSERT_EQ(conn, conn_);
325 connection_ready_to_send_ = true;
326 }
327
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700329 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000330
331 int complete_count_;
332 Connection* conn_;
333 SocketAddress remote_address_;
334 rtc::scoped_ptr<StunMessage> remote_request_;
335 std::string remote_frag_;
336 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700337 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000338};
339
340class PortTest : public testing::Test, public sigslot::has_slots<> {
341 public:
342 PortTest()
343 : main_(rtc::Thread::Current()),
344 pss_(new rtc::PhysicalSocketServer),
345 ss_(new rtc::VirtualSocketServer(pss_.get())),
346 ss_scope_(ss_.get()),
347 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
348 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700349 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
350 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351 nat_socket_factory1_(&nat_factory1_),
352 nat_socket_factory2_(&nat_factory2_),
353 stun_server_(TestStunServer::Create(main_, kStunAddr)),
354 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700355 relay_server_(main_,
356 kRelayUdpIntAddr,
357 kRelayUdpExtAddr,
358 kRelayTcpIntAddr,
359 kRelayTcpExtAddr,
360 kRelaySslTcpIntAddr,
361 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000362 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
363 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364 role_conflict_(false),
365 destroyed_(false) {
366 network_.AddIP(rtc::IPAddress(INADDR_ANY));
367 }
368
369 protected:
370 void TestLocalToLocal() {
371 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700372 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700374 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000375 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
376 }
377 void TestLocalToStun(NATType ntype) {
378 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700379 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
381 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700382 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000383 TestConnectivity("udp", port1, StunName(ntype), port2,
384 ntype == NAT_OPEN_CONE, true,
385 ntype != NAT_SYMMETRIC, true);
386 }
387 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
388 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700389 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000390 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700391 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000392 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
393 rtype == RELAY_GTURN, true, true, true);
394 }
395 void TestStunToLocal(NATType ntype) {
396 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
397 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700398 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000399 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700400 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 TestConnectivity(StunName(ntype), port1, "udp", port2,
402 true, ntype != NAT_SYMMETRIC, true, true);
403 }
404 void TestStunToStun(NATType ntype1, NATType ntype2) {
405 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
406 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700407 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
409 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700410 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000411 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
412 ntype2 == NAT_OPEN_CONE,
413 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
414 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
415 }
416 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
417 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
418 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700419 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700421 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
423 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
424 }
425 void TestTcpToTcp() {
426 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700427 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000428 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700429 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
431 }
432 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
433 Port* port1 = CreateTcpPort(kLocalAddr1);
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_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700436 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000437 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
438 rtype == RELAY_GTURN, false, true, true);
439 }
440 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
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 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700444 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
446 rtype == RELAY_GTURN, false, true, true);
447 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 // helpers for above functions
449 UDPPort* CreateUdpPort(const SocketAddress& addr) {
450 return CreateUdpPort(addr, &socket_factory_);
451 }
452 UDPPort* CreateUdpPort(const SocketAddress& addr,
453 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700454 return UDPPort::Create(main_, socket_factory, &network_,
455 addr.ipaddr(), 0, 0, username_, password_,
456 std::string(), false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457 }
458 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700459 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 }
461 TCPPort* CreateTcpPort(const SocketAddress& addr,
462 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700463 return TCPPort::Create(main_, socket_factory, &network_,
464 addr.ipaddr(), 0, 0, username_, password_,
465 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 }
467 StunPort* CreateStunPort(const SocketAddress& addr,
468 rtc::PacketSocketFactory* factory) {
469 ServerAddresses stun_servers;
470 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700471 return StunPort::Create(main_, factory, &network_,
472 addr.ipaddr(), 0, 0,
473 username_, password_, stun_servers,
474 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475 }
476 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
477 ProtocolType int_proto, ProtocolType ext_proto) {
478 if (rtype == RELAY_TURN) {
479 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
480 } else {
481 return CreateGturnPort(addr, int_proto, ext_proto);
482 }
483 }
484 TurnPort* CreateTurnPort(const SocketAddress& addr,
485 PacketSocketFactory* socket_factory,
486 ProtocolType int_proto, ProtocolType ext_proto) {
487 return CreateTurnPort(addr, socket_factory,
488 int_proto, ext_proto, kTurnUdpIntAddr);
489 }
490 TurnPort* CreateTurnPort(const SocketAddress& addr,
491 PacketSocketFactory* socket_factory,
492 ProtocolType int_proto, ProtocolType ext_proto,
493 const rtc::SocketAddress& server_addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700494 return TurnPort::Create(main_, socket_factory, &network_,
495 addr.ipaddr(), 0, 0,
496 username_, password_, ProtocolAddress(
497 server_addr, PROTO_UDP),
498 kRelayCredentials, 0,
499 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000500 }
501 RelayPort* CreateGturnPort(const SocketAddress& addr,
502 ProtocolType int_proto, ProtocolType ext_proto) {
503 RelayPort* port = CreateGturnPort(addr);
504 SocketAddress addrs[] =
505 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
506 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
507 return port;
508 }
509 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700510 // TODO(pthatcher): Remove GTURN.
511 return RelayPort::Create(main_, &socket_factory_, &network_,
512 addr.ipaddr(), 0, 0,
513 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000514 // TODO: Add an external address for ext_proto, so that the
515 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000516 }
517 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
518 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700519 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000520 }
521 static const char* StunName(NATType type) {
522 switch (type) {
523 case NAT_OPEN_CONE: return "stun(open cone)";
524 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
525 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
526 case NAT_SYMMETRIC: return "stun(symmetric)";
527 default: return "stun(?)";
528 }
529 }
530 static const char* RelayName(RelayType type, ProtocolType proto) {
531 if (type == RELAY_TURN) {
532 switch (proto) {
533 case PROTO_UDP: return "turn(udp)";
534 case PROTO_TCP: return "turn(tcp)";
535 case PROTO_SSLTCP: return "turn(ssltcp)";
536 default: return "turn(?)";
537 }
538 } else {
539 switch (proto) {
540 case PROTO_UDP: return "gturn(udp)";
541 case PROTO_TCP: return "gturn(tcp)";
542 case PROTO_SSLTCP: return "gturn(ssltcp)";
543 default: return "gturn(?)";
544 }
545 }
546 }
547
548 void TestCrossFamilyPorts(int type);
549
Peter Thatcherb8b01432015-07-07 16:45:53 -0700550 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
551
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 // This does all the work and then deletes |port1| and |port2|.
553 void TestConnectivity(const char* name1, Port* port1,
554 const char* name2, Port* port2,
555 bool accept, bool same_addr1,
556 bool same_addr2, bool possible);
557
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700558 // This connects the provided channels which have already started. |ch1|
559 // should have its Connection created (either through CreateConnection() or
560 // TCP reconnecting mechanism before entering this function.
561 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
562 ASSERT_TRUE(ch1->conn());
563 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
564 ch1->Ping();
565 WAIT(!ch2->remote_address().IsNil(), kTimeout);
566
567 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700568 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700569 ch2->Ping();
570 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
571 kTimeout);
572 }
573
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000574 // This connects and disconnects the provided channels in the same sequence as
575 // TestConnectivity with all options set to |true|. It does not delete either
576 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700577 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
578 // Acquire addresses.
579 ch1->Start();
580 ch2->Start();
581
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700582 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700583 ConnectStartedChannels(ch1, ch2);
584
585 // Destroy the connections.
586 ch1->Stop();
587 ch2->Stop();
588 }
589
590 // This disconnects both end's Connection and make sure ch2 ready for new
591 // connection.
592 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700593 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
594 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
595 ASSERT_TRUE(
596 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
597 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700598
599 // Wait for both OnClose are delivered.
600 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
601 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
602
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700603 // Ensure redundant SignalClose events on TcpConnection won't break tcp
604 // reconnection. Chromium will fire SignalClose for all outstanding IPC
605 // packets during reconnection.
606 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
607 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
608
609 // Speed up destroying ch2's connection such that the test is ready to
610 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700611 ch2->conn()->Destroy();
612 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
613 }
614
615 void TestTcpReconnect(bool ping_after_disconnected,
616 bool send_after_disconnected) {
617 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700618 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700619 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700620 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700621
622 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
623 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
624
625 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700626 TestChannel ch1(port1);
627 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700628 EXPECT_EQ(0, ch1.complete_count());
629 EXPECT_EQ(0, ch2.complete_count());
630
631 ch1.Start();
632 ch2.Start();
633 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
634 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
635
636 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700637 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700638 ConnectStartedChannels(&ch1, &ch2);
639
640 // Shorten the timeout period.
641 const int kTcpReconnectTimeout = kTimeout;
642 static_cast<TCPConnection*>(ch1.conn())
643 ->set_reconnection_timeout(kTcpReconnectTimeout);
644 static_cast<TCPConnection*>(ch2.conn())
645 ->set_reconnection_timeout(kTcpReconnectTimeout);
646
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700647 EXPECT_FALSE(ch1.connection_ready_to_send());
648 EXPECT_FALSE(ch2.connection_ready_to_send());
649
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700650 // Once connected, disconnect them.
651 DisconnectTcpTestChannels(&ch1, &ch2);
652
653 if (send_after_disconnected || ping_after_disconnected) {
654 if (send_after_disconnected) {
655 // First SendData after disconnect should fail but will trigger
656 // reconnect.
657 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
658 }
659
660 if (ping_after_disconnected) {
661 // Ping should trigger reconnect.
662 ch1.Ping();
663 }
664
665 // Wait for channel's outgoing TCPConnection connected.
666 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
667
668 // Verify that we could still connect channels.
669 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700670 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
671 kTcpReconnectTimeout);
672 // Channel2 is the passive one so a new connection is created during
673 // reconnect. This new connection should never have issued EWOULDBLOCK
674 // hence the connection_ready_to_send() should be false.
675 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700676 } else {
677 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700678 // Since the reconnection never happens, the connections should have been
679 // destroyed after the timeout.
680 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
681 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700682 }
683
684 // Tear down and ensure that goes smoothly.
685 ch1.Stop();
686 ch2.Stop();
687 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
688 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
689 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691 IceMessage* CreateStunMessage(int type) {
692 IceMessage* msg = new IceMessage();
693 msg->SetType(type);
694 msg->SetTransactionID("TESTTESTTEST");
695 return msg;
696 }
697 IceMessage* CreateStunMessageWithUsername(int type,
698 const std::string& username) {
699 IceMessage* msg = CreateStunMessage(type);
700 msg->AddAttribute(
701 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
702 return msg;
703 }
704 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
705 const std::string& username,
706 const std::string& password) {
707 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
708 addr.ipaddr(), 0, 0, username, password);
709 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
710 return port;
711 }
712 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
713 const std::string& username,
714 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000715 cricket::IceRole role,
716 int tiebreaker) {
717 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000718 port->SetIceRole(role);
719 port->SetIceTiebreaker(tiebreaker);
720 return port;
721 }
722
723 void OnRoleConflict(PortInterface* port) {
724 role_conflict_ = true;
725 }
726 bool role_conflict() const { return role_conflict_; }
727
728 void ConnectToSignalDestroyed(PortInterface* port) {
729 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
730 }
731
732 void OnDestroyed(PortInterface* port) {
733 destroyed_ = true;
734 }
735 bool destroyed() const { return destroyed_; }
736
737 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
738 return &nat_socket_factory1_;
739 }
740
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700741 protected:
742 rtc::VirtualSocketServer* vss() { return ss_.get(); }
743
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000744 private:
745 rtc::Thread* main_;
746 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
747 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
748 rtc::SocketServerScope ss_scope_;
749 rtc::Network network_;
750 rtc::BasicPacketSocketFactory socket_factory_;
751 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
752 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
753 rtc::NATSocketFactory nat_factory1_;
754 rtc::NATSocketFactory nat_factory2_;
755 rtc::BasicPacketSocketFactory nat_socket_factory1_;
756 rtc::BasicPacketSocketFactory nat_socket_factory2_;
757 scoped_ptr<TestStunServer> stun_server_;
758 TestTurnServer turn_server_;
759 TestRelayServer relay_server_;
760 std::string username_;
761 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000762 bool role_conflict_;
763 bool destroyed_;
764};
765
766void PortTest::TestConnectivity(const char* name1, Port* port1,
767 const char* name2, Port* port2,
768 bool accept, bool same_addr1,
769 bool same_addr2, bool possible) {
770 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
771 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
772 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
773
774 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700775 TestChannel ch1(port1);
776 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000777 EXPECT_EQ(0, ch1.complete_count());
778 EXPECT_EQ(0, ch2.complete_count());
779
780 // Acquire addresses.
781 ch1.Start();
782 ch2.Start();
783 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
784 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
785
786 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700787 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000788 ASSERT_TRUE(ch1.conn() != NULL);
789 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
790 ch1.Ping();
791 WAIT(!ch2.remote_address().IsNil(), kTimeout);
792
793 if (accept) {
794 // We are able to send a ping from src to dst. This is the case when
795 // sending to UDP ports and cone NATs.
796 EXPECT_TRUE(ch1.remote_address().IsNil());
797 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
798
799 // Ensure the ping came from the same address used for src.
800 // This is the case unless the source NAT was symmetric.
801 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
802 EXPECT_TRUE(same_addr2);
803
804 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700805 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000806 ASSERT_TRUE(ch2.conn() != NULL);
807 ch2.Ping();
808 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
809 kTimeout);
810 } else {
811 // We can't send a ping from src to dst, so flip it around. This will happen
812 // when the destination NAT is addr/port restricted or symmetric.
813 EXPECT_TRUE(ch1.remote_address().IsNil());
814 EXPECT_TRUE(ch2.remote_address().IsNil());
815
816 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700817 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 ASSERT_TRUE(ch2.conn() != NULL);
819 ch2.Ping();
820 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
821
822 if (same_addr1 && same_addr2) {
823 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700824 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000825 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
826
827 // First connection may not be writable if the first ping did not get
828 // through. So we will have to do another.
829 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
830 ch1.Ping();
831 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
832 kTimeout);
833 }
834 } else if (!same_addr1 && possible) {
835 // The new ping went to the candidate address, but that address was bad.
836 // This will happen when the source NAT is symmetric.
837 EXPECT_TRUE(ch1.remote_address().IsNil());
838 EXPECT_TRUE(ch2.remote_address().IsNil());
839
840 // However, since we have now sent a ping to the source IP, we should be
841 // able to get a ping from it. This gives us the real source address.
842 ch1.Ping();
843 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700844 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 EXPECT_TRUE(ch1.remote_address().IsNil());
846
847 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700848 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 ASSERT_TRUE(ch2.conn() != NULL);
850 ch2.Ping();
851 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
852 kTimeout);
853 } else if (!same_addr2 && possible) {
854 // The new ping came in, but from an unexpected address. This will happen
855 // when the destination NAT is symmetric.
856 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700857 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000858
859 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700860 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000861 ch1.Ping();
862 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
863 kTimeout);
864 } else { // (!possible)
865 // There should be s no way for the pings to reach each other. Check it.
866 EXPECT_TRUE(ch1.remote_address().IsNil());
867 EXPECT_TRUE(ch2.remote_address().IsNil());
868 ch1.Ping();
869 WAIT(!ch2.remote_address().IsNil(), kTimeout);
870 EXPECT_TRUE(ch1.remote_address().IsNil());
871 EXPECT_TRUE(ch2.remote_address().IsNil());
872 }
873 }
874
875 // Everything should be good, unless we know the situation is impossible.
876 ASSERT_TRUE(ch1.conn() != NULL);
877 ASSERT_TRUE(ch2.conn() != NULL);
878 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700879 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000880 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700881 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000882 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
883 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700884 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700886 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
888 }
889
890 // Tear down and ensure that goes smoothly.
891 ch1.Stop();
892 ch2.Stop();
893 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
894 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
895}
896
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897class FakePacketSocketFactory : public rtc::PacketSocketFactory {
898 public:
899 FakePacketSocketFactory()
900 : next_udp_socket_(NULL),
901 next_server_tcp_socket_(NULL),
902 next_client_tcp_socket_(NULL) {
903 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000904 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000906 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
907 uint16 min_port,
908 uint16 max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909 EXPECT_TRUE(next_udp_socket_ != NULL);
910 AsyncPacketSocket* result = next_udp_socket_;
911 next_udp_socket_ = NULL;
912 return result;
913 }
914
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000915 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
916 uint16 min_port,
917 uint16 max_port,
918 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000919 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
920 AsyncPacketSocket* result = next_server_tcp_socket_;
921 next_server_tcp_socket_ = NULL;
922 return result;
923 }
924
925 // TODO: |proxy_info| and |user_agent| should be set
926 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000927 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
928 const SocketAddress& remote_address,
929 const rtc::ProxyInfo& proxy_info,
930 const std::string& user_agent,
931 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000932 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
933 AsyncPacketSocket* result = next_client_tcp_socket_;
934 next_client_tcp_socket_ = NULL;
935 return result;
936 }
937
938 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
939 next_udp_socket_ = next_udp_socket;
940 }
941 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
942 next_server_tcp_socket_ = next_server_tcp_socket;
943 }
944 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
945 next_client_tcp_socket_ = next_client_tcp_socket;
946 }
947 rtc::AsyncResolverInterface* CreateAsyncResolver() {
948 return NULL;
949 }
950
951 private:
952 AsyncPacketSocket* next_udp_socket_;
953 AsyncPacketSocket* next_server_tcp_socket_;
954 AsyncPacketSocket* next_client_tcp_socket_;
955};
956
957class FakeAsyncPacketSocket : public AsyncPacketSocket {
958 public:
959 // Returns current local address. Address may be set to NULL if the
960 // socket is not bound yet (GetState() returns STATE_BINDING).
961 virtual SocketAddress GetLocalAddress() const {
962 return SocketAddress();
963 }
964
965 // Returns remote address. Returns zeroes if this is not a client TCP socket.
966 virtual SocketAddress GetRemoteAddress() const {
967 return SocketAddress();
968 }
969
970 // Send a packet.
971 virtual int Send(const void *pv, size_t cb,
972 const rtc::PacketOptions& options) {
973 return static_cast<int>(cb);
974 }
975 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
976 const rtc::PacketOptions& options) {
977 return static_cast<int>(cb);
978 }
979 virtual int Close() {
980 return 0;
981 }
982
983 virtual State GetState() const { return state_; }
984 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
985 virtual int SetOption(Socket::Option opt, int value) { return 0; }
986 virtual int GetError() const { return 0; }
987 virtual void SetError(int error) { }
988
989 void set_state(State state) { state_ = state; }
990
991 private:
992 State state_;
993};
994
995// Local -> XXXX
996TEST_F(PortTest, TestLocalToLocal) {
997 TestLocalToLocal();
998}
999
1000TEST_F(PortTest, TestLocalToConeNat) {
1001 TestLocalToStun(NAT_OPEN_CONE);
1002}
1003
1004TEST_F(PortTest, TestLocalToARNat) {
1005 TestLocalToStun(NAT_ADDR_RESTRICTED);
1006}
1007
1008TEST_F(PortTest, TestLocalToPRNat) {
1009 TestLocalToStun(NAT_PORT_RESTRICTED);
1010}
1011
1012TEST_F(PortTest, TestLocalToSymNat) {
1013 TestLocalToStun(NAT_SYMMETRIC);
1014}
1015
1016// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1017TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1018 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1019}
1020
1021TEST_F(PortTest, TestLocalToGturn) {
1022 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1023}
1024
1025TEST_F(PortTest, TestLocalToTcpGturn) {
1026 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1027}
1028
1029TEST_F(PortTest, TestLocalToSslTcpGturn) {
1030 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1031}
1032
1033// Cone NAT -> XXXX
1034TEST_F(PortTest, TestConeNatToLocal) {
1035 TestStunToLocal(NAT_OPEN_CONE);
1036}
1037
1038TEST_F(PortTest, TestConeNatToConeNat) {
1039 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1040}
1041
1042TEST_F(PortTest, TestConeNatToARNat) {
1043 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1044}
1045
1046TEST_F(PortTest, TestConeNatToPRNat) {
1047 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1048}
1049
1050TEST_F(PortTest, TestConeNatToSymNat) {
1051 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1052}
1053
1054TEST_F(PortTest, TestConeNatToTurn) {
1055 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1056}
1057
1058TEST_F(PortTest, TestConeNatToGturn) {
1059 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1060}
1061
1062TEST_F(PortTest, TestConeNatToTcpGturn) {
1063 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1064}
1065
1066// Address-restricted NAT -> XXXX
1067TEST_F(PortTest, TestARNatToLocal) {
1068 TestStunToLocal(NAT_ADDR_RESTRICTED);
1069}
1070
1071TEST_F(PortTest, TestARNatToConeNat) {
1072 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1073}
1074
1075TEST_F(PortTest, TestARNatToARNat) {
1076 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1077}
1078
1079TEST_F(PortTest, TestARNatToPRNat) {
1080 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1081}
1082
1083TEST_F(PortTest, TestARNatToSymNat) {
1084 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1085}
1086
1087TEST_F(PortTest, TestARNatToTurn) {
1088 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1089}
1090
1091TEST_F(PortTest, TestARNatToGturn) {
1092 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1093}
1094
1095TEST_F(PortTest, TestARNATNatToTcpGturn) {
1096 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1097}
1098
1099// Port-restricted NAT -> XXXX
1100TEST_F(PortTest, TestPRNatToLocal) {
1101 TestStunToLocal(NAT_PORT_RESTRICTED);
1102}
1103
1104TEST_F(PortTest, TestPRNatToConeNat) {
1105 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1106}
1107
1108TEST_F(PortTest, TestPRNatToARNat) {
1109 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1110}
1111
1112TEST_F(PortTest, TestPRNatToPRNat) {
1113 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1114}
1115
1116TEST_F(PortTest, TestPRNatToSymNat) {
1117 // Will "fail"
1118 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1119}
1120
1121TEST_F(PortTest, TestPRNatToTurn) {
1122 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1123}
1124
1125TEST_F(PortTest, TestPRNatToGturn) {
1126 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1127}
1128
1129TEST_F(PortTest, TestPRNatToTcpGturn) {
1130 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1131}
1132
1133// Symmetric NAT -> XXXX
1134TEST_F(PortTest, TestSymNatToLocal) {
1135 TestStunToLocal(NAT_SYMMETRIC);
1136}
1137
1138TEST_F(PortTest, TestSymNatToConeNat) {
1139 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1140}
1141
1142TEST_F(PortTest, TestSymNatToARNat) {
1143 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1144}
1145
1146TEST_F(PortTest, TestSymNatToPRNat) {
1147 // Will "fail"
1148 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1149}
1150
1151TEST_F(PortTest, TestSymNatToSymNat) {
1152 // Will "fail"
1153 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1154}
1155
1156TEST_F(PortTest, TestSymNatToTurn) {
1157 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1158}
1159
1160TEST_F(PortTest, TestSymNatToGturn) {
1161 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1162}
1163
1164TEST_F(PortTest, TestSymNatToTcpGturn) {
1165 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1166}
1167
1168// Outbound TCP -> XXXX
1169TEST_F(PortTest, TestTcpToTcp) {
1170 TestTcpToTcp();
1171}
1172
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001173TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1174 TestTcpReconnect(false /* ping */, true /* send */);
1175}
1176
1177TEST_F(PortTest, TestTcpReconnectOnPing) {
1178 TestTcpReconnect(true /* ping */, false /* send */);
1179}
1180
1181TEST_F(PortTest, TestTcpReconnectTimeout) {
1182 TestTcpReconnect(false /* ping */, false /* send */);
1183}
1184
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001185// Test when TcpConnection never connects, the OnClose() will be called to
1186// destroy the connection.
1187TEST_F(PortTest, TestTcpNeverConnect) {
1188 Port* port1 = CreateTcpPort(kLocalAddr1);
1189 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1190 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1191
1192 // Set up a channel and ensure the port will be deleted.
1193 TestChannel ch1(port1);
1194 EXPECT_EQ(0, ch1.complete_count());
1195
1196 ch1.Start();
1197 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1198
1199 rtc::scoped_ptr<rtc::AsyncSocket> server(
1200 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1201 // Bind but not listen.
1202 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1203
1204 Candidate c = GetCandidate(port1);
1205 c.set_address(server->GetLocalAddress());
1206
1207 ch1.CreateConnection(c);
1208 EXPECT_TRUE(ch1.conn());
1209 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1210}
1211
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001212/* TODO: Enable these once testrelayserver can accept external TCP.
1213TEST_F(PortTest, TestTcpToTcpRelay) {
1214 TestTcpToRelay(PROTO_TCP);
1215}
1216
1217TEST_F(PortTest, TestTcpToSslTcpRelay) {
1218 TestTcpToRelay(PROTO_SSLTCP);
1219}
1220*/
1221
1222// Outbound SSLTCP -> XXXX
1223/* TODO: Enable these once testrelayserver can accept external SSL.
1224TEST_F(PortTest, TestSslTcpToTcpRelay) {
1225 TestSslTcpToRelay(PROTO_TCP);
1226}
1227
1228TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1229 TestSslTcpToRelay(PROTO_SSLTCP);
1230}
1231*/
1232
1233// This test case verifies standard ICE features in STUN messages. Currently it
1234// verifies Message Integrity attribute in STUN messages and username in STUN
1235// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001236TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1238 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1239 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1241 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1242 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243 // Same parameters as TestLocalToLocal above.
1244 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1245}
1246
1247// This test is trying to validate a successful and failure scenario in a
1248// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1249// should remain equal to the request generated by the port and role of port
1250// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001251TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001252 rtc::scoped_ptr<TestPort> lport(
1253 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001254 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1255 lport->SetIceTiebreaker(kTiebreaker1);
1256 lport->PrepareAddress();
1257 ASSERT_FALSE(lport->Candidates().empty());
1258 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1259 Port::ORIGIN_MESSAGE);
1260 conn->Ping(0);
1261
1262 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1263 IceMessage* msg = lport->last_stun_msg();
1264 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1265 conn->OnReadPacket(lport->last_stun_buf()->Data(),
1266 lport->last_stun_buf()->Length(),
1267 rtc::PacketTime());
1268 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1269 msg = lport->last_stun_msg();
1270 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1271
1272 // If the tiebreaker value is different from port, we expect a error
1273 // response.
1274 lport->Reset();
1275 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001276 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1278 Port::ORIGIN_MESSAGE);
1279 conn1->Ping(0);
1280
1281 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1282 msg = lport->last_stun_msg();
1283 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1284 rtc::scoped_ptr<IceMessage> modified_req(
1285 CreateStunMessage(STUN_BINDING_REQUEST));
1286 const StunByteStringAttribute* username_attr = msg->GetByteString(
1287 STUN_ATTR_USERNAME);
1288 modified_req->AddAttribute(new StunByteStringAttribute(
1289 STUN_ATTR_USERNAME, username_attr->GetString()));
1290 // To make sure we receive error response, adding tiebreaker less than
1291 // what's present in request.
1292 modified_req->AddAttribute(new StunUInt64Attribute(
1293 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1294 modified_req->AddMessageIntegrity("lpass");
1295 modified_req->AddFingerprint();
1296
1297 lport->Reset();
1298 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1299 WriteStunMessage(modified_req.get(), buf.get());
1300 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1301 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1302 msg = lport->last_stun_msg();
1303 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1304}
1305
1306// This test verifies role conflict signal is received when there is
1307// conflict in the role. In this case both ports are in controlling and
1308// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1309// value of tiebreaker, when it receives ping request from |rport| it will
1310// send role conflict signal.
1311TEST_F(PortTest, TestIceRoleConflict) {
1312 rtc::scoped_ptr<TestPort> lport(
1313 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1315 lport->SetIceTiebreaker(kTiebreaker1);
1316 rtc::scoped_ptr<TestPort> rport(
1317 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1319 rport->SetIceTiebreaker(kTiebreaker2);
1320
1321 lport->PrepareAddress();
1322 rport->PrepareAddress();
1323 ASSERT_FALSE(lport->Candidates().empty());
1324 ASSERT_FALSE(rport->Candidates().empty());
1325 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1326 Port::ORIGIN_MESSAGE);
1327 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1328 Port::ORIGIN_MESSAGE);
1329 rconn->Ping(0);
1330
1331 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1332 IceMessage* msg = rport->last_stun_msg();
1333 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1334 // Send rport binding request to lport.
1335 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1336 rport->last_stun_buf()->Length(),
1337 rtc::PacketTime());
1338
1339 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1340 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1341 EXPECT_TRUE(role_conflict());
1342}
1343
1344TEST_F(PortTest, TestTcpNoDelay) {
1345 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001346 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001347 int option_value = -1;
1348 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1349 &option_value);
1350 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1351 ASSERT_EQ(1, option_value);
1352 delete port1;
1353}
1354
1355TEST_F(PortTest, TestDelayedBindingUdp) {
1356 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1357 FakePacketSocketFactory socket_factory;
1358
1359 socket_factory.set_next_udp_socket(socket);
1360 scoped_ptr<UDPPort> port(
1361 CreateUdpPort(kLocalAddr1, &socket_factory));
1362
1363 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1364 port->PrepareAddress();
1365
1366 EXPECT_EQ(0U, port->Candidates().size());
1367 socket->SignalAddressReady(socket, kLocalAddr2);
1368
1369 EXPECT_EQ(1U, port->Candidates().size());
1370}
1371
1372TEST_F(PortTest, TestDelayedBindingTcp) {
1373 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1374 FakePacketSocketFactory socket_factory;
1375
1376 socket_factory.set_next_server_tcp_socket(socket);
1377 scoped_ptr<TCPPort> port(
1378 CreateTcpPort(kLocalAddr1, &socket_factory));
1379
1380 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1381 port->PrepareAddress();
1382
1383 EXPECT_EQ(0U, port->Candidates().size());
1384 socket->SignalAddressReady(socket, kLocalAddr2);
1385
1386 EXPECT_EQ(1U, port->Candidates().size());
1387}
1388
1389void PortTest::TestCrossFamilyPorts(int type) {
1390 FakePacketSocketFactory factory;
1391 scoped_ptr<Port> ports[4];
1392 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1393 SocketAddress("192.168.1.4", 0),
1394 SocketAddress("2001:db8::1", 0),
1395 SocketAddress("2001:db8::2", 0)};
1396 for (int i = 0; i < 4; i++) {
1397 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1398 if (type == SOCK_DGRAM) {
1399 factory.set_next_udp_socket(socket);
1400 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1401 } else if (type == SOCK_STREAM) {
1402 factory.set_next_server_tcp_socket(socket);
1403 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1404 }
1405 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1406 socket->SignalAddressReady(socket, addresses[i]);
1407 ports[i]->PrepareAddress();
1408 }
1409
1410 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1411 if (type == SOCK_STREAM) {
1412 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1413 factory.set_next_client_tcp_socket(clientsocket);
1414 }
1415 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1416 Port::ORIGIN_MESSAGE);
1417 EXPECT_TRUE(NULL == c);
1418 EXPECT_EQ(0U, ports[0]->connections().size());
1419 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1420 Port::ORIGIN_MESSAGE);
1421 EXPECT_FALSE(NULL == c);
1422 EXPECT_EQ(1U, ports[0]->connections().size());
1423
1424 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1425 if (type == SOCK_STREAM) {
1426 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1427 factory.set_next_client_tcp_socket(clientsocket);
1428 }
1429 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1430 Port::ORIGIN_MESSAGE);
1431 EXPECT_TRUE(NULL == c);
1432 EXPECT_EQ(0U, ports[2]->connections().size());
1433 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1434 Port::ORIGIN_MESSAGE);
1435 EXPECT_FALSE(NULL == c);
1436 EXPECT_EQ(1U, ports[2]->connections().size());
1437}
1438
1439TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1440 TestCrossFamilyPorts(SOCK_STREAM);
1441}
1442
1443TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1444 TestCrossFamilyPorts(SOCK_DGRAM);
1445}
1446
Peter Thatcherb8b01432015-07-07 16:45:53 -07001447void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1448 Connection* c = p1->CreateConnection(GetCandidate(p2),
1449 Port::ORIGIN_MESSAGE);
1450 if (can_connect) {
1451 EXPECT_FALSE(NULL == c);
1452 EXPECT_EQ(1U, p1->connections().size());
1453 } else {
1454 EXPECT_TRUE(NULL == c);
1455 EXPECT_EQ(0U, p1->connections().size());
1456 }
1457}
1458
1459TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1460 FakePacketSocketFactory factory;
1461 scoped_ptr<Port> ports[4];
1462 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1463 SocketAddress("fe80::1", 0),
1464 SocketAddress("fe80::2", 0),
1465 SocketAddress("::1", 0)};
1466 for (int i = 0; i < 4; i++) {
1467 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1468 factory.set_next_udp_socket(socket);
1469 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1470 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1471 socket->SignalAddressReady(socket, addresses[i]);
1472 ports[i]->PrepareAddress();
1473 }
1474
1475 Port* standard = ports[0].get();
1476 Port* link_local1 = ports[1].get();
1477 Port* link_local2 = ports[2].get();
1478 Port* localhost = ports[3].get();
1479
1480 ExpectPortsCanConnect(false, link_local1, standard);
1481 ExpectPortsCanConnect(false, standard, link_local1);
1482 ExpectPortsCanConnect(false, link_local1, localhost);
1483 ExpectPortsCanConnect(false, localhost, link_local1);
1484
1485 ExpectPortsCanConnect(true, link_local1, link_local2);
1486 ExpectPortsCanConnect(true, localhost, standard);
1487 ExpectPortsCanConnect(true, standard, localhost);
1488}
1489
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001490// This test verifies DSCP value set through SetOption interface can be
1491// get through DefaultDscpValue.
1492TEST_F(PortTest, TestDefaultDscpValue) {
1493 int dscp;
1494 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1495 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1496 rtc::DSCP_CS6));
1497 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1498 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1499 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1500 rtc::DSCP_AF31));
1501 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1502 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1503 rtc::scoped_ptr<StunPort> stunport(
1504 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1505 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1506 rtc::DSCP_AF41));
1507 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1508 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1509 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1510 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1511 // Socket is created in PrepareAddress.
1512 turnport1->PrepareAddress();
1513 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1514 rtc::DSCP_CS7));
1515 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1516 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1517 // This will verify correct value returned without the socket.
1518 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1519 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1520 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1521 rtc::DSCP_CS6));
1522 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1523 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1524}
1525
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001526// Test sending STUN messages.
1527TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001528 rtc::scoped_ptr<TestPort> lport(
1529 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1530 rtc::scoped_ptr<TestPort> rport(
1531 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001532 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1533 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001534 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1535 rport->SetIceTiebreaker(kTiebreaker2);
1536
1537 // Send a fake ping from lport to rport.
1538 lport->PrepareAddress();
1539 rport->PrepareAddress();
1540 ASSERT_FALSE(rport->Candidates().empty());
1541 Connection* lconn = lport->CreateConnection(
1542 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1543 Connection* rconn = rport->CreateConnection(
1544 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1545 lconn->Ping(0);
1546
1547 // Check that it's a proper BINDING-REQUEST.
1548 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1549 IceMessage* msg = lport->last_stun_msg();
1550 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1551 EXPECT_FALSE(msg->IsLegacy());
1552 const StunByteStringAttribute* username_attr =
1553 msg->GetByteString(STUN_ATTR_USERNAME);
1554 ASSERT_TRUE(username_attr != NULL);
1555 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1556 ASSERT_TRUE(priority_attr != NULL);
1557 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1558 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1559 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1560 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1561 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length(),
1562 "rpass"));
1563 const StunUInt64Attribute* ice_controlling_attr =
1564 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1565 ASSERT_TRUE(ice_controlling_attr != NULL);
1566 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1567 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1568 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1569 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1570 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1571 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1572
1573 // Request should not include ping count.
1574 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1575
1576 // Save a copy of the BINDING-REQUEST for use below.
1577 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1578
1579 // Respond with a BINDING-RESPONSE.
1580 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1581 msg = rport->last_stun_msg();
1582 ASSERT_TRUE(msg != NULL);
1583 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1584
1585
1586 EXPECT_FALSE(msg->IsLegacy());
1587 const StunAddressAttribute* addr_attr = msg->GetAddress(
1588 STUN_ATTR_XOR_MAPPED_ADDRESS);
1589 ASSERT_TRUE(addr_attr != NULL);
1590 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1591 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1592 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1593 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1594 "rpass"));
1595 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1596 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1597 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1598 // No USERNAME or PRIORITY in ICE responses.
1599 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1600 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1601 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1602 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1603 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1604 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1605
1606 // Response should not include ping count.
1607 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1608
1609 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1610 // but we can do it here.
1611 rport->SendBindingErrorResponse(request.get(),
1612 lport->Candidates()[0].address(),
1613 STUN_ERROR_SERVER_ERROR,
1614 STUN_ERROR_REASON_SERVER_ERROR);
1615 msg = rport->last_stun_msg();
1616 ASSERT_TRUE(msg != NULL);
1617 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1618 EXPECT_FALSE(msg->IsLegacy());
1619 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1620 ASSERT_TRUE(error_attr != NULL);
1621 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1622 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1623 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1624 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
1625 rport->last_stun_buf()->Data(), rport->last_stun_buf()->Length(),
1626 "rpass"));
1627 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1628 EXPECT_TRUE(StunMessage::ValidateFingerprint(
1629 lport->last_stun_buf()->Data(), lport->last_stun_buf()->Length()));
1630 // No USERNAME with ICE.
1631 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1632 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1633
1634 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1635 // and (incremented) RETRANSMIT_COUNT attributes.
1636 rport->Reset();
1637 rport->set_send_retransmit_count_attribute(true);
1638 rconn->Ping(0);
1639 rconn->Ping(0);
1640 rconn->Ping(0);
1641 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1642 msg = rport->last_stun_msg();
1643 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1644 const StunUInt64Attribute* ice_controlled_attr =
1645 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1646 ASSERT_TRUE(ice_controlled_attr != NULL);
1647 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1648 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1649
1650 // Request should include ping count.
1651 const StunUInt32Attribute* retransmit_attr =
1652 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1653 ASSERT_TRUE(retransmit_attr != NULL);
1654 EXPECT_EQ(2U, retransmit_attr->value());
1655
1656 // Respond with a BINDING-RESPONSE.
1657 request.reset(CopyStunMessage(msg));
1658 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1659 msg = lport->last_stun_msg();
1660
1661 // Response should include same ping count.
1662 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1663 ASSERT_TRUE(retransmit_attr != NULL);
1664 EXPECT_EQ(2U, retransmit_attr->value());
1665}
1666
1667TEST_F(PortTest, TestUseCandidateAttribute) {
1668 rtc::scoped_ptr<TestPort> lport(
1669 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1670 rtc::scoped_ptr<TestPort> rport(
1671 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001672 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1673 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001674 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1675 rport->SetIceTiebreaker(kTiebreaker2);
1676
1677 // Send a fake ping from lport to rport.
1678 lport->PrepareAddress();
1679 rport->PrepareAddress();
1680 ASSERT_FALSE(rport->Candidates().empty());
1681 Connection* lconn = lport->CreateConnection(
1682 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1683 lconn->Ping(0);
1684 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1685 IceMessage* msg = lport->last_stun_msg();
1686 const StunUInt64Attribute* ice_controlling_attr =
1687 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1688 ASSERT_TRUE(ice_controlling_attr != NULL);
1689 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1690 STUN_ATTR_USE_CANDIDATE);
1691 ASSERT_TRUE(use_candidate_attr != NULL);
1692}
1693
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001694// Test handling STUN messages.
1695TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001696 // Our port will act as the "remote" port.
1697 rtc::scoped_ptr<TestPort> port(
1698 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001699
1700 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1701 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1702 rtc::SocketAddress addr(kLocalAddr1);
1703 std::string username;
1704
1705 // BINDING-REQUEST from local to remote with valid ICE username,
1706 // MESSAGE-INTEGRITY, and FINGERPRINT.
1707 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1708 "rfrag:lfrag"));
1709 in_msg->AddMessageIntegrity("rpass");
1710 in_msg->AddFingerprint();
1711 WriteStunMessage(in_msg.get(), buf.get());
1712 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1713 out_msg.accept(), &username));
1714 EXPECT_TRUE(out_msg.get() != NULL);
1715 EXPECT_EQ("lfrag", username);
1716
1717 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1718 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1719 in_msg->AddAttribute(
1720 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1721 in_msg->AddMessageIntegrity("rpass");
1722 in_msg->AddFingerprint();
1723 WriteStunMessage(in_msg.get(), buf.get());
1724 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1725 out_msg.accept(), &username));
1726 EXPECT_TRUE(out_msg.get() != NULL);
1727 EXPECT_EQ("", username);
1728
1729 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1730 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1731 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1732 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1733 in_msg->AddFingerprint();
1734 WriteStunMessage(in_msg.get(), buf.get());
1735 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1736 out_msg.accept(), &username));
1737 EXPECT_TRUE(out_msg.get() != NULL);
1738 EXPECT_EQ("", username);
1739 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1740 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1741 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1742 out_msg->GetErrorCode()->reason());
1743}
1744
guoweisd12140a2015-09-10 13:32:11 -07001745// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001746TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001747 rtc::scoped_ptr<TestPort> port(
1748 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001749
1750 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1751 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1752 rtc::SocketAddress addr(kLocalAddr1);
1753 std::string username;
1754
1755 // BINDING-REQUEST with no username.
1756 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1757 in_msg->AddMessageIntegrity("rpass");
1758 in_msg->AddFingerprint();
1759 WriteStunMessage(in_msg.get(), buf.get());
1760 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1761 out_msg.accept(), &username));
1762 EXPECT_TRUE(out_msg.get() == NULL);
1763 EXPECT_EQ("", username);
1764 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1765
1766 // BINDING-REQUEST with empty username.
1767 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1768 in_msg->AddMessageIntegrity("rpass");
1769 in_msg->AddFingerprint();
1770 WriteStunMessage(in_msg.get(), buf.get());
1771 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1772 out_msg.accept(), &username));
1773 EXPECT_TRUE(out_msg.get() == NULL);
1774 EXPECT_EQ("", username);
1775 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1776
1777 // BINDING-REQUEST with too-short username.
1778 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1779 in_msg->AddMessageIntegrity("rpass");
1780 in_msg->AddFingerprint();
1781 WriteStunMessage(in_msg.get(), buf.get());
1782 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1783 out_msg.accept(), &username));
1784 EXPECT_TRUE(out_msg.get() == NULL);
1785 EXPECT_EQ("", username);
1786 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1787
1788 // BINDING-REQUEST with reversed username.
1789 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1790 "lfrag:rfrag"));
1791 in_msg->AddMessageIntegrity("rpass");
1792 in_msg->AddFingerprint();
1793 WriteStunMessage(in_msg.get(), buf.get());
1794 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1795 out_msg.accept(), &username));
1796 EXPECT_TRUE(out_msg.get() == NULL);
1797 EXPECT_EQ("", username);
1798 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1799
1800 // BINDING-REQUEST with garbage username.
1801 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1802 "abcd:efgh"));
1803 in_msg->AddMessageIntegrity("rpass");
1804 in_msg->AddFingerprint();
1805 WriteStunMessage(in_msg.get(), buf.get());
1806 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1807 out_msg.accept(), &username));
1808 EXPECT_TRUE(out_msg.get() == NULL);
1809 EXPECT_EQ("", username);
1810 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1811}
1812
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001813// Test handling STUN messages with missing or malformed M-I.
1814TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001815 // Our port will act as the "remote" port.
1816 rtc::scoped_ptr<TestPort> port(
1817 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001818
1819 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1820 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1821 rtc::SocketAddress addr(kLocalAddr1);
1822 std::string username;
1823
1824 // BINDING-REQUEST from local to remote with valid ICE username and
1825 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1826 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1827 "rfrag:lfrag"));
1828 in_msg->AddFingerprint();
1829 WriteStunMessage(in_msg.get(), buf.get());
1830 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1831 out_msg.accept(), &username));
1832 EXPECT_TRUE(out_msg.get() == NULL);
1833 EXPECT_EQ("", username);
1834 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1835
1836 // BINDING-REQUEST from local to remote with valid ICE username and
1837 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1838 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1839 "rfrag:lfrag"));
1840 in_msg->AddMessageIntegrity("invalid");
1841 in_msg->AddFingerprint();
1842 WriteStunMessage(in_msg.get(), buf.get());
1843 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1844 out_msg.accept(), &username));
1845 EXPECT_TRUE(out_msg.get() == NULL);
1846 EXPECT_EQ("", username);
1847 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1848
1849 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1850 // by the Connection, not the Port, since they require the remote username.
1851 // Change this test to pass in data via Connection::OnReadPacket instead.
1852}
1853
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001854// Test handling STUN messages with missing or malformed FINGERPRINT.
1855TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001856 // Our port will act as the "remote" port.
1857 rtc::scoped_ptr<TestPort> port(
1858 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001859
1860 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1861 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1862 rtc::SocketAddress addr(kLocalAddr1);
1863 std::string username;
1864
1865 // BINDING-REQUEST from local to remote with valid ICE username and
1866 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1867 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1868 "rfrag:lfrag"));
1869 in_msg->AddMessageIntegrity("rpass");
1870 WriteStunMessage(in_msg.get(), buf.get());
1871 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1872 out_msg.accept(), &username));
1873 EXPECT_EQ(0, port->last_stun_error_code());
1874
1875 // Now, add a fingerprint, but munge the message so it's not valid.
1876 in_msg->AddFingerprint();
1877 in_msg->SetTransactionID("TESTTESTBADD");
1878 WriteStunMessage(in_msg.get(), buf.get());
1879 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1880 out_msg.accept(), &username));
1881 EXPECT_EQ(0, port->last_stun_error_code());
1882
1883 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1884 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1885 in_msg->AddAttribute(
1886 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1887 in_msg->AddMessageIntegrity("rpass");
1888 WriteStunMessage(in_msg.get(), buf.get());
1889 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1890 out_msg.accept(), &username));
1891 EXPECT_EQ(0, port->last_stun_error_code());
1892
1893 // Now, add a fingerprint, but munge the message so it's not valid.
1894 in_msg->AddFingerprint();
1895 in_msg->SetTransactionID("TESTTESTBADD");
1896 WriteStunMessage(in_msg.get(), buf.get());
1897 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1898 out_msg.accept(), &username));
1899 EXPECT_EQ(0, port->last_stun_error_code());
1900
1901 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
1902 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1903 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1904 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1905 in_msg->AddMessageIntegrity("rpass");
1906 WriteStunMessage(in_msg.get(), buf.get());
1907 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1908 out_msg.accept(), &username));
1909 EXPECT_EQ(0, port->last_stun_error_code());
1910
1911 // Now, add a fingerprint, but munge the message so it's not valid.
1912 in_msg->AddFingerprint();
1913 in_msg->SetTransactionID("TESTTESTBADD");
1914 WriteStunMessage(in_msg.get(), buf.get());
1915 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr,
1916 out_msg.accept(), &username));
1917 EXPECT_EQ(0, port->last_stun_error_code());
1918}
1919
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001920// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001921// indications are allowed only to the connection which is in read mode.
1922TEST_F(PortTest, TestHandleStunBindingIndication) {
1923 rtc::scoped_ptr<TestPort> lport(
1924 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001925 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1926 lport->SetIceTiebreaker(kTiebreaker1);
1927
1928 // Verifying encoding and decoding STUN indication message.
1929 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
1930 rtc::scoped_ptr<ByteBuffer> buf(new ByteBuffer());
1931 rtc::SocketAddress addr(kLocalAddr1);
1932 std::string username;
1933
1934 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
1935 in_msg->AddFingerprint();
1936 WriteStunMessage(in_msg.get(), buf.get());
1937 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr,
1938 out_msg.accept(), &username));
1939 EXPECT_TRUE(out_msg.get() != NULL);
1940 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
1941 EXPECT_EQ("", username);
1942
1943 // Verify connection can handle STUN indication and updates
1944 // last_ping_received.
1945 rtc::scoped_ptr<TestPort> rport(
1946 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001947 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1948 rport->SetIceTiebreaker(kTiebreaker2);
1949
1950 lport->PrepareAddress();
1951 rport->PrepareAddress();
1952 ASSERT_FALSE(lport->Candidates().empty());
1953 ASSERT_FALSE(rport->Candidates().empty());
1954
1955 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1956 Port::ORIGIN_MESSAGE);
1957 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1958 Port::ORIGIN_MESSAGE);
1959 rconn->Ping(0);
1960
1961 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1962 IceMessage* msg = rport->last_stun_msg();
1963 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1964 // Send rport binding request to lport.
1965 lconn->OnReadPacket(rport->last_stun_buf()->Data(),
1966 rport->last_stun_buf()->Length(),
1967 rtc::PacketTime());
1968 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1969 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1970 uint32 last_ping_received1 = lconn->last_ping_received();
1971
1972 // Adding a delay of 100ms.
1973 rtc::Thread::Current()->ProcessMessages(100);
1974 // Pinging lconn using stun indication message.
1975 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1976 uint32 last_ping_received2 = lconn->last_ping_received();
1977 EXPECT_GT(last_ping_received2, last_ping_received1);
1978}
1979
1980TEST_F(PortTest, TestComputeCandidatePriority) {
1981 rtc::scoped_ptr<TestPort> port(
1982 CreateTestPort(kLocalAddr1, "name", "pass"));
1983 port->set_type_preference(90);
1984 port->set_component(177);
1985 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
1986 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
1987 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
1988 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
1989 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
1990 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
1991 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
1992 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
1993 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
1994 // These should all be:
1995 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
1996 uint32 expected_priority_v4 = 1509957199U;
1997 uint32 expected_priority_v6 = 1509959759U;
1998 uint32 expected_priority_ula = 1509962319U;
1999 uint32 expected_priority_v4mapped = expected_priority_v4;
2000 uint32 expected_priority_v4compat = 1509949775U;
2001 uint32 expected_priority_6to4 = 1509954639U;
2002 uint32 expected_priority_teredo = 1509952079U;
2003 uint32 expected_priority_sitelocal = 1509949775U;
2004 uint32 expected_priority_6bone = 1509949775U;
2005 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2006 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2007 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2008 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2009 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2010 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2011 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2012 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2013 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2014}
2015
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002016// In the case of shared socket, one port may be shared by local and stun.
2017// Test that candidates with different types will have different foundation.
2018TEST_F(PortTest, TestFoundation) {
2019 rtc::scoped_ptr<TestPort> testport(
2020 CreateTestPort(kLocalAddr1, "name", "pass"));
2021 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2022 LOCAL_PORT_TYPE,
2023 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2024 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2025 STUN_PORT_TYPE,
2026 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2027 EXPECT_NE(testport->Candidates()[0].foundation(),
2028 testport->Candidates()[1].foundation());
2029}
2030
2031// This test verifies the foundation of different types of ICE candidates.
2032TEST_F(PortTest, TestCandidateFoundation) {
2033 rtc::scoped_ptr<rtc::NATServer> nat_server(
2034 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2035 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2036 udpport1->PrepareAddress();
2037 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2038 udpport2->PrepareAddress();
2039 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2040 udpport2->Candidates()[0].foundation());
2041 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2042 tcpport1->PrepareAddress();
2043 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2044 tcpport2->PrepareAddress();
2045 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2046 tcpport2->Candidates()[0].foundation());
2047 rtc::scoped_ptr<Port> stunport(
2048 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2049 stunport->PrepareAddress();
2050 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2051 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2052 stunport->Candidates()[0].foundation());
2053 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2054 stunport->Candidates()[0].foundation());
2055 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2056 stunport->Candidates()[0].foundation());
2057 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2058 stunport->Candidates()[0].foundation());
2059 // Verify GTURN candidate foundation.
2060 rtc::scoped_ptr<RelayPort> relayport(
2061 CreateGturnPort(kLocalAddr1));
2062 relayport->AddServerAddress(
2063 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2064 relayport->PrepareAddress();
2065 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2066 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2067 relayport->Candidates()[0].foundation());
2068 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2069 relayport->Candidates()[0].foundation());
2070 // Verifying TURN candidate foundation.
2071 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2072 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2073 turnport1->PrepareAddress();
2074 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2075 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2076 turnport1->Candidates()[0].foundation());
2077 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2078 turnport1->Candidates()[0].foundation());
2079 EXPECT_NE(stunport->Candidates()[0].foundation(),
2080 turnport1->Candidates()[0].foundation());
2081 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2082 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2083 turnport2->PrepareAddress();
2084 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2085 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2086 turnport2->Candidates()[0].foundation());
2087
2088 // Running a second turn server, to get different base IP address.
2089 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2090 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2091 TestTurnServer turn_server2(
2092 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2093 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2094 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2095 kTurnUdpIntAddr2));
2096 turnport3->PrepareAddress();
2097 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2098 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2099 turnport2->Candidates()[0].foundation());
2100}
2101
2102// This test verifies the related addresses of different types of
2103// ICE candiates.
2104TEST_F(PortTest, TestCandidateRelatedAddress) {
2105 rtc::scoped_ptr<rtc::NATServer> nat_server(
2106 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2107 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2108 udpport->PrepareAddress();
2109 // For UDPPort, related address will be empty.
2110 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2111 // Testing related address for stun candidates.
2112 // For stun candidate related address must be equal to the base
2113 // socket address.
2114 rtc::scoped_ptr<StunPort> stunport(
2115 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2116 stunport->PrepareAddress();
2117 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2118 // Check STUN candidate address.
2119 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2120 kNatAddr1.ipaddr());
2121 // Check STUN candidate related address.
2122 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2123 stunport->GetLocalAddress());
2124 // Verifying the related address for the GTURN candidates.
2125 // NOTE: In case of GTURN related address will be equal to the mapped
2126 // address, but address(mapped) will not be XOR.
2127 rtc::scoped_ptr<RelayPort> relayport(
2128 CreateGturnPort(kLocalAddr1));
2129 relayport->AddServerAddress(
2130 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2131 relayport->PrepareAddress();
2132 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2133 // For Gturn related address is set to "0.0.0.0:0"
2134 EXPECT_EQ(rtc::SocketAddress(),
2135 relayport->Candidates()[0].related_address());
2136 // Verifying the related address for TURN candidate.
2137 // For TURN related address must be equal to the mapped address.
2138 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2139 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2140 turnport->PrepareAddress();
2141 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2142 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2143 turnport->Candidates()[0].address().ipaddr());
2144 EXPECT_EQ(kNatAddr1.ipaddr(),
2145 turnport->Candidates()[0].related_address().ipaddr());
2146}
2147
2148// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002149TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002150 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002151 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002152 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002153 cand2.set_priority(1);
2154 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002155}
2156
2157// Test the Connection priority is calculated correctly.
2158TEST_F(PortTest, TestConnectionPriority) {
2159 rtc::scoped_ptr<TestPort> lport(
2160 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2161 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2162 rtc::scoped_ptr<TestPort> rport(
2163 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2164 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2165 lport->set_component(123);
2166 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2167 rport->set_component(23);
2168 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2169
2170 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2171 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2172
2173 // RFC 5245
2174 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2175 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2176 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2177 Connection* lconn = lport->CreateConnection(
2178 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2179#if defined(WEBRTC_WIN)
2180 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2181#else
2182 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2183#endif
2184
2185 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2186 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2187 Connection* rconn = rport->CreateConnection(
2188 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2189#if defined(WEBRTC_WIN)
2190 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2191#else
2192 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2193#endif
2194}
2195
2196TEST_F(PortTest, TestWritableState) {
2197 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002198 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002199 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002200 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002201
2202 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002203 TestChannel ch1(port1);
2204 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002205
2206 // Acquire addresses.
2207 ch1.Start();
2208 ch2.Start();
2209 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2210 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2211
2212 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002213 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002214 ASSERT_TRUE(ch1.conn() != NULL);
2215 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2216 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2217 ch1.Ping();
2218 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2219
2220 // Data should be unsendable until the connection is accepted.
2221 char data[] = "abcd";
2222 int data_size = ARRAY_SIZE(data);
2223 rtc::PacketOptions options;
2224 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2225
2226 // Accept the connection to return the binding response, transition to
2227 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002228 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002229 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2230 kTimeout);
2231 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2232
2233 // Ask the connection to update state as if enough time has passed to lose
2234 // full writability and 5 pings went unresponded to. We'll accomplish the
2235 // latter by sending pings but not pumping messages.
2236 for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2237 ch1.Ping(i);
2238 }
2239 uint32 unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500u;
2240 ch1.conn()->UpdateState(unreliable_timeout_delay);
2241 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2242
2243 // Data should be able to be sent in this state.
2244 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2245
2246 // And now allow the other side to process the pings and send binding
2247 // responses.
2248 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2249 kTimeout);
2250
2251 // Wait long enough for a full timeout (past however long we've already
2252 // waited).
2253 for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2254 ch1.Ping(unreliable_timeout_delay + i);
2255 }
2256 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2257 500u);
2258 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2259
2260 // Now that the connection has completely timed out, data send should fail.
2261 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2262
2263 ch1.Stop();
2264 ch2.Stop();
2265}
2266
2267TEST_F(PortTest, TestTimeoutForNeverWritable) {
2268 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002269 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002270 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002271 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002272
2273 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002274 TestChannel ch1(port1);
2275 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002276
2277 // Acquire addresses.
2278 ch1.Start();
2279 ch2.Start();
2280
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002281 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002282 ASSERT_TRUE(ch1.conn() != NULL);
2283 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2284
2285 // Attempt to go directly to write timeout.
2286 for (uint32 i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
2287 ch1.Ping(i);
2288 }
2289 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2290 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2291}
2292
2293// This test verifies the connection setup between ICEMODE_FULL
2294// and ICEMODE_LITE.
2295// In this test |ch1| behaves like FULL mode client and we have created
2296// port which responds to the ping message just like LITE client.
2297TEST_F(PortTest, TestIceLiteConnectivity) {
2298 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002299 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002300 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2301
2302 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002303 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002304 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2305 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002306 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002307 ch1.SetIceMode(ICEMODE_FULL);
2308
2309 // Start gathering candidates.
2310 ch1.Start();
2311 ice_lite_port->PrepareAddress();
2312
2313 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2314 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2315
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002316 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002317 ASSERT_TRUE(ch1.conn() != NULL);
2318 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2319
2320 // Send ping from full mode client.
2321 // This ping must not have USE_CANDIDATE_ATTR.
2322 ch1.Ping();
2323
2324 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2325 // from port.
2326 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2327 IceMessage* msg = ice_full_port->last_stun_msg();
2328 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2329
2330 // Respond with a BINDING-RESPONSE from litemode client.
2331 // NOTE: Ideally we should't create connection at this stage from lite
2332 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2333 // But we need a connection to send a response message.
2334 ice_lite_port->CreateConnection(
2335 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2336 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2337 ice_lite_port->SendBindingResponse(
2338 request.get(), ice_full_port->Candidates()[0].address());
2339
2340 // Feeding the respone message from litemode to the full mode connection.
2341 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->Data(),
2342 ice_lite_port->last_stun_buf()->Length(),
2343 rtc::PacketTime());
2344 // Verifying full mode connection becomes writable from the response.
2345 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2346 kTimeout);
2347 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2348
2349 // Clear existing stun messsages. Otherwise we will process old stun
2350 // message right after we send ping.
2351 ice_full_port->Reset();
2352 // Send ping. This must have USE_CANDIDATE_ATTR.
2353 ch1.Ping();
2354 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2355 msg = ice_full_port->last_stun_msg();
2356 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2357 ch1.Stop();
2358}
2359
2360// This test case verifies that the CONTROLLING port does not time out.
2361TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002362 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2363 ConnectToSignalDestroyed(port1);
2364 port1->set_timeout_delay(10); // milliseconds
2365 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2366 port1->SetIceTiebreaker(kTiebreaker1);
2367
2368 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2369 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2370 port2->SetIceTiebreaker(kTiebreaker2);
2371
2372 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002373 TestChannel ch1(port1);
2374 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002375
2376 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002377 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002378
2379 // After the connection is destroyed, the port should not be destroyed.
2380 rtc::Thread::Current()->ProcessMessages(kTimeout);
2381 EXPECT_FALSE(destroyed());
2382}
2383
2384// This test case verifies that the CONTROLLED port does time out, but only
2385// after connectivity is lost.
2386TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002387 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2388 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2389 port1->SetIceTiebreaker(kTiebreaker1);
2390
2391 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2392 ConnectToSignalDestroyed(port2);
2393 port2->set_timeout_delay(10); // milliseconds
2394 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2395 port2->SetIceTiebreaker(kTiebreaker2);
2396
2397 // The connection must not be destroyed before a connection is attempted.
2398 EXPECT_FALSE(destroyed());
2399
2400 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2401 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2402
2403 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002404 TestChannel ch1(port1);
2405 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002406
2407 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002408 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002409
2410 // The controlled port should be destroyed after 10 milliseconds.
2411 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2412}
honghaizd0b31432015-09-30 12:42:17 -07002413
2414// This test case verifies that if the role of a port changes from controlled
2415// to controlling after all connections fail, the port will not be destroyed.
2416TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2417 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2418 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2419 port1->SetIceTiebreaker(kTiebreaker1);
2420
2421 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2422 ConnectToSignalDestroyed(port2);
2423 port2->set_timeout_delay(10); // milliseconds
2424 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2425 port2->SetIceTiebreaker(kTiebreaker2);
2426
2427 // The connection must not be destroyed before a connection is attempted.
2428 EXPECT_FALSE(destroyed());
2429
2430 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2431 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2432
2433 // Set up channels and ensure both ports will be deleted.
2434 TestChannel ch1(port1);
2435 TestChannel ch2(port2);
2436
2437 // Simulate a connection that succeeds, and then is destroyed.
2438 StartConnectAndStopChannels(&ch1, &ch2);
2439 // Switch the role after all connections are destroyed.
2440 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2441 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2442 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2443
2444 // After the connection is destroyed, the port should not be destroyed.
2445 rtc::Thread::Current()->ProcessMessages(kTimeout);
2446 EXPECT_FALSE(destroyed());
2447}