blob: fc49f20a5d7ef7e55721555686ac182206e44ff5 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/base/basicpacketsocketfactory.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012#include "webrtc/p2p/base/relayport.h"
13#include "webrtc/p2p/base/stunport.h"
14#include "webrtc/p2p/base/tcpport.h"
15#include "webrtc/p2p/base/testrelayserver.h"
16#include "webrtc/p2p/base/teststunserver.h"
17#include "webrtc/p2p/base/testturnserver.h"
18#include "webrtc/p2p/base/transport.h"
19#include "webrtc/p2p/base/turnport.h"
tfarina5237aaf2015-11-10 23:44:30 -080020#include "webrtc/base/arraysize.h"
jbauchf1f87202016-03-30 06:43:37 -070021#include "webrtc/base/buffer.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000022#include "webrtc/base/crc32.h"
23#include "webrtc/base/gunit.h"
24#include "webrtc/base/helpers.h"
25#include "webrtc/base/logging.h"
26#include "webrtc/base/natserver.h"
27#include "webrtc/base/natsocketfactory.h"
28#include "webrtc/base/physicalsocketserver.h"
29#include "webrtc/base/scoped_ptr.h"
30#include "webrtc/base/socketaddress.h"
31#include "webrtc/base/ssladapter.h"
32#include "webrtc/base/stringutils.h"
33#include "webrtc/base/thread.h"
34#include "webrtc/base/virtualsocketserver.h"
35
36using rtc::AsyncPacketSocket;
jbauchf1f87202016-03-30 06:43:37 -070037using rtc::Buffer;
38using rtc::ByteBufferReader;
39using rtc::ByteBufferWriter;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000040using rtc::NATType;
41using rtc::NAT_OPEN_CONE;
42using rtc::NAT_ADDR_RESTRICTED;
43using rtc::NAT_PORT_RESTRICTED;
44using rtc::NAT_SYMMETRIC;
45using rtc::PacketSocketFactory;
46using rtc::scoped_ptr;
47using rtc::Socket;
48using rtc::SocketAddress;
49using namespace cricket;
50
51static const int kTimeout = 1000;
52static const SocketAddress kLocalAddr1("192.168.1.2", 0);
53static const SocketAddress kLocalAddr2("192.168.1.3", 0);
deadbeefc5d0d952015-07-16 10:22:21 -070054static const SocketAddress kNatAddr1("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
55static const SocketAddress kNatAddr2("88.88.88.88", rtc::NAT_SERVER_UDP_PORT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000056static const SocketAddress kStunAddr("99.99.99.1", STUN_SERVER_PORT);
57static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
58static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
59static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
60static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
61static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
62static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
63static const SocketAddress kTurnUdpIntAddr("99.99.99.4", STUN_SERVER_PORT);
Honghai Zhang80f1db92016-01-27 11:54:45 -080064static const SocketAddress kTurnTcpIntAddr("99.99.99.4", 5010);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000065static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
66static const RelayCredentials kRelayCredentials("test", "test");
67
68// TODO: Update these when RFC5245 is completely supported.
69// Magic value of 30 is from RFC3484, for IPv4 addresses.
Peter Boström0c4e06b2015-10-07 12:23:21 +020070static const uint32_t kDefaultPrflxPriority =
71 ICE_TYPE_PREFERENCE_PRFLX << 24 | 30 << 8 |
72 (256 - ICE_CANDIDATE_COMPONENT_DEFAULT);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073
74static const int kTiebreaker1 = 11111;
75static const int kTiebreaker2 = 22222;
76
Guo-wei Shiehbe508a12015-04-06 12:48:47 -070077static const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
78
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000079static Candidate GetCandidate(Port* port) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -070080 assert(port->Candidates().size() >= 1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000081 return port->Candidates()[0];
82}
83
84static SocketAddress GetAddress(Port* port) {
85 return GetCandidate(port).address();
86}
87
88static IceMessage* CopyStunMessage(const IceMessage* src) {
89 IceMessage* dst = new IceMessage();
jbauchf1f87202016-03-30 06:43:37 -070090 ByteBufferWriter buf;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091 src->Write(&buf);
jbauchf1f87202016-03-30 06:43:37 -070092 ByteBufferReader read_buf(buf);
93 dst->Read(&read_buf);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000094 return dst;
95}
96
jbauchf1f87202016-03-30 06:43:37 -070097static bool WriteStunMessage(const StunMessage* msg, ByteBufferWriter* buf) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098 buf->Resize(0); // clear out any existing buffer contents
99 return msg->Write(buf);
100}
101
102// Stub port class for testing STUN generation and processing.
103class TestPort : public Port {
104 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000105 TestPort(rtc::Thread* thread,
106 const std::string& type,
107 rtc::PacketSocketFactory* factory,
108 rtc::Network* network,
109 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200110 uint16_t min_port,
111 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000112 const std::string& username_fragment,
113 const std::string& password)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200114 : Port(thread,
115 type,
116 factory,
117 network,
118 ip,
119 min_port,
120 max_port,
121 username_fragment,
122 password) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000123 ~TestPort() {}
124
125 // Expose GetStunMessage so that we can test it.
126 using cricket::Port::GetStunMessage;
127
128 // The last StunMessage that was sent on this Port.
129 // TODO: Make these const; requires changes to SendXXXXResponse.
jbauchf1f87202016-03-30 06:43:37 -0700130 Buffer* last_stun_buf() { return last_stun_buf_.get(); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000131 IceMessage* last_stun_msg() { return last_stun_msg_.get(); }
132 int last_stun_error_code() {
133 int code = 0;
134 if (last_stun_msg_) {
135 const StunErrorCodeAttribute* error_attr = last_stun_msg_->GetErrorCode();
136 if (error_attr) {
137 code = error_attr->code();
138 }
139 }
140 return code;
141 }
142
143 virtual void PrepareAddress() {
144 rtc::SocketAddress addr(ip(), min_port());
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700145 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 ICE_TYPE_PREFERENCE_HOST, 0, true);
147 }
148
Honghai Zhangf9945b22015-12-15 12:20:13 -0800149 virtual bool SupportsProtocol(const std::string& protocol) const {
150 return true;
151 }
152
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153 // Exposed for testing candidate building.
154 void AddCandidateAddress(const rtc::SocketAddress& addr) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700155 AddAddress(addr, addr, rtc::SocketAddress(), "udp", "", "", Type(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 type_preference_, 0, false);
157 }
158 void AddCandidateAddress(const rtc::SocketAddress& addr,
159 const rtc::SocketAddress& base_address,
160 const std::string& type,
161 int type_preference,
162 bool final) {
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700163 AddAddress(addr, base_address, rtc::SocketAddress(), "udp", "", "", type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 type_preference, 0, final);
165 }
166
167 virtual Connection* CreateConnection(const Candidate& remote_candidate,
168 CandidateOrigin origin) {
169 Connection* conn = new ProxyConnection(this, 0, remote_candidate);
170 AddConnection(conn);
171 // Set use-candidate attribute flag as this will add USE-CANDIDATE attribute
172 // in STUN binding requests.
173 conn->set_use_candidate_attr(true);
174 return conn;
175 }
176 virtual int SendTo(
177 const void* data, size_t size, const rtc::SocketAddress& addr,
178 const rtc::PacketOptions& options, bool payload) {
179 if (!payload) {
180 IceMessage* msg = new IceMessage;
jbauchf1f87202016-03-30 06:43:37 -0700181 Buffer* buf = new Buffer(static_cast<const char*>(data), size);
182 ByteBufferReader read_buf(*buf);
183 if (!msg->Read(&read_buf)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 delete msg;
185 delete buf;
186 return -1;
187 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188 last_stun_buf_.reset(buf);
189 last_stun_msg_.reset(msg);
190 }
191 return static_cast<int>(size);
192 }
193 virtual int SetOption(rtc::Socket::Option opt, int value) {
194 return 0;
195 }
196 virtual int GetOption(rtc::Socket::Option opt, int* value) {
197 return -1;
198 }
199 virtual int GetError() {
200 return 0;
201 }
202 void Reset() {
203 last_stun_buf_.reset();
204 last_stun_msg_.reset();
205 }
206 void set_type_preference(int type_preference) {
207 type_preference_ = type_preference;
208 }
209
210 private:
Stefan Holmer55674ff2016-01-14 15:49:16 +0100211 void OnSentPacket(rtc::AsyncPacketSocket* socket,
212 const rtc::SentPacket& sent_packet) {
213 PortInterface::SignalSentPacket(sent_packet);
214 }
jbauchf1f87202016-03-30 06:43:37 -0700215 rtc::scoped_ptr<Buffer> last_stun_buf_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216 rtc::scoped_ptr<IceMessage> last_stun_msg_;
pbos7640ffa2015-11-30 09:16:59 -0800217 int type_preference_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218};
219
220class TestChannel : public sigslot::has_slots<> {
221 public:
222 // Takes ownership of |p1| (but not |p2|).
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700223 TestChannel(Port* p1)
224 : ice_mode_(ICEMODE_FULL),
225 port_(p1),
226 complete_count_(0),
227 conn_(NULL),
228 remote_request_(),
229 nominated_(false) {
230 port_->SignalPortComplete.connect(this, &TestChannel::OnPortComplete);
231 port_->SignalUnknownAddress.connect(this, &TestChannel::OnUnknownAddress);
232 port_->SignalDestroyed.connect(this, &TestChannel::OnSrcPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233 }
234
235 int complete_count() { return complete_count_; }
236 Connection* conn() { return conn_; }
237 const SocketAddress& remote_address() { return remote_address_; }
238 const std::string remote_fragment() { return remote_frag_; }
239
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700240 void Start() { port_->PrepareAddress(); }
241 void CreateConnection(const Candidate& remote_candidate) {
242 conn_ = port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000243 IceMode remote_ice_mode =
244 (ice_mode_ == ICEMODE_FULL) ? ICEMODE_LITE : ICEMODE_FULL;
245 conn_->set_remote_ice_mode(remote_ice_mode);
246 conn_->set_use_candidate_attr(remote_ice_mode == ICEMODE_FULL);
247 conn_->SignalStateChange.connect(
248 this, &TestChannel::OnConnectionStateChange);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700249 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700250 conn_->SignalReadyToSend.connect(this,
251 &TestChannel::OnConnectionReadyToSend);
252 connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253 }
254 void OnConnectionStateChange(Connection* conn) {
255 if (conn->write_state() == Connection::STATE_WRITABLE) {
256 conn->set_use_candidate_attr(true);
257 nominated_ = true;
258 }
259 }
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700260 void AcceptConnection(const Candidate& remote_candidate) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 ASSERT_TRUE(remote_request_.get() != NULL);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700262 Candidate c = remote_candidate;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263 c.set_address(remote_address_);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700264 conn_ = port_->CreateConnection(c, Port::ORIGIN_MESSAGE);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700265 conn_->SignalDestroyed.connect(this, &TestChannel::OnDestroyed);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700266 port_->SendBindingResponse(remote_request_.get(), remote_address_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 remote_request_.reset();
268 }
269 void Ping() {
270 Ping(0);
271 }
honghaiz34b11eb2016-03-16 08:55:44 -0700272 void Ping(int64_t now) { conn_->Ping(now); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273 void Stop() {
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700274 if (conn_) {
275 conn_->Destroy();
276 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277 }
278
279 void OnPortComplete(Port* port) {
280 complete_count_++;
281 }
282 void SetIceMode(IceMode ice_mode) {
283 ice_mode_ = ice_mode;
284 }
285
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700286 int SendData(const char* data, size_t len) {
287 rtc::PacketOptions options;
288 return conn_->Send(data, len, options);
289 }
290
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 void OnUnknownAddress(PortInterface* port, const SocketAddress& addr,
292 ProtocolType proto,
293 IceMessage* msg, const std::string& rf,
294 bool /*port_muxed*/) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700295 ASSERT_EQ(port_.get(), port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 if (!remote_address_.IsNil()) {
297 ASSERT_EQ(remote_address_, addr);
298 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 const cricket::StunUInt32Attribute* priority_attr =
300 msg->GetUInt32(STUN_ATTR_PRIORITY);
301 const cricket::StunByteStringAttribute* mi_attr =
302 msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY);
303 const cricket::StunUInt32Attribute* fingerprint_attr =
304 msg->GetUInt32(STUN_ATTR_FINGERPRINT);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700305 EXPECT_TRUE(priority_attr != NULL);
306 EXPECT_TRUE(mi_attr != NULL);
307 EXPECT_TRUE(fingerprint_attr != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 remote_address_ = addr;
309 remote_request_.reset(CopyStunMessage(msg));
310 remote_frag_ = rf;
311 }
312
313 void OnDestroyed(Connection* conn) {
314 ASSERT_EQ(conn_, conn);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700315 LOG(INFO) << "OnDestroy connection " << conn << " deleted";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 conn_ = NULL;
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700317 // When the connection is destroyed, also clear these fields so future
318 // connections are possible.
319 remote_request_.reset();
320 remote_address_.Clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321 }
322
323 void OnSrcPortDestroyed(PortInterface* port) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700324 Port* destroyed_src = port_.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000325 ASSERT_EQ(destroyed_src, port);
326 }
327
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700328 Port* port() { return port_.get(); }
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700329
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000330 bool nominated() const { return nominated_; }
331
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700332 void set_connection_ready_to_send(bool ready) {
333 connection_ready_to_send_ = ready;
334 }
335 bool connection_ready_to_send() const {
336 return connection_ready_to_send_;
337 }
338
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 private:
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700340 // ReadyToSend will only issue after a Connection recovers from EWOULDBLOCK.
341 void OnConnectionReadyToSend(Connection* conn) {
342 ASSERT_EQ(conn, conn_);
343 connection_ready_to_send_ = true;
344 }
345
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000346 IceMode ice_mode_;
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700347 rtc::scoped_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348
349 int complete_count_;
350 Connection* conn_;
351 SocketAddress remote_address_;
352 rtc::scoped_ptr<StunMessage> remote_request_;
353 std::string remote_frag_;
354 bool nominated_;
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700355 bool connection_ready_to_send_ = false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356};
357
358class PortTest : public testing::Test, public sigslot::has_slots<> {
359 public:
360 PortTest()
361 : main_(rtc::Thread::Current()),
362 pss_(new rtc::PhysicalSocketServer),
363 ss_(new rtc::VirtualSocketServer(pss_.get())),
364 ss_scope_(ss_.get()),
365 network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
366 socket_factory_(rtc::Thread::Current()),
deadbeefc5d0d952015-07-16 10:22:21 -0700367 nat_factory1_(ss_.get(), kNatAddr1, SocketAddress()),
368 nat_factory2_(ss_.get(), kNatAddr2, SocketAddress()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000369 nat_socket_factory1_(&nat_factory1_),
370 nat_socket_factory2_(&nat_factory2_),
371 stun_server_(TestStunServer::Create(main_, kStunAddr)),
372 turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700373 relay_server_(main_,
374 kRelayUdpIntAddr,
375 kRelayUdpExtAddr,
376 kRelayTcpIntAddr,
377 kRelayTcpExtAddr,
378 kRelaySslTcpIntAddr,
379 kRelaySslTcpExtAddr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380 username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
381 password_(rtc::CreateRandomString(ICE_PWD_LENGTH)),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 role_conflict_(false),
383 destroyed_(false) {
384 network_.AddIP(rtc::IPAddress(INADDR_ANY));
385 }
386
387 protected:
388 void TestLocalToLocal() {
389 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700390 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000391 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700392 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000393 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
394 }
395 void TestLocalToStun(NATType ntype) {
396 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700397 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype));
399 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700400 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 TestConnectivity("udp", port1, StunName(ntype), port2,
402 ntype == NAT_OPEN_CONE, true,
403 ntype != NAT_SYMMETRIC, true);
404 }
405 void TestLocalToRelay(RelayType rtype, ProtocolType proto) {
406 Port* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700407 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700409 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 TestConnectivity("udp", port1, RelayName(rtype, proto), port2,
411 rtype == RELAY_GTURN, true, true, true);
412 }
413 void TestStunToLocal(NATType ntype) {
414 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
415 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700416 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000417 Port* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700418 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000419 TestConnectivity(StunName(ntype), port1, "udp", port2,
420 true, ntype != NAT_SYMMETRIC, true, true);
421 }
422 void TestStunToStun(NATType ntype1, NATType ntype2) {
423 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype1));
424 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700425 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000426 nat_server2_.reset(CreateNatServer(kNatAddr2, ntype2));
427 Port* port2 = CreateStunPort(kLocalAddr2, &nat_socket_factory2_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700428 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000429 TestConnectivity(StunName(ntype1), port1, StunName(ntype2), port2,
430 ntype2 == NAT_OPEN_CONE,
431 ntype1 != NAT_SYMMETRIC, ntype2 != NAT_SYMMETRIC,
432 ntype1 + ntype2 < (NAT_PORT_RESTRICTED + NAT_SYMMETRIC));
433 }
434 void TestStunToRelay(NATType ntype, RelayType rtype, ProtocolType proto) {
435 nat_server1_.reset(CreateNatServer(kNatAddr1, ntype));
436 Port* port1 = CreateStunPort(kLocalAddr1, &nat_socket_factory1_);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700437 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_UDP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700439 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 TestConnectivity(StunName(ntype), port1, RelayName(rtype, proto), port2,
441 rtype == RELAY_GTURN, ntype != NAT_SYMMETRIC, true, true);
442 }
443 void TestTcpToTcp() {
444 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700445 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700447 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 TestConnectivity("tcp", port1, "tcp", port2, true, false, true, true);
449 }
450 void TestTcpToRelay(RelayType rtype, ProtocolType proto) {
451 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700452 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_TCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700454 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455 TestConnectivity("tcp", port1, RelayName(rtype, proto), port2,
456 rtype == RELAY_GTURN, false, true, true);
457 }
458 void TestSslTcpToRelay(RelayType rtype, ProtocolType proto) {
459 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700460 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 Port* port2 = CreateRelayPort(kLocalAddr2, rtype, proto, PROTO_SSLTCP);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700462 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 TestConnectivity("ssltcp", port1, RelayName(rtype, proto), port2,
464 rtype == RELAY_GTURN, false, true, true);
465 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 // helpers for above functions
467 UDPPort* CreateUdpPort(const SocketAddress& addr) {
468 return CreateUdpPort(addr, &socket_factory_);
469 }
470 UDPPort* CreateUdpPort(const SocketAddress& addr,
471 PacketSocketFactory* socket_factory) {
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800472 return UDPPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
473 0, username_, password_, std::string(), true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 }
475 TCPPort* CreateTcpPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700476 return CreateTcpPort(addr, &socket_factory_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 }
478 TCPPort* CreateTcpPort(const SocketAddress& addr,
479 PacketSocketFactory* socket_factory) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700480 return TCPPort::Create(main_, socket_factory, &network_,
481 addr.ipaddr(), 0, 0, username_, password_,
482 true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000483 }
484 StunPort* CreateStunPort(const SocketAddress& addr,
485 rtc::PacketSocketFactory* factory) {
486 ServerAddresses stun_servers;
487 stun_servers.insert(kStunAddr);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700488 return StunPort::Create(main_, factory, &network_,
489 addr.ipaddr(), 0, 0,
490 username_, password_, stun_servers,
491 std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 }
493 Port* CreateRelayPort(const SocketAddress& addr, RelayType rtype,
494 ProtocolType int_proto, ProtocolType ext_proto) {
495 if (rtype == RELAY_TURN) {
496 return CreateTurnPort(addr, &socket_factory_, int_proto, ext_proto);
497 } else {
498 return CreateGturnPort(addr, int_proto, ext_proto);
499 }
500 }
501 TurnPort* CreateTurnPort(const SocketAddress& addr,
502 PacketSocketFactory* socket_factory,
503 ProtocolType int_proto, ProtocolType ext_proto) {
Honghai Zhang80f1db92016-01-27 11:54:45 -0800504 SocketAddress server_addr =
505 int_proto == PROTO_TCP ? kTurnTcpIntAddr : kTurnUdpIntAddr;
506 return CreateTurnPort(addr, socket_factory, int_proto, ext_proto,
507 server_addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508 }
509 TurnPort* CreateTurnPort(const SocketAddress& addr,
510 PacketSocketFactory* socket_factory,
511 ProtocolType int_proto, ProtocolType ext_proto,
512 const rtc::SocketAddress& server_addr) {
Honghai Zhang80f1db92016-01-27 11:54:45 -0800513 return TurnPort::Create(main_, socket_factory, &network_, addr.ipaddr(), 0,
514 0, username_, password_,
515 ProtocolAddress(server_addr, int_proto),
516 kRelayCredentials, 0, std::string());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000517 }
518 RelayPort* CreateGturnPort(const SocketAddress& addr,
519 ProtocolType int_proto, ProtocolType ext_proto) {
520 RelayPort* port = CreateGturnPort(addr);
521 SocketAddress addrs[] =
522 { kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr };
523 port->AddServerAddress(ProtocolAddress(addrs[int_proto], int_proto));
524 return port;
525 }
526 RelayPort* CreateGturnPort(const SocketAddress& addr) {
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700527 // TODO(pthatcher): Remove GTURN.
528 return RelayPort::Create(main_, &socket_factory_, &network_,
529 addr.ipaddr(), 0, 0,
530 username_, password_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000531 // TODO: Add an external address for ext_proto, so that the
532 // other side can connect to this port using a non-UDP protocol.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000533 }
534 rtc::NATServer* CreateNatServer(const SocketAddress& addr,
535 rtc::NATType type) {
deadbeefc5d0d952015-07-16 10:22:21 -0700536 return new rtc::NATServer(type, ss_.get(), addr, addr, ss_.get(), addr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000537 }
538 static const char* StunName(NATType type) {
539 switch (type) {
540 case NAT_OPEN_CONE: return "stun(open cone)";
541 case NAT_ADDR_RESTRICTED: return "stun(addr restricted)";
542 case NAT_PORT_RESTRICTED: return "stun(port restricted)";
543 case NAT_SYMMETRIC: return "stun(symmetric)";
544 default: return "stun(?)";
545 }
546 }
547 static const char* RelayName(RelayType type, ProtocolType proto) {
548 if (type == RELAY_TURN) {
549 switch (proto) {
550 case PROTO_UDP: return "turn(udp)";
551 case PROTO_TCP: return "turn(tcp)";
552 case PROTO_SSLTCP: return "turn(ssltcp)";
553 default: return "turn(?)";
554 }
555 } else {
556 switch (proto) {
557 case PROTO_UDP: return "gturn(udp)";
558 case PROTO_TCP: return "gturn(tcp)";
559 case PROTO_SSLTCP: return "gturn(ssltcp)";
560 default: return "gturn(?)";
561 }
562 }
563 }
564
honghaiza0c44ea2016-03-23 16:07:48 -0700565 void SetNetworkType(rtc::AdapterType adapter_type) {
566 network_.set_type(adapter_type);
567 }
568
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 void TestCrossFamilyPorts(int type);
570
Peter Thatcherb8b01432015-07-07 16:45:53 -0700571 void ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2);
572
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000573 // This does all the work and then deletes |port1| and |port2|.
574 void TestConnectivity(const char* name1, Port* port1,
575 const char* name2, Port* port2,
576 bool accept, bool same_addr1,
577 bool same_addr2, bool possible);
578
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700579 // This connects the provided channels which have already started. |ch1|
580 // should have its Connection created (either through CreateConnection() or
581 // TCP reconnecting mechanism before entering this function.
582 void ConnectStartedChannels(TestChannel* ch1, TestChannel* ch2) {
583 ASSERT_TRUE(ch1->conn());
584 EXPECT_TRUE_WAIT(ch1->conn()->connected(), kTimeout); // for TCP connect
585 ch1->Ping();
586 WAIT(!ch2->remote_address().IsNil(), kTimeout);
587
588 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700589 ch2->AcceptConnection(GetCandidate(ch1->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700590 ch2->Ping();
591 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2->conn()->write_state(),
592 kTimeout);
593 }
594
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595 // This connects and disconnects the provided channels in the same sequence as
596 // TestConnectivity with all options set to |true|. It does not delete either
597 // channel.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700598 void StartConnectAndStopChannels(TestChannel* ch1, TestChannel* ch2) {
599 // Acquire addresses.
600 ch1->Start();
601 ch2->Start();
602
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700603 ch1->CreateConnection(GetCandidate(ch2->port()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700604 ConnectStartedChannels(ch1, ch2);
605
606 // Destroy the connections.
607 ch1->Stop();
608 ch2->Stop();
609 }
610
611 // This disconnects both end's Connection and make sure ch2 ready for new
612 // connection.
613 void DisconnectTcpTestChannels(TestChannel* ch1, TestChannel* ch2) {
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700614 TCPConnection* tcp_conn1 = static_cast<TCPConnection*>(ch1->conn());
615 TCPConnection* tcp_conn2 = static_cast<TCPConnection*>(ch2->conn());
616 ASSERT_TRUE(
617 ss_->CloseTcpConnections(tcp_conn1->socket()->GetLocalAddress(),
618 tcp_conn2->socket()->GetLocalAddress()));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700619
620 // Wait for both OnClose are delivered.
621 EXPECT_TRUE_WAIT(!ch1->conn()->connected(), kTimeout);
622 EXPECT_TRUE_WAIT(!ch2->conn()->connected(), kTimeout);
623
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700624 // Ensure redundant SignalClose events on TcpConnection won't break tcp
625 // reconnection. Chromium will fire SignalClose for all outstanding IPC
626 // packets during reconnection.
627 tcp_conn1->socket()->SignalClose(tcp_conn1->socket(), 0);
628 tcp_conn2->socket()->SignalClose(tcp_conn2->socket(), 0);
629
630 // Speed up destroying ch2's connection such that the test is ready to
631 // accept a new connection from ch1 before ch1's connection destroys itself.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700632 ch2->conn()->Destroy();
633 EXPECT_TRUE_WAIT(ch2->conn() == NULL, kTimeout);
634 }
635
636 void TestTcpReconnect(bool ping_after_disconnected,
637 bool send_after_disconnected) {
638 Port* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700639 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700640 Port* port2 = CreateTcpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700641 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700642
643 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
644 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
645
646 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700647 TestChannel ch1(port1);
648 TestChannel ch2(port2);
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700649 EXPECT_EQ(0, ch1.complete_count());
650 EXPECT_EQ(0, ch2.complete_count());
651
652 ch1.Start();
653 ch2.Start();
654 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
655 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
656
657 // Initial connecting the channel, create connection on channel1.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700658 ch1.CreateConnection(GetCandidate(port2));
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700659 ConnectStartedChannels(&ch1, &ch2);
660
661 // Shorten the timeout period.
662 const int kTcpReconnectTimeout = kTimeout;
663 static_cast<TCPConnection*>(ch1.conn())
664 ->set_reconnection_timeout(kTcpReconnectTimeout);
665 static_cast<TCPConnection*>(ch2.conn())
666 ->set_reconnection_timeout(kTcpReconnectTimeout);
667
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700668 EXPECT_FALSE(ch1.connection_ready_to_send());
669 EXPECT_FALSE(ch2.connection_ready_to_send());
670
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700671 // Once connected, disconnect them.
672 DisconnectTcpTestChannels(&ch1, &ch2);
673
674 if (send_after_disconnected || ping_after_disconnected) {
675 if (send_after_disconnected) {
676 // First SendData after disconnect should fail but will trigger
677 // reconnect.
678 EXPECT_EQ(-1, ch1.SendData(data, static_cast<int>(strlen(data))));
679 }
680
681 if (ping_after_disconnected) {
682 // Ping should trigger reconnect.
683 ch1.Ping();
684 }
685
686 // Wait for channel's outgoing TCPConnection connected.
687 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout);
688
689 // Verify that we could still connect channels.
690 ConnectStartedChannels(&ch1, &ch2);
Guo-wei Shiehb5940412015-08-24 11:58:03 -0700691 EXPECT_TRUE_WAIT(ch1.connection_ready_to_send(),
692 kTcpReconnectTimeout);
693 // Channel2 is the passive one so a new connection is created during
694 // reconnect. This new connection should never have issued EWOULDBLOCK
695 // hence the connection_ready_to_send() should be false.
696 EXPECT_FALSE(ch2.connection_ready_to_send());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700697 } else {
698 EXPECT_EQ(ch1.conn()->write_state(), Connection::STATE_WRITABLE);
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700699 // Since the reconnection never happens, the connections should have been
700 // destroyed after the timeout.
701 EXPECT_TRUE_WAIT(!ch1.conn(), kTcpReconnectTimeout + kTimeout);
702 EXPECT_TRUE(!ch2.conn());
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700703 }
704
705 // Tear down and ensure that goes smoothly.
706 ch1.Stop();
707 ch2.Stop();
708 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
709 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
710 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000711
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000712 IceMessage* CreateStunMessage(int type) {
713 IceMessage* msg = new IceMessage();
714 msg->SetType(type);
715 msg->SetTransactionID("TESTTESTTEST");
716 return msg;
717 }
718 IceMessage* CreateStunMessageWithUsername(int type,
719 const std::string& username) {
720 IceMessage* msg = CreateStunMessage(type);
721 msg->AddAttribute(
722 new StunByteStringAttribute(STUN_ATTR_USERNAME, username));
723 return msg;
724 }
725 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
726 const std::string& username,
727 const std::string& password) {
728 TestPort* port = new TestPort(main_, "test", &socket_factory_, &network_,
729 addr.ipaddr(), 0, 0, username, password);
730 port->SignalRoleConflict.connect(this, &PortTest::OnRoleConflict);
731 return port;
732 }
733 TestPort* CreateTestPort(const rtc::SocketAddress& addr,
734 const std::string& username,
735 const std::string& password,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 cricket::IceRole role,
737 int tiebreaker) {
738 TestPort* port = CreateTestPort(addr, username, password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739 port->SetIceRole(role);
740 port->SetIceTiebreaker(tiebreaker);
741 return port;
742 }
743
744 void OnRoleConflict(PortInterface* port) {
745 role_conflict_ = true;
746 }
747 bool role_conflict() const { return role_conflict_; }
748
749 void ConnectToSignalDestroyed(PortInterface* port) {
750 port->SignalDestroyed.connect(this, &PortTest::OnDestroyed);
751 }
752
753 void OnDestroyed(PortInterface* port) {
754 destroyed_ = true;
755 }
756 bool destroyed() const { return destroyed_; }
757
758 rtc::BasicPacketSocketFactory* nat_socket_factory1() {
759 return &nat_socket_factory1_;
760 }
761
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700762 protected:
763 rtc::VirtualSocketServer* vss() { return ss_.get(); }
764
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000765 private:
766 rtc::Thread* main_;
767 rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
768 rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
769 rtc::SocketServerScope ss_scope_;
770 rtc::Network network_;
771 rtc::BasicPacketSocketFactory socket_factory_;
772 rtc::scoped_ptr<rtc::NATServer> nat_server1_;
773 rtc::scoped_ptr<rtc::NATServer> nat_server2_;
774 rtc::NATSocketFactory nat_factory1_;
775 rtc::NATSocketFactory nat_factory2_;
776 rtc::BasicPacketSocketFactory nat_socket_factory1_;
777 rtc::BasicPacketSocketFactory nat_socket_factory2_;
778 scoped_ptr<TestStunServer> stun_server_;
779 TestTurnServer turn_server_;
780 TestRelayServer relay_server_;
781 std::string username_;
782 std::string password_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000783 bool role_conflict_;
784 bool destroyed_;
785};
786
787void PortTest::TestConnectivity(const char* name1, Port* port1,
788 const char* name2, Port* port2,
789 bool accept, bool same_addr1,
790 bool same_addr2, bool possible) {
791 LOG(LS_INFO) << "Test: " << name1 << " to " << name2 << ": ";
792 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
793 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
794
795 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700796 TestChannel ch1(port1);
797 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000798 EXPECT_EQ(0, ch1.complete_count());
799 EXPECT_EQ(0, ch2.complete_count());
800
801 // Acquire addresses.
802 ch1.Start();
803 ch2.Start();
804 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
805 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
806
807 // Send a ping from src to dst. This may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700808 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000809 ASSERT_TRUE(ch1.conn() != NULL);
810 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
811 ch1.Ping();
812 WAIT(!ch2.remote_address().IsNil(), kTimeout);
813
814 if (accept) {
815 // We are able to send a ping from src to dst. This is the case when
816 // sending to UDP ports and cone NATs.
817 EXPECT_TRUE(ch1.remote_address().IsNil());
818 EXPECT_EQ(ch2.remote_fragment(), port1->username_fragment());
819
820 // Ensure the ping came from the same address used for src.
821 // This is the case unless the source NAT was symmetric.
822 if (same_addr1) EXPECT_EQ(ch2.remote_address(), GetAddress(port1));
823 EXPECT_TRUE(same_addr2);
824
825 // Send a ping from dst to src.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700826 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827 ASSERT_TRUE(ch2.conn() != NULL);
828 ch2.Ping();
829 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
830 kTimeout);
831 } else {
832 // We can't send a ping from src to dst, so flip it around. This will happen
833 // when the destination NAT is addr/port restricted or symmetric.
834 EXPECT_TRUE(ch1.remote_address().IsNil());
835 EXPECT_TRUE(ch2.remote_address().IsNil());
836
837 // Send a ping from dst to src. Again, this may or may not make it.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700838 ch2.CreateConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000839 ASSERT_TRUE(ch2.conn() != NULL);
840 ch2.Ping();
841 WAIT(ch2.conn()->write_state() == Connection::STATE_WRITABLE, kTimeout);
842
843 if (same_addr1 && same_addr2) {
844 // The new ping got back to the source.
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700845 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
847
848 // First connection may not be writable if the first ping did not get
849 // through. So we will have to do another.
850 if (ch1.conn()->write_state() == Connection::STATE_WRITE_INIT) {
851 ch1.Ping();
852 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
853 kTimeout);
854 }
855 } else if (!same_addr1 && possible) {
856 // The new ping went to the candidate address, but that address was bad.
857 // This will happen when the source NAT is symmetric.
858 EXPECT_TRUE(ch1.remote_address().IsNil());
859 EXPECT_TRUE(ch2.remote_address().IsNil());
860
861 // However, since we have now sent a ping to the source IP, we should be
862 // able to get a ping from it. This gives us the real source address.
863 ch1.Ping();
864 EXPECT_TRUE_WAIT(!ch2.remote_address().IsNil(), kTimeout);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700865 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 EXPECT_TRUE(ch1.remote_address().IsNil());
867
868 // Pick up the actual address and establish the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700869 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 ASSERT_TRUE(ch2.conn() != NULL);
871 ch2.Ping();
872 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch2.conn()->write_state(),
873 kTimeout);
874 } else if (!same_addr2 && possible) {
875 // The new ping came in, but from an unexpected address. This will happen
876 // when the destination NAT is symmetric.
877 EXPECT_FALSE(ch1.remote_address().IsNil());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700878 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879
880 // Update our address and complete the connection.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -0700881 ch1.AcceptConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000882 ch1.Ping();
883 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
884 kTimeout);
885 } else { // (!possible)
886 // There should be s no way for the pings to reach each other. Check it.
887 EXPECT_TRUE(ch1.remote_address().IsNil());
888 EXPECT_TRUE(ch2.remote_address().IsNil());
889 ch1.Ping();
890 WAIT(!ch2.remote_address().IsNil(), kTimeout);
891 EXPECT_TRUE(ch1.remote_address().IsNil());
892 EXPECT_TRUE(ch2.remote_address().IsNil());
893 }
894 }
895
896 // Everything should be good, unless we know the situation is impossible.
897 ASSERT_TRUE(ch1.conn() != NULL);
898 ASSERT_TRUE(ch2.conn() != NULL);
899 if (possible) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700900 EXPECT_TRUE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901 EXPECT_EQ(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700902 EXPECT_TRUE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903 EXPECT_EQ(Connection::STATE_WRITABLE, ch2.conn()->write_state());
904 } else {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700905 EXPECT_FALSE(ch1.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 EXPECT_NE(Connection::STATE_WRITABLE, ch1.conn()->write_state());
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700907 EXPECT_FALSE(ch2.conn()->receiving());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000908 EXPECT_NE(Connection::STATE_WRITABLE, ch2.conn()->write_state());
909 }
910
911 // Tear down and ensure that goes smoothly.
912 ch1.Stop();
913 ch2.Stop();
914 EXPECT_TRUE_WAIT(ch1.conn() == NULL, kTimeout);
915 EXPECT_TRUE_WAIT(ch2.conn() == NULL, kTimeout);
916}
917
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918class FakePacketSocketFactory : public rtc::PacketSocketFactory {
919 public:
920 FakePacketSocketFactory()
921 : next_udp_socket_(NULL),
922 next_server_tcp_socket_(NULL),
923 next_client_tcp_socket_(NULL) {
924 }
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000925 ~FakePacketSocketFactory() override { }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000927 AsyncPacketSocket* CreateUdpSocket(const SocketAddress& address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200928 uint16_t min_port,
929 uint16_t max_port) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930 EXPECT_TRUE(next_udp_socket_ != NULL);
931 AsyncPacketSocket* result = next_udp_socket_;
932 next_udp_socket_ = NULL;
933 return result;
934 }
935
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000936 AsyncPacketSocket* CreateServerTcpSocket(const SocketAddress& local_address,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200937 uint16_t min_port,
938 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000939 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940 EXPECT_TRUE(next_server_tcp_socket_ != NULL);
941 AsyncPacketSocket* result = next_server_tcp_socket_;
942 next_server_tcp_socket_ = NULL;
943 return result;
944 }
945
946 // TODO: |proxy_info| and |user_agent| should be set
947 // per-factory and not when socket is created.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000948 AsyncPacketSocket* CreateClientTcpSocket(const SocketAddress& local_address,
949 const SocketAddress& remote_address,
950 const rtc::ProxyInfo& proxy_info,
951 const std::string& user_agent,
952 int opts) override {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000953 EXPECT_TRUE(next_client_tcp_socket_ != NULL);
954 AsyncPacketSocket* result = next_client_tcp_socket_;
955 next_client_tcp_socket_ = NULL;
956 return result;
957 }
958
959 void set_next_udp_socket(AsyncPacketSocket* next_udp_socket) {
960 next_udp_socket_ = next_udp_socket;
961 }
962 void set_next_server_tcp_socket(AsyncPacketSocket* next_server_tcp_socket) {
963 next_server_tcp_socket_ = next_server_tcp_socket;
964 }
965 void set_next_client_tcp_socket(AsyncPacketSocket* next_client_tcp_socket) {
966 next_client_tcp_socket_ = next_client_tcp_socket;
967 }
968 rtc::AsyncResolverInterface* CreateAsyncResolver() {
969 return NULL;
970 }
971
972 private:
973 AsyncPacketSocket* next_udp_socket_;
974 AsyncPacketSocket* next_server_tcp_socket_;
975 AsyncPacketSocket* next_client_tcp_socket_;
976};
977
978class FakeAsyncPacketSocket : public AsyncPacketSocket {
979 public:
980 // Returns current local address. Address may be set to NULL if the
981 // socket is not bound yet (GetState() returns STATE_BINDING).
982 virtual SocketAddress GetLocalAddress() const {
983 return SocketAddress();
984 }
985
986 // Returns remote address. Returns zeroes if this is not a client TCP socket.
987 virtual SocketAddress GetRemoteAddress() const {
988 return SocketAddress();
989 }
990
991 // Send a packet.
992 virtual int Send(const void *pv, size_t cb,
993 const rtc::PacketOptions& options) {
994 return static_cast<int>(cb);
995 }
996 virtual int SendTo(const void *pv, size_t cb, const SocketAddress& addr,
997 const rtc::PacketOptions& options) {
998 return static_cast<int>(cb);
999 }
1000 virtual int Close() {
1001 return 0;
1002 }
1003
1004 virtual State GetState() const { return state_; }
1005 virtual int GetOption(Socket::Option opt, int* value) { return 0; }
1006 virtual int SetOption(Socket::Option opt, int value) { return 0; }
1007 virtual int GetError() const { return 0; }
1008 virtual void SetError(int error) { }
1009
1010 void set_state(State state) { state_ = state; }
1011
1012 private:
1013 State state_;
1014};
1015
1016// Local -> XXXX
1017TEST_F(PortTest, TestLocalToLocal) {
1018 TestLocalToLocal();
1019}
1020
1021TEST_F(PortTest, TestLocalToConeNat) {
1022 TestLocalToStun(NAT_OPEN_CONE);
1023}
1024
1025TEST_F(PortTest, TestLocalToARNat) {
1026 TestLocalToStun(NAT_ADDR_RESTRICTED);
1027}
1028
1029TEST_F(PortTest, TestLocalToPRNat) {
1030 TestLocalToStun(NAT_PORT_RESTRICTED);
1031}
1032
1033TEST_F(PortTest, TestLocalToSymNat) {
1034 TestLocalToStun(NAT_SYMMETRIC);
1035}
1036
1037// Flaky: https://code.google.com/p/webrtc/issues/detail?id=3316.
1038TEST_F(PortTest, DISABLED_TestLocalToTurn) {
1039 TestLocalToRelay(RELAY_TURN, PROTO_UDP);
1040}
1041
1042TEST_F(PortTest, TestLocalToGturn) {
1043 TestLocalToRelay(RELAY_GTURN, PROTO_UDP);
1044}
1045
1046TEST_F(PortTest, TestLocalToTcpGturn) {
1047 TestLocalToRelay(RELAY_GTURN, PROTO_TCP);
1048}
1049
1050TEST_F(PortTest, TestLocalToSslTcpGturn) {
1051 TestLocalToRelay(RELAY_GTURN, PROTO_SSLTCP);
1052}
1053
1054// Cone NAT -> XXXX
1055TEST_F(PortTest, TestConeNatToLocal) {
1056 TestStunToLocal(NAT_OPEN_CONE);
1057}
1058
1059TEST_F(PortTest, TestConeNatToConeNat) {
1060 TestStunToStun(NAT_OPEN_CONE, NAT_OPEN_CONE);
1061}
1062
1063TEST_F(PortTest, TestConeNatToARNat) {
1064 TestStunToStun(NAT_OPEN_CONE, NAT_ADDR_RESTRICTED);
1065}
1066
1067TEST_F(PortTest, TestConeNatToPRNat) {
1068 TestStunToStun(NAT_OPEN_CONE, NAT_PORT_RESTRICTED);
1069}
1070
1071TEST_F(PortTest, TestConeNatToSymNat) {
1072 TestStunToStun(NAT_OPEN_CONE, NAT_SYMMETRIC);
1073}
1074
1075TEST_F(PortTest, TestConeNatToTurn) {
1076 TestStunToRelay(NAT_OPEN_CONE, RELAY_TURN, PROTO_UDP);
1077}
1078
1079TEST_F(PortTest, TestConeNatToGturn) {
1080 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_UDP);
1081}
1082
1083TEST_F(PortTest, TestConeNatToTcpGturn) {
1084 TestStunToRelay(NAT_OPEN_CONE, RELAY_GTURN, PROTO_TCP);
1085}
1086
1087// Address-restricted NAT -> XXXX
1088TEST_F(PortTest, TestARNatToLocal) {
1089 TestStunToLocal(NAT_ADDR_RESTRICTED);
1090}
1091
1092TEST_F(PortTest, TestARNatToConeNat) {
1093 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_OPEN_CONE);
1094}
1095
1096TEST_F(PortTest, TestARNatToARNat) {
1097 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_ADDR_RESTRICTED);
1098}
1099
1100TEST_F(PortTest, TestARNatToPRNat) {
1101 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_PORT_RESTRICTED);
1102}
1103
1104TEST_F(PortTest, TestARNatToSymNat) {
1105 TestStunToStun(NAT_ADDR_RESTRICTED, NAT_SYMMETRIC);
1106}
1107
1108TEST_F(PortTest, TestARNatToTurn) {
1109 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_TURN, PROTO_UDP);
1110}
1111
1112TEST_F(PortTest, TestARNatToGturn) {
1113 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1114}
1115
1116TEST_F(PortTest, TestARNATNatToTcpGturn) {
1117 TestStunToRelay(NAT_ADDR_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1118}
1119
1120// Port-restricted NAT -> XXXX
1121TEST_F(PortTest, TestPRNatToLocal) {
1122 TestStunToLocal(NAT_PORT_RESTRICTED);
1123}
1124
1125TEST_F(PortTest, TestPRNatToConeNat) {
1126 TestStunToStun(NAT_PORT_RESTRICTED, NAT_OPEN_CONE);
1127}
1128
1129TEST_F(PortTest, TestPRNatToARNat) {
1130 TestStunToStun(NAT_PORT_RESTRICTED, NAT_ADDR_RESTRICTED);
1131}
1132
1133TEST_F(PortTest, TestPRNatToPRNat) {
1134 TestStunToStun(NAT_PORT_RESTRICTED, NAT_PORT_RESTRICTED);
1135}
1136
1137TEST_F(PortTest, TestPRNatToSymNat) {
1138 // Will "fail"
1139 TestStunToStun(NAT_PORT_RESTRICTED, NAT_SYMMETRIC);
1140}
1141
1142TEST_F(PortTest, TestPRNatToTurn) {
1143 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_TURN, PROTO_UDP);
1144}
1145
1146TEST_F(PortTest, TestPRNatToGturn) {
1147 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_UDP);
1148}
1149
1150TEST_F(PortTest, TestPRNatToTcpGturn) {
1151 TestStunToRelay(NAT_PORT_RESTRICTED, RELAY_GTURN, PROTO_TCP);
1152}
1153
1154// Symmetric NAT -> XXXX
1155TEST_F(PortTest, TestSymNatToLocal) {
1156 TestStunToLocal(NAT_SYMMETRIC);
1157}
1158
1159TEST_F(PortTest, TestSymNatToConeNat) {
1160 TestStunToStun(NAT_SYMMETRIC, NAT_OPEN_CONE);
1161}
1162
1163TEST_F(PortTest, TestSymNatToARNat) {
1164 TestStunToStun(NAT_SYMMETRIC, NAT_ADDR_RESTRICTED);
1165}
1166
1167TEST_F(PortTest, TestSymNatToPRNat) {
1168 // Will "fail"
1169 TestStunToStun(NAT_SYMMETRIC, NAT_PORT_RESTRICTED);
1170}
1171
1172TEST_F(PortTest, TestSymNatToSymNat) {
1173 // Will "fail"
1174 TestStunToStun(NAT_SYMMETRIC, NAT_SYMMETRIC);
1175}
1176
1177TEST_F(PortTest, TestSymNatToTurn) {
1178 TestStunToRelay(NAT_SYMMETRIC, RELAY_TURN, PROTO_UDP);
1179}
1180
1181TEST_F(PortTest, TestSymNatToGturn) {
1182 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_UDP);
1183}
1184
1185TEST_F(PortTest, TestSymNatToTcpGturn) {
1186 TestStunToRelay(NAT_SYMMETRIC, RELAY_GTURN, PROTO_TCP);
1187}
1188
1189// Outbound TCP -> XXXX
1190TEST_F(PortTest, TestTcpToTcp) {
1191 TestTcpToTcp();
1192}
1193
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07001194TEST_F(PortTest, TestTcpReconnectOnSendPacket) {
1195 TestTcpReconnect(false /* ping */, true /* send */);
1196}
1197
1198TEST_F(PortTest, TestTcpReconnectOnPing) {
1199 TestTcpReconnect(true /* ping */, false /* send */);
1200}
1201
1202TEST_F(PortTest, TestTcpReconnectTimeout) {
1203 TestTcpReconnect(false /* ping */, false /* send */);
1204}
1205
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001206// Test when TcpConnection never connects, the OnClose() will be called to
1207// destroy the connection.
1208TEST_F(PortTest, TestTcpNeverConnect) {
1209 Port* port1 = CreateTcpPort(kLocalAddr1);
1210 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1211 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
1212
1213 // Set up a channel and ensure the port will be deleted.
1214 TestChannel ch1(port1);
1215 EXPECT_EQ(0, ch1.complete_count());
1216
1217 ch1.Start();
1218 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1219
1220 rtc::scoped_ptr<rtc::AsyncSocket> server(
1221 vss()->CreateAsyncSocket(kLocalAddr2.family(), SOCK_STREAM));
1222 // Bind but not listen.
1223 EXPECT_EQ(0, server->Bind(kLocalAddr2));
1224
1225 Candidate c = GetCandidate(port1);
1226 c.set_address(server->GetLocalAddress());
1227
1228 ch1.CreateConnection(c);
1229 EXPECT_TRUE(ch1.conn());
1230 EXPECT_TRUE_WAIT(!ch1.conn(), kTimeout); // for TCP connect
1231}
1232
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233/* TODO: Enable these once testrelayserver can accept external TCP.
1234TEST_F(PortTest, TestTcpToTcpRelay) {
1235 TestTcpToRelay(PROTO_TCP);
1236}
1237
1238TEST_F(PortTest, TestTcpToSslTcpRelay) {
1239 TestTcpToRelay(PROTO_SSLTCP);
1240}
1241*/
1242
1243// Outbound SSLTCP -> XXXX
1244/* TODO: Enable these once testrelayserver can accept external SSL.
1245TEST_F(PortTest, TestSslTcpToTcpRelay) {
1246 TestSslTcpToRelay(PROTO_TCP);
1247}
1248
1249TEST_F(PortTest, TestSslTcpToSslTcpRelay) {
1250 TestSslTcpToRelay(PROTO_SSLTCP);
1251}
1252*/
1253
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001254// Test that a connection will be dead and deleted if
1255// i) it has never received anything for MIN_CONNECTION_LIFETIME milliseconds
1256// since it was created, or
1257// ii) it has not received anything for DEAD_CONNECTION_RECEIVE_TIMEOUT
1258// milliseconds since last receiving.
1259TEST_F(PortTest, TestConnectionDead) {
1260 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1261 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1262 TestChannel ch1(port1);
1263 TestChannel ch2(port2);
1264 // Acquire address.
1265 ch1.Start();
1266 ch2.Start();
1267 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
1268 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
1269
honghaiz37389b42016-01-04 21:57:33 -08001270 // Test case that the connection has never received anything.
honghaiz34b11eb2016-03-16 08:55:44 -07001271 int64_t before_created = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001272 ch1.CreateConnection(GetCandidate(port2));
honghaiz34b11eb2016-03-16 08:55:44 -07001273 int64_t after_created = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001274 Connection* conn = ch1.conn();
1275 ASSERT(conn != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001276 // It is not dead if it is after MIN_CONNECTION_LIFETIME but not pruned.
1277 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1278 rtc::Thread::Current()->ProcessMessages(0);
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001279 EXPECT_TRUE(ch1.conn() != nullptr);
honghaiz37389b42016-01-04 21:57:33 -08001280 // It is not dead if it is before MIN_CONNECTION_LIFETIME and pruned.
1281 conn->UpdateState(before_created + MIN_CONNECTION_LIFETIME - 1);
1282 conn->Prune();
1283 rtc::Thread::Current()->ProcessMessages(0);
1284 EXPECT_TRUE(ch1.conn() != nullptr);
1285 // It will be dead after MIN_CONNECTION_LIFETIME and pruned.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001286 conn->UpdateState(after_created + MIN_CONNECTION_LIFETIME + 1);
1287 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1288
honghaiz37389b42016-01-04 21:57:33 -08001289 // Test case that the connection has received something.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001290 // Create a connection again and receive a ping.
1291 ch1.CreateConnection(GetCandidate(port2));
1292 conn = ch1.conn();
1293 ASSERT(conn != nullptr);
honghaiz34b11eb2016-03-16 08:55:44 -07001294 int64_t before_last_receiving = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001295 conn->ReceivedPing();
honghaiz34b11eb2016-03-16 08:55:44 -07001296 int64_t after_last_receiving = rtc::Time64();
Honghai Zhang2cd7afe2015-11-12 11:14:33 -08001297 // The connection will be dead after DEAD_CONNECTION_RECEIVE_TIMEOUT
1298 conn->UpdateState(
1299 before_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT - 1);
1300 rtc::Thread::Current()->ProcessMessages(100);
1301 EXPECT_TRUE(ch1.conn() != nullptr);
1302 conn->UpdateState(after_last_receiving + DEAD_CONNECTION_RECEIVE_TIMEOUT + 1);
1303 EXPECT_TRUE_WAIT(ch1.conn() == nullptr, kTimeout);
1304}
1305
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306// This test case verifies standard ICE features in STUN messages. Currently it
1307// verifies Message Integrity attribute in STUN messages and username in STUN
1308// binding request will have colon (":") between remote and local username.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001309TEST_F(PortTest, TestLocalToLocalStandard) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
1311 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
1312 port1->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
1314 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
1315 port2->SetIceTiebreaker(kTiebreaker2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316 // Same parameters as TestLocalToLocal above.
1317 TestConnectivity("udp", port1, "udp", port2, true, true, true, true);
1318}
1319
1320// This test is trying to validate a successful and failure scenario in a
1321// loopback test when protocol is RFC5245. For success IceTiebreaker, username
1322// should remain equal to the request generated by the port and role of port
1323// must be in controlling.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001324TEST_F(PortTest, TestLoopbackCal) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325 rtc::scoped_ptr<TestPort> lport(
1326 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001327 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1328 lport->SetIceTiebreaker(kTiebreaker1);
1329 lport->PrepareAddress();
1330 ASSERT_FALSE(lport->Candidates().empty());
1331 Connection* conn = lport->CreateConnection(lport->Candidates()[0],
1332 Port::ORIGIN_MESSAGE);
1333 conn->Ping(0);
1334
1335 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1336 IceMessage* msg = lport->last_stun_msg();
1337 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
jbauchf1f87202016-03-30 06:43:37 -07001338 conn->OnReadPacket(lport->last_stun_buf()->data<char>(),
1339 lport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001340 rtc::PacketTime());
1341 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1342 msg = lport->last_stun_msg();
1343 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1344
1345 // If the tiebreaker value is different from port, we expect a error
1346 // response.
1347 lport->Reset();
1348 lport->AddCandidateAddress(kLocalAddr2);
Peter Thatcher04ac81f2015-09-21 11:48:28 -07001349 // Creating a different connection as |conn| is receiving.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350 Connection* conn1 = lport->CreateConnection(lport->Candidates()[1],
1351 Port::ORIGIN_MESSAGE);
1352 conn1->Ping(0);
1353
1354 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1355 msg = lport->last_stun_msg();
1356 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1357 rtc::scoped_ptr<IceMessage> modified_req(
1358 CreateStunMessage(STUN_BINDING_REQUEST));
1359 const StunByteStringAttribute* username_attr = msg->GetByteString(
1360 STUN_ATTR_USERNAME);
1361 modified_req->AddAttribute(new StunByteStringAttribute(
1362 STUN_ATTR_USERNAME, username_attr->GetString()));
1363 // To make sure we receive error response, adding tiebreaker less than
1364 // what's present in request.
1365 modified_req->AddAttribute(new StunUInt64Attribute(
1366 STUN_ATTR_ICE_CONTROLLING, kTiebreaker1 - 1));
1367 modified_req->AddMessageIntegrity("lpass");
1368 modified_req->AddFingerprint();
1369
1370 lport->Reset();
jbauchf1f87202016-03-30 06:43:37 -07001371 rtc::scoped_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372 WriteStunMessage(modified_req.get(), buf.get());
1373 conn1->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
1374 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1375 msg = lport->last_stun_msg();
1376 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1377}
1378
1379// This test verifies role conflict signal is received when there is
1380// conflict in the role. In this case both ports are in controlling and
1381// |rport| has higher tiebreaker value than |lport|. Since |lport| has lower
1382// value of tiebreaker, when it receives ping request from |rport| it will
1383// send role conflict signal.
1384TEST_F(PortTest, TestIceRoleConflict) {
1385 rtc::scoped_ptr<TestPort> lport(
1386 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001387 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1388 lport->SetIceTiebreaker(kTiebreaker1);
1389 rtc::scoped_ptr<TestPort> rport(
1390 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001391 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1392 rport->SetIceTiebreaker(kTiebreaker2);
1393
1394 lport->PrepareAddress();
1395 rport->PrepareAddress();
1396 ASSERT_FALSE(lport->Candidates().empty());
1397 ASSERT_FALSE(rport->Candidates().empty());
1398 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
1399 Port::ORIGIN_MESSAGE);
1400 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
1401 Port::ORIGIN_MESSAGE);
1402 rconn->Ping(0);
1403
1404 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1405 IceMessage* msg = rport->last_stun_msg();
1406 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1407 // Send rport binding request to lport.
jbauchf1f87202016-03-30 06:43:37 -07001408 lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
1409 rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001410 rtc::PacketTime());
1411
1412 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1413 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
1414 EXPECT_TRUE(role_conflict());
1415}
1416
1417TEST_F(PortTest, TestTcpNoDelay) {
1418 TCPPort* port1 = CreateTcpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001419 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001420 int option_value = -1;
1421 int success = port1->GetOption(rtc::Socket::OPT_NODELAY,
1422 &option_value);
1423 ASSERT_EQ(0, success); // GetOption() should complete successfully w/ 0
1424 ASSERT_EQ(1, option_value);
1425 delete port1;
1426}
1427
1428TEST_F(PortTest, TestDelayedBindingUdp) {
1429 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1430 FakePacketSocketFactory socket_factory;
1431
1432 socket_factory.set_next_udp_socket(socket);
1433 scoped_ptr<UDPPort> port(
1434 CreateUdpPort(kLocalAddr1, &socket_factory));
1435
1436 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1437 port->PrepareAddress();
1438
1439 EXPECT_EQ(0U, port->Candidates().size());
1440 socket->SignalAddressReady(socket, kLocalAddr2);
1441
1442 EXPECT_EQ(1U, port->Candidates().size());
1443}
1444
1445TEST_F(PortTest, TestDelayedBindingTcp) {
1446 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1447 FakePacketSocketFactory socket_factory;
1448
1449 socket_factory.set_next_server_tcp_socket(socket);
1450 scoped_ptr<TCPPort> port(
1451 CreateTcpPort(kLocalAddr1, &socket_factory));
1452
1453 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1454 port->PrepareAddress();
1455
1456 EXPECT_EQ(0U, port->Candidates().size());
1457 socket->SignalAddressReady(socket, kLocalAddr2);
1458
1459 EXPECT_EQ(1U, port->Candidates().size());
1460}
1461
1462void PortTest::TestCrossFamilyPorts(int type) {
1463 FakePacketSocketFactory factory;
1464 scoped_ptr<Port> ports[4];
1465 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1466 SocketAddress("192.168.1.4", 0),
1467 SocketAddress("2001:db8::1", 0),
1468 SocketAddress("2001:db8::2", 0)};
1469 for (int i = 0; i < 4; i++) {
1470 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1471 if (type == SOCK_DGRAM) {
1472 factory.set_next_udp_socket(socket);
1473 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1474 } else if (type == SOCK_STREAM) {
1475 factory.set_next_server_tcp_socket(socket);
1476 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1477 }
1478 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1479 socket->SignalAddressReady(socket, addresses[i]);
1480 ports[i]->PrepareAddress();
1481 }
1482
1483 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1484 if (type == SOCK_STREAM) {
1485 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1486 factory.set_next_client_tcp_socket(clientsocket);
1487 }
1488 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1489 Port::ORIGIN_MESSAGE);
1490 EXPECT_TRUE(NULL == c);
1491 EXPECT_EQ(0U, ports[0]->connections().size());
1492 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1493 Port::ORIGIN_MESSAGE);
1494 EXPECT_FALSE(NULL == c);
1495 EXPECT_EQ(1U, ports[0]->connections().size());
1496
1497 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1498 if (type == SOCK_STREAM) {
1499 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1500 factory.set_next_client_tcp_socket(clientsocket);
1501 }
1502 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1503 Port::ORIGIN_MESSAGE);
1504 EXPECT_TRUE(NULL == c);
1505 EXPECT_EQ(0U, ports[2]->connections().size());
1506 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1507 Port::ORIGIN_MESSAGE);
1508 EXPECT_FALSE(NULL == c);
1509 EXPECT_EQ(1U, ports[2]->connections().size());
1510}
1511
1512TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1513 TestCrossFamilyPorts(SOCK_STREAM);
1514}
1515
1516TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1517 TestCrossFamilyPorts(SOCK_DGRAM);
1518}
1519
Peter Thatcherb8b01432015-07-07 16:45:53 -07001520void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1521 Connection* c = p1->CreateConnection(GetCandidate(p2),
1522 Port::ORIGIN_MESSAGE);
1523 if (can_connect) {
1524 EXPECT_FALSE(NULL == c);
1525 EXPECT_EQ(1U, p1->connections().size());
1526 } else {
1527 EXPECT_TRUE(NULL == c);
1528 EXPECT_EQ(0U, p1->connections().size());
1529 }
1530}
1531
1532TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1533 FakePacketSocketFactory factory;
1534 scoped_ptr<Port> ports[4];
1535 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1536 SocketAddress("fe80::1", 0),
1537 SocketAddress("fe80::2", 0),
1538 SocketAddress("::1", 0)};
1539 for (int i = 0; i < 4; i++) {
1540 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1541 factory.set_next_udp_socket(socket);
1542 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1543 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1544 socket->SignalAddressReady(socket, addresses[i]);
1545 ports[i]->PrepareAddress();
1546 }
1547
1548 Port* standard = ports[0].get();
1549 Port* link_local1 = ports[1].get();
1550 Port* link_local2 = ports[2].get();
1551 Port* localhost = ports[3].get();
1552
1553 ExpectPortsCanConnect(false, link_local1, standard);
1554 ExpectPortsCanConnect(false, standard, link_local1);
1555 ExpectPortsCanConnect(false, link_local1, localhost);
1556 ExpectPortsCanConnect(false, localhost, link_local1);
1557
1558 ExpectPortsCanConnect(true, link_local1, link_local2);
1559 ExpectPortsCanConnect(true, localhost, standard);
1560 ExpectPortsCanConnect(true, standard, localhost);
1561}
1562
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001563// This test verifies DSCP value set through SetOption interface can be
1564// get through DefaultDscpValue.
1565TEST_F(PortTest, TestDefaultDscpValue) {
1566 int dscp;
1567 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
1568 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1569 rtc::DSCP_CS6));
1570 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1571 rtc::scoped_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
1572 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1573 rtc::DSCP_AF31));
1574 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1575 EXPECT_EQ(rtc::DSCP_AF31, dscp);
1576 rtc::scoped_ptr<StunPort> stunport(
1577 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1578 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1579 rtc::DSCP_AF41));
1580 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1581 EXPECT_EQ(rtc::DSCP_AF41, dscp);
1582 rtc::scoped_ptr<TurnPort> turnport1(CreateTurnPort(
1583 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1584 // Socket is created in PrepareAddress.
1585 turnport1->PrepareAddress();
1586 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1587 rtc::DSCP_CS7));
1588 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1589 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1590 // This will verify correct value returned without the socket.
1591 rtc::scoped_ptr<TurnPort> turnport2(CreateTurnPort(
1592 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
1593 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1594 rtc::DSCP_CS6));
1595 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1596 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1597}
1598
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001599// Test sending STUN messages.
1600TEST_F(PortTest, TestSendStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001601 rtc::scoped_ptr<TestPort> lport(
1602 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1603 rtc::scoped_ptr<TestPort> rport(
1604 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001605 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1606 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001607 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1608 rport->SetIceTiebreaker(kTiebreaker2);
1609
1610 // Send a fake ping from lport to rport.
1611 lport->PrepareAddress();
1612 rport->PrepareAddress();
1613 ASSERT_FALSE(rport->Candidates().empty());
1614 Connection* lconn = lport->CreateConnection(
1615 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1616 Connection* rconn = rport->CreateConnection(
1617 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1618 lconn->Ping(0);
1619
1620 // Check that it's a proper BINDING-REQUEST.
1621 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1622 IceMessage* msg = lport->last_stun_msg();
1623 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1624 EXPECT_FALSE(msg->IsLegacy());
1625 const StunByteStringAttribute* username_attr =
1626 msg->GetByteString(STUN_ATTR_USERNAME);
1627 ASSERT_TRUE(username_attr != NULL);
1628 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1629 ASSERT_TRUE(priority_attr != NULL);
1630 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1631 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1632 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1633 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
jbauchf1f87202016-03-30 06:43:37 -07001634 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001635 "rpass"));
1636 const StunUInt64Attribute* ice_controlling_attr =
1637 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1638 ASSERT_TRUE(ice_controlling_attr != NULL);
1639 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1640 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1641 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1642 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1643 EXPECT_TRUE(StunMessage::ValidateFingerprint(
jbauchf1f87202016-03-30 06:43:37 -07001644 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001645
1646 // Request should not include ping count.
1647 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1648
1649 // Save a copy of the BINDING-REQUEST for use below.
1650 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
1651
1652 // Respond with a BINDING-RESPONSE.
1653 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1654 msg = rport->last_stun_msg();
1655 ASSERT_TRUE(msg != NULL);
1656 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1657
1658
1659 EXPECT_FALSE(msg->IsLegacy());
1660 const StunAddressAttribute* addr_attr = msg->GetAddress(
1661 STUN_ATTR_XOR_MAPPED_ADDRESS);
1662 ASSERT_TRUE(addr_attr != NULL);
1663 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1664 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1665 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
jbauchf1f87202016-03-30 06:43:37 -07001666 rport->last_stun_buf()->data<char>(), rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001667 "rpass"));
1668 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1669 EXPECT_TRUE(StunMessage::ValidateFingerprint(
jbauchf1f87202016-03-30 06:43:37 -07001670 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001671 // No USERNAME or PRIORITY in ICE responses.
1672 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1673 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1674 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1675 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1676 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1677 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1678
1679 // Response should not include ping count.
1680 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1681
1682 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1683 // but we can do it here.
1684 rport->SendBindingErrorResponse(request.get(),
1685 lport->Candidates()[0].address(),
1686 STUN_ERROR_SERVER_ERROR,
1687 STUN_ERROR_REASON_SERVER_ERROR);
1688 msg = rport->last_stun_msg();
1689 ASSERT_TRUE(msg != NULL);
1690 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1691 EXPECT_FALSE(msg->IsLegacy());
1692 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1693 ASSERT_TRUE(error_attr != NULL);
1694 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1695 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1696 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1697 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
jbauchf1f87202016-03-30 06:43:37 -07001698 rport->last_stun_buf()->data<char>(), rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001699 "rpass"));
1700 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1701 EXPECT_TRUE(StunMessage::ValidateFingerprint(
jbauchf1f87202016-03-30 06:43:37 -07001702 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001703 // No USERNAME with ICE.
1704 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1705 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1706
1707 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1708 // and (incremented) RETRANSMIT_COUNT attributes.
1709 rport->Reset();
1710 rport->set_send_retransmit_count_attribute(true);
1711 rconn->Ping(0);
1712 rconn->Ping(0);
1713 rconn->Ping(0);
1714 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1715 msg = rport->last_stun_msg();
1716 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1717 const StunUInt64Attribute* ice_controlled_attr =
1718 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1719 ASSERT_TRUE(ice_controlled_attr != NULL);
1720 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1721 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1722
1723 // Request should include ping count.
1724 const StunUInt32Attribute* retransmit_attr =
1725 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1726 ASSERT_TRUE(retransmit_attr != NULL);
1727 EXPECT_EQ(2U, retransmit_attr->value());
1728
1729 // Respond with a BINDING-RESPONSE.
1730 request.reset(CopyStunMessage(msg));
1731 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1732 msg = lport->last_stun_msg();
1733
1734 // Response should include same ping count.
1735 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1736 ASSERT_TRUE(retransmit_attr != NULL);
1737 EXPECT_EQ(2U, retransmit_attr->value());
1738}
1739
1740TEST_F(PortTest, TestUseCandidateAttribute) {
1741 rtc::scoped_ptr<TestPort> lport(
1742 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1743 rtc::scoped_ptr<TestPort> rport(
1744 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001745 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1746 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001747 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1748 rport->SetIceTiebreaker(kTiebreaker2);
1749
1750 // Send a fake ping from lport to rport.
1751 lport->PrepareAddress();
1752 rport->PrepareAddress();
1753 ASSERT_FALSE(rport->Candidates().empty());
1754 Connection* lconn = lport->CreateConnection(
1755 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1756 lconn->Ping(0);
1757 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1758 IceMessage* msg = lport->last_stun_msg();
1759 const StunUInt64Attribute* ice_controlling_attr =
1760 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1761 ASSERT_TRUE(ice_controlling_attr != NULL);
1762 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1763 STUN_ATTR_USE_CANDIDATE);
1764 ASSERT_TRUE(use_candidate_attr != NULL);
1765}
1766
honghaiza0c44ea2016-03-23 16:07:48 -07001767TEST_F(PortTest, TestNetworkInfoAttribute) {
1768 rtc::scoped_ptr<TestPort> lport(
1769 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1770 // Set the network type for rport to be cellular so its cost will be 999.
1771 SetNetworkType(rtc::ADAPTER_TYPE_CELLULAR);
1772 rtc::scoped_ptr<TestPort> rport(
1773 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1774 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1775 lport->SetIceTiebreaker(kTiebreaker1);
1776 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1777 rport->SetIceTiebreaker(kTiebreaker2);
1778
1779 uint16_t lnetwork_id = 9;
1780 lport->Network()->set_id(lnetwork_id);
1781 // Send a fake ping from lport to rport.
1782 lport->PrepareAddress();
1783 rport->PrepareAddress();
1784 Connection* lconn =
1785 lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1786 lconn->Ping(0);
1787 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1788 IceMessage* msg = lport->last_stun_msg();
1789 const StunUInt32Attribute* network_info_attr =
1790 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1791 ASSERT_TRUE(network_info_attr != NULL);
1792 uint32_t network_info = network_info_attr->value();
1793 EXPECT_EQ(lnetwork_id, network_info >> 16);
1794 // Default network cost is 0.
1795 EXPECT_EQ(0U, network_info & 0xFFFF);
1796
1797 // Send a fake ping from rport to lport.
1798 uint16_t rnetwork_id = 8;
1799 rport->Network()->set_id(rnetwork_id);
1800 Connection* rconn =
1801 rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1802 rconn->Ping(0);
1803 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1804 msg = rport->last_stun_msg();
1805 network_info_attr = msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1806 ASSERT_TRUE(network_info_attr != NULL);
1807 network_info = network_info_attr->value();
1808 EXPECT_EQ(rnetwork_id, network_info >> 16);
1809 EXPECT_EQ(cricket::kMaxNetworkCost, network_info & 0xFFFF);
1810}
1811
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001812// Test handling STUN messages.
1813TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001814 // Our port will act as the "remote" port.
1815 rtc::scoped_ptr<TestPort> port(
1816 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001817
1818 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
jbauchf1f87202016-03-30 06:43:37 -07001819 rtc::scoped_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001820 rtc::SocketAddress addr(kLocalAddr1);
1821 std::string username;
1822
1823 // BINDING-REQUEST from local to remote with valid ICE username,
1824 // MESSAGE-INTEGRITY, and FINGERPRINT.
1825 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1826 "rfrag:lfrag"));
1827 in_msg->AddMessageIntegrity("rpass");
1828 in_msg->AddFingerprint();
1829 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001830 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1831 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001832 EXPECT_TRUE(out_msg.get() != NULL);
1833 EXPECT_EQ("lfrag", username);
1834
1835 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1836 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1837 in_msg->AddAttribute(
1838 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1839 in_msg->AddMessageIntegrity("rpass");
1840 in_msg->AddFingerprint();
1841 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001842 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1843 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001844 EXPECT_TRUE(out_msg.get() != NULL);
1845 EXPECT_EQ("", username);
1846
1847 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1848 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1849 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1850 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1851 in_msg->AddFingerprint();
1852 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001853 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1854 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001855 EXPECT_TRUE(out_msg.get() != NULL);
1856 EXPECT_EQ("", username);
1857 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1858 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1859 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1860 out_msg->GetErrorCode()->reason());
1861}
1862
guoweisd12140a2015-09-10 13:32:11 -07001863// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001864TEST_F(PortTest, TestHandleStunMessageBadUsername) {
guoweisd12140a2015-09-10 13:32:11 -07001865 rtc::scoped_ptr<TestPort> port(
1866 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001867
1868 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
jbauchf1f87202016-03-30 06:43:37 -07001869 rtc::scoped_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001870 rtc::SocketAddress addr(kLocalAddr1);
1871 std::string username;
1872
1873 // BINDING-REQUEST with no username.
1874 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1875 in_msg->AddMessageIntegrity("rpass");
1876 in_msg->AddFingerprint();
1877 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001878 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1879 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001880 EXPECT_TRUE(out_msg.get() == NULL);
1881 EXPECT_EQ("", username);
1882 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1883
1884 // BINDING-REQUEST with empty username.
1885 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1886 in_msg->AddMessageIntegrity("rpass");
1887 in_msg->AddFingerprint();
1888 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001889 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1890 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001891 EXPECT_TRUE(out_msg.get() == NULL);
1892 EXPECT_EQ("", username);
1893 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1894
1895 // BINDING-REQUEST with too-short username.
1896 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1897 in_msg->AddMessageIntegrity("rpass");
1898 in_msg->AddFingerprint();
1899 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001900 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1901 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001902 EXPECT_TRUE(out_msg.get() == NULL);
1903 EXPECT_EQ("", username);
1904 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1905
1906 // BINDING-REQUEST with reversed username.
1907 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1908 "lfrag:rfrag"));
1909 in_msg->AddMessageIntegrity("rpass");
1910 in_msg->AddFingerprint();
1911 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001912 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1913 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001914 EXPECT_TRUE(out_msg.get() == NULL);
1915 EXPECT_EQ("", username);
1916 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1917
1918 // BINDING-REQUEST with garbage username.
1919 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1920 "abcd:efgh"));
1921 in_msg->AddMessageIntegrity("rpass");
1922 in_msg->AddFingerprint();
1923 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001924 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1925 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001926 EXPECT_TRUE(out_msg.get() == NULL);
1927 EXPECT_EQ("", username);
1928 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1929}
1930
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001931// Test handling STUN messages with missing or malformed M-I.
1932TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001933 // Our port will act as the "remote" port.
1934 rtc::scoped_ptr<TestPort> port(
1935 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001936
1937 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
jbauchf1f87202016-03-30 06:43:37 -07001938 rtc::scoped_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001939 rtc::SocketAddress addr(kLocalAddr1);
1940 std::string username;
1941
1942 // BINDING-REQUEST from local to remote with valid ICE username and
1943 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1944 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1945 "rfrag:lfrag"));
1946 in_msg->AddFingerprint();
1947 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001948 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1949 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001950 EXPECT_TRUE(out_msg.get() == NULL);
1951 EXPECT_EQ("", username);
1952 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1953
1954 // BINDING-REQUEST from local to remote with valid ICE username and
1955 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1956 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1957 "rfrag:lfrag"));
1958 in_msg->AddMessageIntegrity("invalid");
1959 in_msg->AddFingerprint();
1960 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001961 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1962 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001963 EXPECT_TRUE(out_msg.get() == NULL);
1964 EXPECT_EQ("", username);
1965 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1966
1967 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1968 // by the Connection, not the Port, since they require the remote username.
1969 // Change this test to pass in data via Connection::OnReadPacket instead.
1970}
1971
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001972// Test handling STUN messages with missing or malformed FINGERPRINT.
1973TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001974 // Our port will act as the "remote" port.
1975 rtc::scoped_ptr<TestPort> port(
1976 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001977
1978 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
jbauchf1f87202016-03-30 06:43:37 -07001979 rtc::scoped_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001980 rtc::SocketAddress addr(kLocalAddr1);
1981 std::string username;
1982
1983 // BINDING-REQUEST from local to remote with valid ICE username and
1984 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1985 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1986 "rfrag:lfrag"));
1987 in_msg->AddMessageIntegrity("rpass");
1988 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001989 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1990 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001991 EXPECT_EQ(0, port->last_stun_error_code());
1992
1993 // Now, add a fingerprint, but munge the message so it's not valid.
1994 in_msg->AddFingerprint();
1995 in_msg->SetTransactionID("TESTTESTBADD");
1996 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001997 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1998 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001999 EXPECT_EQ(0, port->last_stun_error_code());
2000
2001 // Valid BINDING-RESPONSE, except no FINGERPRINT.
2002 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
2003 in_msg->AddAttribute(
2004 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
2005 in_msg->AddMessageIntegrity("rpass");
2006 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002007 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2008 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002009 EXPECT_EQ(0, port->last_stun_error_code());
2010
2011 // Now, add a fingerprint, but munge the message so it's not valid.
2012 in_msg->AddFingerprint();
2013 in_msg->SetTransactionID("TESTTESTBADD");
2014 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002015 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2016 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002017 EXPECT_EQ(0, port->last_stun_error_code());
2018
2019 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
2020 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
2021 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
2022 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
2023 in_msg->AddMessageIntegrity("rpass");
2024 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002025 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2026 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002027 EXPECT_EQ(0, port->last_stun_error_code());
2028
2029 // Now, add a fingerprint, but munge the message so it's not valid.
2030 in_msg->AddFingerprint();
2031 in_msg->SetTransactionID("TESTTESTBADD");
2032 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002033 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2034 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002035 EXPECT_EQ(0, port->last_stun_error_code());
2036}
2037
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002038// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002039// indications are allowed only to the connection which is in read mode.
2040TEST_F(PortTest, TestHandleStunBindingIndication) {
2041 rtc::scoped_ptr<TestPort> lport(
2042 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002043 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2044 lport->SetIceTiebreaker(kTiebreaker1);
2045
2046 // Verifying encoding and decoding STUN indication message.
2047 rtc::scoped_ptr<IceMessage> in_msg, out_msg;
jbauchf1f87202016-03-30 06:43:37 -07002048 rtc::scoped_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002049 rtc::SocketAddress addr(kLocalAddr1);
2050 std::string username;
2051
2052 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
2053 in_msg->AddFingerprint();
2054 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002055 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2056 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002057 EXPECT_TRUE(out_msg.get() != NULL);
2058 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2059 EXPECT_EQ("", username);
2060
2061 // Verify connection can handle STUN indication and updates
2062 // last_ping_received.
2063 rtc::scoped_ptr<TestPort> rport(
2064 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002065 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2066 rport->SetIceTiebreaker(kTiebreaker2);
2067
2068 lport->PrepareAddress();
2069 rport->PrepareAddress();
2070 ASSERT_FALSE(lport->Candidates().empty());
2071 ASSERT_FALSE(rport->Candidates().empty());
2072
2073 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2074 Port::ORIGIN_MESSAGE);
2075 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2076 Port::ORIGIN_MESSAGE);
2077 rconn->Ping(0);
2078
2079 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2080 IceMessage* msg = rport->last_stun_msg();
2081 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2082 // Send rport binding request to lport.
jbauchf1f87202016-03-30 06:43:37 -07002083 lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
2084 rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002085 rtc::PacketTime());
2086 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2087 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
honghaiz34b11eb2016-03-16 08:55:44 -07002088 int64_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002089
2090 // Adding a delay of 100ms.
2091 rtc::Thread::Current()->ProcessMessages(100);
2092 // Pinging lconn using stun indication message.
2093 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
honghaiz34b11eb2016-03-16 08:55:44 -07002094 int64_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002095 EXPECT_GT(last_ping_received2, last_ping_received1);
2096}
2097
2098TEST_F(PortTest, TestComputeCandidatePriority) {
2099 rtc::scoped_ptr<TestPort> port(
2100 CreateTestPort(kLocalAddr1, "name", "pass"));
2101 port->set_type_preference(90);
2102 port->set_component(177);
2103 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2104 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2105 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2106 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2107 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2108 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2109 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2110 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2111 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2112 // These should all be:
2113 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002114 uint32_t expected_priority_v4 = 1509957199U;
2115 uint32_t expected_priority_v6 = 1509959759U;
2116 uint32_t expected_priority_ula = 1509962319U;
2117 uint32_t expected_priority_v4mapped = expected_priority_v4;
2118 uint32_t expected_priority_v4compat = 1509949775U;
2119 uint32_t expected_priority_6to4 = 1509954639U;
2120 uint32_t expected_priority_teredo = 1509952079U;
2121 uint32_t expected_priority_sitelocal = 1509949775U;
2122 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002123 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2124 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2125 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2126 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2127 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2128 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2129 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2130 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2131 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2132}
2133
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002134// In the case of shared socket, one port may be shared by local and stun.
2135// Test that candidates with different types will have different foundation.
2136TEST_F(PortTest, TestFoundation) {
2137 rtc::scoped_ptr<TestPort> testport(
2138 CreateTestPort(kLocalAddr1, "name", "pass"));
2139 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2140 LOCAL_PORT_TYPE,
2141 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2142 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2143 STUN_PORT_TYPE,
2144 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2145 EXPECT_NE(testport->Candidates()[0].foundation(),
2146 testport->Candidates()[1].foundation());
2147}
2148
2149// This test verifies the foundation of different types of ICE candidates.
2150TEST_F(PortTest, TestCandidateFoundation) {
2151 rtc::scoped_ptr<rtc::NATServer> nat_server(
2152 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2153 rtc::scoped_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
2154 udpport1->PrepareAddress();
2155 rtc::scoped_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
2156 udpport2->PrepareAddress();
2157 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2158 udpport2->Candidates()[0].foundation());
2159 rtc::scoped_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
2160 tcpport1->PrepareAddress();
2161 rtc::scoped_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
2162 tcpport2->PrepareAddress();
2163 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2164 tcpport2->Candidates()[0].foundation());
2165 rtc::scoped_ptr<Port> stunport(
2166 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2167 stunport->PrepareAddress();
2168 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2169 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2170 stunport->Candidates()[0].foundation());
2171 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2172 stunport->Candidates()[0].foundation());
2173 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2174 stunport->Candidates()[0].foundation());
2175 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2176 stunport->Candidates()[0].foundation());
2177 // Verify GTURN candidate foundation.
2178 rtc::scoped_ptr<RelayPort> relayport(
2179 CreateGturnPort(kLocalAddr1));
2180 relayport->AddServerAddress(
2181 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2182 relayport->PrepareAddress();
2183 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2184 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2185 relayport->Candidates()[0].foundation());
2186 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2187 relayport->Candidates()[0].foundation());
2188 // Verifying TURN candidate foundation.
2189 rtc::scoped_ptr<Port> turnport1(CreateTurnPort(
2190 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2191 turnport1->PrepareAddress();
2192 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2193 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2194 turnport1->Candidates()[0].foundation());
2195 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2196 turnport1->Candidates()[0].foundation());
2197 EXPECT_NE(stunport->Candidates()[0].foundation(),
2198 turnport1->Candidates()[0].foundation());
2199 rtc::scoped_ptr<Port> turnport2(CreateTurnPort(
2200 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2201 turnport2->PrepareAddress();
2202 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2203 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2204 turnport2->Candidates()[0].foundation());
2205
2206 // Running a second turn server, to get different base IP address.
2207 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2208 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2209 TestTurnServer turn_server2(
2210 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
2211 rtc::scoped_ptr<Port> turnport3(CreateTurnPort(
2212 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2213 kTurnUdpIntAddr2));
2214 turnport3->PrepareAddress();
2215 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2216 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2217 turnport2->Candidates()[0].foundation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08002218
2219 // Start a TCP turn server, and check that two turn candidates have
2220 // different foundations if their relay protocols are different.
2221 TestTurnServer turn_server3(rtc::Thread::Current(), kTurnTcpIntAddr,
2222 kTurnUdpExtAddr, PROTO_TCP);
2223 rtc::scoped_ptr<Port> turnport4(
2224 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_TCP, PROTO_UDP));
2225 turnport4->PrepareAddress();
2226 ASSERT_EQ_WAIT(1U, turnport4->Candidates().size(), kTimeout);
2227 EXPECT_NE(turnport2->Candidates()[0].foundation(),
2228 turnport4->Candidates()[0].foundation());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002229}
2230
2231// This test verifies the related addresses of different types of
2232// ICE candiates.
2233TEST_F(PortTest, TestCandidateRelatedAddress) {
2234 rtc::scoped_ptr<rtc::NATServer> nat_server(
2235 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
2236 rtc::scoped_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
2237 udpport->PrepareAddress();
2238 // For UDPPort, related address will be empty.
2239 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2240 // Testing related address for stun candidates.
2241 // For stun candidate related address must be equal to the base
2242 // socket address.
2243 rtc::scoped_ptr<StunPort> stunport(
2244 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2245 stunport->PrepareAddress();
2246 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2247 // Check STUN candidate address.
2248 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2249 kNatAddr1.ipaddr());
2250 // Check STUN candidate related address.
2251 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2252 stunport->GetLocalAddress());
2253 // Verifying the related address for the GTURN candidates.
2254 // NOTE: In case of GTURN related address will be equal to the mapped
2255 // address, but address(mapped) will not be XOR.
2256 rtc::scoped_ptr<RelayPort> relayport(
2257 CreateGturnPort(kLocalAddr1));
2258 relayport->AddServerAddress(
2259 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2260 relayport->PrepareAddress();
2261 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2262 // For Gturn related address is set to "0.0.0.0:0"
2263 EXPECT_EQ(rtc::SocketAddress(),
2264 relayport->Candidates()[0].related_address());
2265 // Verifying the related address for TURN candidate.
2266 // For TURN related address must be equal to the mapped address.
2267 rtc::scoped_ptr<Port> turnport(CreateTurnPort(
2268 kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2269 turnport->PrepareAddress();
2270 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2271 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2272 turnport->Candidates()[0].address().ipaddr());
2273 EXPECT_EQ(kNatAddr1.ipaddr(),
2274 turnport->Candidates()[0].related_address().ipaddr());
2275}
2276
2277// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002278TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002279 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002280 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002281 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002282 cand2.set_priority(1);
2283 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002284}
2285
2286// Test the Connection priority is calculated correctly.
2287TEST_F(PortTest, TestConnectionPriority) {
2288 rtc::scoped_ptr<TestPort> lport(
2289 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2290 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
2291 rtc::scoped_ptr<TestPort> rport(
2292 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2293 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2294 lport->set_component(123);
2295 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2296 rport->set_component(23);
2297 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2298
2299 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2300 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2301
2302 // RFC 5245
2303 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2304 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2305 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2306 Connection* lconn = lport->CreateConnection(
2307 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2308#if defined(WEBRTC_WIN)
2309 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2310#else
2311 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2312#endif
2313
2314 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2315 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2316 Connection* rconn = rport->CreateConnection(
2317 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2318#if defined(WEBRTC_WIN)
2319 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2320#else
2321 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2322#endif
2323}
2324
2325TEST_F(PortTest, TestWritableState) {
2326 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002327 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002328 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002329 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002330
2331 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002332 TestChannel ch1(port1);
2333 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002334
2335 // Acquire addresses.
2336 ch1.Start();
2337 ch2.Start();
2338 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2339 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2340
2341 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002342 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002343 ASSERT_TRUE(ch1.conn() != NULL);
2344 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2345 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2346 ch1.Ping();
2347 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2348
2349 // Data should be unsendable until the connection is accepted.
2350 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002351 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002352 rtc::PacketOptions options;
2353 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2354
2355 // Accept the connection to return the binding response, transition to
2356 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002357 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002358 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2359 kTimeout);
2360 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2361
2362 // Ask the connection to update state as if enough time has passed to lose
2363 // full writability and 5 pings went unresponded to. We'll accomplish the
2364 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002365 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002366 ch1.Ping(i);
2367 }
honghaiz34b11eb2016-03-16 08:55:44 -07002368 int unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002369 ch1.conn()->UpdateState(unreliable_timeout_delay);
2370 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2371
2372 // Data should be able to be sent in this state.
2373 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2374
2375 // And now allow the other side to process the pings and send binding
2376 // responses.
2377 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2378 kTimeout);
2379
2380 // Wait long enough for a full timeout (past however long we've already
2381 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002382 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002383 ch1.Ping(unreliable_timeout_delay + i);
2384 }
2385 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2386 500u);
2387 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2388
2389 // Now that the connection has completely timed out, data send should fail.
2390 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2391
2392 ch1.Stop();
2393 ch2.Stop();
2394}
2395
2396TEST_F(PortTest, TestTimeoutForNeverWritable) {
2397 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002398 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002399 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002400 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002401
2402 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002403 TestChannel ch1(port1);
2404 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002405
2406 // Acquire addresses.
2407 ch1.Start();
2408 ch2.Start();
2409
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002410 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002411 ASSERT_TRUE(ch1.conn() != NULL);
2412 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2413
2414 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002415 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002416 ch1.Ping(i);
2417 }
2418 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2419 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2420}
2421
2422// This test verifies the connection setup between ICEMODE_FULL
2423// and ICEMODE_LITE.
2424// In this test |ch1| behaves like FULL mode client and we have created
2425// port which responds to the ping message just like LITE client.
2426TEST_F(PortTest, TestIceLiteConnectivity) {
2427 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002428 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002429 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2430
2431 rtc::scoped_ptr<TestPort> ice_lite_port(CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002432 kLocalAddr2, "rfrag", "rpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002433 cricket::ICEROLE_CONTROLLED, kTiebreaker2));
2434 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002435 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002436 ch1.SetIceMode(ICEMODE_FULL);
2437
2438 // Start gathering candidates.
2439 ch1.Start();
2440 ice_lite_port->PrepareAddress();
2441
2442 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2443 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2444
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002445 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002446 ASSERT_TRUE(ch1.conn() != NULL);
2447 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2448
2449 // Send ping from full mode client.
2450 // This ping must not have USE_CANDIDATE_ATTR.
2451 ch1.Ping();
2452
2453 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2454 // from port.
2455 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2456 IceMessage* msg = ice_full_port->last_stun_msg();
2457 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2458
2459 // Respond with a BINDING-RESPONSE from litemode client.
2460 // NOTE: Ideally we should't create connection at this stage from lite
2461 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2462 // But we need a connection to send a response message.
2463 ice_lite_port->CreateConnection(
2464 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
2465 rtc::scoped_ptr<IceMessage> request(CopyStunMessage(msg));
2466 ice_lite_port->SendBindingResponse(
2467 request.get(), ice_full_port->Candidates()[0].address());
2468
2469 // Feeding the respone message from litemode to the full mode connection.
jbauchf1f87202016-03-30 06:43:37 -07002470 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->data<char>(),
2471 ice_lite_port->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002472 rtc::PacketTime());
2473 // Verifying full mode connection becomes writable from the response.
2474 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2475 kTimeout);
2476 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2477
2478 // Clear existing stun messsages. Otherwise we will process old stun
2479 // message right after we send ping.
2480 ice_full_port->Reset();
2481 // Send ping. This must have USE_CANDIDATE_ATTR.
2482 ch1.Ping();
2483 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2484 msg = ice_full_port->last_stun_msg();
2485 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2486 ch1.Stop();
2487}
2488
2489// This test case verifies that the CONTROLLING port does not time out.
2490TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002491 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2492 ConnectToSignalDestroyed(port1);
2493 port1->set_timeout_delay(10); // milliseconds
2494 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2495 port1->SetIceTiebreaker(kTiebreaker1);
2496
2497 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2498 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2499 port2->SetIceTiebreaker(kTiebreaker2);
2500
2501 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002502 TestChannel ch1(port1);
2503 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002504
2505 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002506 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002507
2508 // After the connection is destroyed, the port should not be destroyed.
2509 rtc::Thread::Current()->ProcessMessages(kTimeout);
2510 EXPECT_FALSE(destroyed());
2511}
2512
2513// This test case verifies that the CONTROLLED port does time out, but only
2514// after connectivity is lost.
2515TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002516 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2517 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2518 port1->SetIceTiebreaker(kTiebreaker1);
2519
2520 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2521 ConnectToSignalDestroyed(port2);
2522 port2->set_timeout_delay(10); // milliseconds
2523 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2524 port2->SetIceTiebreaker(kTiebreaker2);
2525
2526 // The connection must not be destroyed before a connection is attempted.
2527 EXPECT_FALSE(destroyed());
2528
2529 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2530 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2531
2532 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002533 TestChannel ch1(port1);
2534 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002535
2536 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002537 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002538
2539 // The controlled port should be destroyed after 10 milliseconds.
2540 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2541}
honghaizd0b31432015-09-30 12:42:17 -07002542
2543// This test case verifies that if the role of a port changes from controlled
2544// to controlling after all connections fail, the port will not be destroyed.
2545TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2546 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2547 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2548 port1->SetIceTiebreaker(kTiebreaker1);
2549
2550 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2551 ConnectToSignalDestroyed(port2);
2552 port2->set_timeout_delay(10); // milliseconds
2553 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2554 port2->SetIceTiebreaker(kTiebreaker2);
2555
2556 // The connection must not be destroyed before a connection is attempted.
2557 EXPECT_FALSE(destroyed());
2558
2559 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2560 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2561
2562 // Set up channels and ensure both ports will be deleted.
2563 TestChannel ch1(port1);
2564 TestChannel ch2(port2);
2565
2566 // Simulate a connection that succeeds, and then is destroyed.
2567 StartConnectAndStopChannels(&ch1, &ch2);
2568 // Switch the role after all connections are destroyed.
2569 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2570 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2571 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2572
2573 // After the connection is destroyed, the port should not be destroyed.
2574 rtc::Thread::Current()->ProcessMessages(kTimeout);
2575 EXPECT_FALSE(destroyed());
2576}
Honghai Zhangf9945b22015-12-15 12:20:13 -08002577
2578TEST_F(PortTest, TestSupportsProtocol) {
2579 rtc::scoped_ptr<Port> udp_port(CreateUdpPort(kLocalAddr1));
2580 EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2581 EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2582
2583 rtc::scoped_ptr<Port> stun_port(
2584 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2585 EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2586 EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2587
2588 rtc::scoped_ptr<Port> tcp_port(CreateTcpPort(kLocalAddr1));
2589 EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2590 EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
2591 EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2592
2593 rtc::scoped_ptr<Port> turn_port(
2594 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2595 EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2596 EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2597}