blob: 7e787e08eb316c24053efdcf6dc39a21891db446 [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
kwiberg3ec46792016-04-27 07:22:53 -070011#include <memory>
12
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000013#include "webrtc/p2p/base/basicpacketsocketfactory.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000014#include "webrtc/p2p/base/relayport.h"
15#include "webrtc/p2p/base/stunport.h"
16#include "webrtc/p2p/base/tcpport.h"
17#include "webrtc/p2p/base/testrelayserver.h"
18#include "webrtc/p2p/base/teststunserver.h"
19#include "webrtc/p2p/base/testturnserver.h"
20#include "webrtc/p2p/base/transport.h"
21#include "webrtc/p2p/base/turnport.h"
tfarina5237aaf2015-11-10 23:44:30 -080022#include "webrtc/base/arraysize.h"
jbauchf1f87202016-03-30 06:43:37 -070023#include "webrtc/base/buffer.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024#include "webrtc/base/crc32.h"
25#include "webrtc/base/gunit.h"
26#include "webrtc/base/helpers.h"
27#include "webrtc/base/logging.h"
28#include "webrtc/base/natserver.h"
29#include "webrtc/base/natsocketfactory.h"
30#include "webrtc/base/physicalsocketserver.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031#include "webrtc/base/socketaddress.h"
32#include "webrtc/base/ssladapter.h"
33#include "webrtc/base/stringutils.h"
34#include "webrtc/base/thread.h"
35#include "webrtc/base/virtualsocketserver.h"
36
37using rtc::AsyncPacketSocket;
jbauchf1f87202016-03-30 06:43:37 -070038using rtc::Buffer;
39using rtc::ByteBufferReader;
40using rtc::ByteBufferWriter;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000041using rtc::NATType;
42using rtc::NAT_OPEN_CONE;
43using rtc::NAT_ADDR_RESTRICTED;
44using rtc::NAT_PORT_RESTRICTED;
45using rtc::NAT_SYMMETRIC;
46using rtc::PacketSocketFactory;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000047using 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 }
kwiberg3ec46792016-04-27 07:22:53 -0700215 std::unique_ptr<Buffer> last_stun_buf_;
216 std::unique_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_;
kwiberg3ec46792016-04-27 07:22:53 -0700347 std::unique_ptr<Port> port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348
349 int complete_count_;
350 Connection* conn_;
351 SocketAddress remote_address_;
kwiberg3ec46792016-04-27 07:22:53 -0700352 std::unique_ptr<StunMessage> remote_request_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353 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_;
kwiberg3ec46792016-04-27 07:22:53 -0700767 std::unique_ptr<rtc::PhysicalSocketServer> pss_;
768 std::unique_ptr<rtc::VirtualSocketServer> ss_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000769 rtc::SocketServerScope ss_scope_;
770 rtc::Network network_;
771 rtc::BasicPacketSocketFactory socket_factory_;
kwiberg3ec46792016-04-27 07:22:53 -0700772 std::unique_ptr<rtc::NATServer> nat_server1_;
773 std::unique_ptr<rtc::NATServer> nat_server2_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774 rtc::NATSocketFactory nat_factory1_;
775 rtc::NATSocketFactory nat_factory2_;
776 rtc::BasicPacketSocketFactory nat_socket_factory1_;
777 rtc::BasicPacketSocketFactory nat_socket_factory2_;
kwiberg3ec46792016-04-27 07:22:53 -0700778 std::unique_ptr<TestStunServer> stun_server_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000779 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
kwiberg3ec46792016-04-27 07:22:53 -07001220 std::unique_ptr<rtc::AsyncSocket> server(
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07001221 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) {
kwiberg3ec46792016-04-27 07:22:53 -07001325 std::unique_ptr<TestPort> lport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001326 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());
kwiberg3ec46792016-04-27 07:22:53 -07001357 std::unique_ptr<IceMessage> modified_req(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001358 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();
kwiberg3ec46792016-04-27 07:22:53 -07001371 std::unique_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) {
kwiberg3ec46792016-04-27 07:22:53 -07001385 std::unique_ptr<TestPort> lport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001386 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001387 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1388 lport->SetIceTiebreaker(kTiebreaker1);
kwiberg3ec46792016-04-27 07:22:53 -07001389 std::unique_ptr<TestPort> rport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 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);
kwiberg3ec46792016-04-27 07:22:53 -07001433 std::unique_ptr<UDPPort> port(CreateUdpPort(kLocalAddr1, &socket_factory));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001434
1435 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1436 port->PrepareAddress();
1437
1438 EXPECT_EQ(0U, port->Candidates().size());
1439 socket->SignalAddressReady(socket, kLocalAddr2);
1440
1441 EXPECT_EQ(1U, port->Candidates().size());
1442}
1443
1444TEST_F(PortTest, TestDelayedBindingTcp) {
1445 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1446 FakePacketSocketFactory socket_factory;
1447
1448 socket_factory.set_next_server_tcp_socket(socket);
kwiberg3ec46792016-04-27 07:22:53 -07001449 std::unique_ptr<TCPPort> port(CreateTcpPort(kLocalAddr1, &socket_factory));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001450
1451 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1452 port->PrepareAddress();
1453
1454 EXPECT_EQ(0U, port->Candidates().size());
1455 socket->SignalAddressReady(socket, kLocalAddr2);
1456
1457 EXPECT_EQ(1U, port->Candidates().size());
1458}
1459
1460void PortTest::TestCrossFamilyPorts(int type) {
1461 FakePacketSocketFactory factory;
kwiberg3ec46792016-04-27 07:22:53 -07001462 std::unique_ptr<Port> ports[4];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463 SocketAddress addresses[4] = {SocketAddress("192.168.1.3", 0),
1464 SocketAddress("192.168.1.4", 0),
1465 SocketAddress("2001:db8::1", 0),
1466 SocketAddress("2001:db8::2", 0)};
1467 for (int i = 0; i < 4; i++) {
1468 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1469 if (type == SOCK_DGRAM) {
1470 factory.set_next_udp_socket(socket);
1471 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1472 } else if (type == SOCK_STREAM) {
1473 factory.set_next_server_tcp_socket(socket);
1474 ports[i].reset(CreateTcpPort(addresses[i], &factory));
1475 }
1476 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1477 socket->SignalAddressReady(socket, addresses[i]);
1478 ports[i]->PrepareAddress();
1479 }
1480
1481 // IPv4 Port, connects to IPv6 candidate and then to IPv4 candidate.
1482 if (type == SOCK_STREAM) {
1483 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1484 factory.set_next_client_tcp_socket(clientsocket);
1485 }
1486 Connection* c = ports[0]->CreateConnection(GetCandidate(ports[2].get()),
1487 Port::ORIGIN_MESSAGE);
1488 EXPECT_TRUE(NULL == c);
1489 EXPECT_EQ(0U, ports[0]->connections().size());
1490 c = ports[0]->CreateConnection(GetCandidate(ports[1].get()),
1491 Port::ORIGIN_MESSAGE);
1492 EXPECT_FALSE(NULL == c);
1493 EXPECT_EQ(1U, ports[0]->connections().size());
1494
1495 // IPv6 Port, connects to IPv4 candidate and to IPv6 candidate.
1496 if (type == SOCK_STREAM) {
1497 FakeAsyncPacketSocket* clientsocket = new FakeAsyncPacketSocket();
1498 factory.set_next_client_tcp_socket(clientsocket);
1499 }
1500 c = ports[2]->CreateConnection(GetCandidate(ports[0].get()),
1501 Port::ORIGIN_MESSAGE);
1502 EXPECT_TRUE(NULL == c);
1503 EXPECT_EQ(0U, ports[2]->connections().size());
1504 c = ports[2]->CreateConnection(GetCandidate(ports[3].get()),
1505 Port::ORIGIN_MESSAGE);
1506 EXPECT_FALSE(NULL == c);
1507 EXPECT_EQ(1U, ports[2]->connections().size());
1508}
1509
1510TEST_F(PortTest, TestSkipCrossFamilyTcp) {
1511 TestCrossFamilyPorts(SOCK_STREAM);
1512}
1513
1514TEST_F(PortTest, TestSkipCrossFamilyUdp) {
1515 TestCrossFamilyPorts(SOCK_DGRAM);
1516}
1517
Peter Thatcherb8b01432015-07-07 16:45:53 -07001518void PortTest::ExpectPortsCanConnect(bool can_connect, Port* p1, Port* p2) {
1519 Connection* c = p1->CreateConnection(GetCandidate(p2),
1520 Port::ORIGIN_MESSAGE);
1521 if (can_connect) {
1522 EXPECT_FALSE(NULL == c);
1523 EXPECT_EQ(1U, p1->connections().size());
1524 } else {
1525 EXPECT_TRUE(NULL == c);
1526 EXPECT_EQ(0U, p1->connections().size());
1527 }
1528}
1529
1530TEST_F(PortTest, TestUdpV6CrossTypePorts) {
1531 FakePacketSocketFactory factory;
kwiberg3ec46792016-04-27 07:22:53 -07001532 std::unique_ptr<Port> ports[4];
Peter Thatcherb8b01432015-07-07 16:45:53 -07001533 SocketAddress addresses[4] = {SocketAddress("2001:db8::1", 0),
1534 SocketAddress("fe80::1", 0),
1535 SocketAddress("fe80::2", 0),
1536 SocketAddress("::1", 0)};
1537 for (int i = 0; i < 4; i++) {
1538 FakeAsyncPacketSocket *socket = new FakeAsyncPacketSocket();
1539 factory.set_next_udp_socket(socket);
1540 ports[i].reset(CreateUdpPort(addresses[i], &factory));
1541 socket->set_state(AsyncPacketSocket::STATE_BINDING);
1542 socket->SignalAddressReady(socket, addresses[i]);
1543 ports[i]->PrepareAddress();
1544 }
1545
1546 Port* standard = ports[0].get();
1547 Port* link_local1 = ports[1].get();
1548 Port* link_local2 = ports[2].get();
1549 Port* localhost = ports[3].get();
1550
1551 ExpectPortsCanConnect(false, link_local1, standard);
1552 ExpectPortsCanConnect(false, standard, link_local1);
1553 ExpectPortsCanConnect(false, link_local1, localhost);
1554 ExpectPortsCanConnect(false, localhost, link_local1);
1555
1556 ExpectPortsCanConnect(true, link_local1, link_local2);
1557 ExpectPortsCanConnect(true, localhost, standard);
1558 ExpectPortsCanConnect(true, standard, localhost);
1559}
1560
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001561// This test verifies DSCP value set through SetOption interface can be
1562// get through DefaultDscpValue.
1563TEST_F(PortTest, TestDefaultDscpValue) {
1564 int dscp;
kwiberg3ec46792016-04-27 07:22:53 -07001565 std::unique_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001566 EXPECT_EQ(0, udpport->SetOption(rtc::Socket::OPT_DSCP,
1567 rtc::DSCP_CS6));
1568 EXPECT_EQ(0, udpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
kwiberg3ec46792016-04-27 07:22:53 -07001569 std::unique_ptr<TCPPort> tcpport(CreateTcpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001570 EXPECT_EQ(0, tcpport->SetOption(rtc::Socket::OPT_DSCP,
1571 rtc::DSCP_AF31));
1572 EXPECT_EQ(0, tcpport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1573 EXPECT_EQ(rtc::DSCP_AF31, dscp);
kwiberg3ec46792016-04-27 07:22:53 -07001574 std::unique_ptr<StunPort> stunport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001575 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
1576 EXPECT_EQ(0, stunport->SetOption(rtc::Socket::OPT_DSCP,
1577 rtc::DSCP_AF41));
1578 EXPECT_EQ(0, stunport->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1579 EXPECT_EQ(rtc::DSCP_AF41, dscp);
kwiberg3ec46792016-04-27 07:22:53 -07001580 std::unique_ptr<TurnPort> turnport1(
1581 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001582 // Socket is created in PrepareAddress.
1583 turnport1->PrepareAddress();
1584 EXPECT_EQ(0, turnport1->SetOption(rtc::Socket::OPT_DSCP,
1585 rtc::DSCP_CS7));
1586 EXPECT_EQ(0, turnport1->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1587 EXPECT_EQ(rtc::DSCP_CS7, dscp);
1588 // This will verify correct value returned without the socket.
kwiberg3ec46792016-04-27 07:22:53 -07001589 std::unique_ptr<TurnPort> turnport2(
1590 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001591 EXPECT_EQ(0, turnport2->SetOption(rtc::Socket::OPT_DSCP,
1592 rtc::DSCP_CS6));
1593 EXPECT_EQ(0, turnport2->GetOption(rtc::Socket::OPT_DSCP, &dscp));
1594 EXPECT_EQ(rtc::DSCP_CS6, dscp);
1595}
1596
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001597// Test sending STUN messages.
1598TEST_F(PortTest, TestSendStunMessage) {
kwiberg3ec46792016-04-27 07:22:53 -07001599 std::unique_ptr<TestPort> lport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001600 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
kwiberg3ec46792016-04-27 07:22:53 -07001601 std::unique_ptr<TestPort> rport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001602 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001603 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1604 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001605 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1606 rport->SetIceTiebreaker(kTiebreaker2);
1607
1608 // Send a fake ping from lport to rport.
1609 lport->PrepareAddress();
1610 rport->PrepareAddress();
1611 ASSERT_FALSE(rport->Candidates().empty());
1612 Connection* lconn = lport->CreateConnection(
1613 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1614 Connection* rconn = rport->CreateConnection(
1615 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1616 lconn->Ping(0);
1617
1618 // Check that it's a proper BINDING-REQUEST.
1619 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1620 IceMessage* msg = lport->last_stun_msg();
1621 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1622 EXPECT_FALSE(msg->IsLegacy());
1623 const StunByteStringAttribute* username_attr =
1624 msg->GetByteString(STUN_ATTR_USERNAME);
1625 ASSERT_TRUE(username_attr != NULL);
1626 const StunUInt32Attribute* priority_attr = msg->GetUInt32(STUN_ATTR_PRIORITY);
1627 ASSERT_TRUE(priority_attr != NULL);
1628 EXPECT_EQ(kDefaultPrflxPriority, priority_attr->value());
1629 EXPECT_EQ("rfrag:lfrag", username_attr->GetString());
1630 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1631 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
jbauchf1f87202016-03-30 06:43:37 -07001632 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001633 "rpass"));
1634 const StunUInt64Attribute* ice_controlling_attr =
1635 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1636 ASSERT_TRUE(ice_controlling_attr != NULL);
1637 EXPECT_EQ(lport->IceTiebreaker(), ice_controlling_attr->value());
1638 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1639 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
1640 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1641 EXPECT_TRUE(StunMessage::ValidateFingerprint(
jbauchf1f87202016-03-30 06:43:37 -07001642 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001643
1644 // Request should not include ping count.
1645 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1646
1647 // Save a copy of the BINDING-REQUEST for use below.
kwiberg3ec46792016-04-27 07:22:53 -07001648 std::unique_ptr<IceMessage> request(CopyStunMessage(msg));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001649
1650 // Respond with a BINDING-RESPONSE.
1651 rport->SendBindingResponse(request.get(), lport->Candidates()[0].address());
1652 msg = rport->last_stun_msg();
1653 ASSERT_TRUE(msg != NULL);
1654 EXPECT_EQ(STUN_BINDING_RESPONSE, msg->type());
1655
1656
1657 EXPECT_FALSE(msg->IsLegacy());
1658 const StunAddressAttribute* addr_attr = msg->GetAddress(
1659 STUN_ATTR_XOR_MAPPED_ADDRESS);
1660 ASSERT_TRUE(addr_attr != NULL);
1661 EXPECT_EQ(lport->Candidates()[0].address(), addr_attr->GetAddress());
1662 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1663 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
jbauchf1f87202016-03-30 06:43:37 -07001664 rport->last_stun_buf()->data<char>(), rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001665 "rpass"));
1666 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1667 EXPECT_TRUE(StunMessage::ValidateFingerprint(
jbauchf1f87202016-03-30 06:43:37 -07001668 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001669 // No USERNAME or PRIORITY in ICE responses.
1670 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1671 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1672 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MAPPED_ADDRESS) == NULL);
1673 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLING) == NULL);
1674 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_ICE_CONTROLLED) == NULL);
1675 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1676
1677 // Response should not include ping count.
1678 ASSERT_TRUE(msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT) == NULL);
1679
1680 // Respond with a BINDING-ERROR-RESPONSE. This wouldn't happen in real life,
1681 // but we can do it here.
1682 rport->SendBindingErrorResponse(request.get(),
1683 lport->Candidates()[0].address(),
1684 STUN_ERROR_SERVER_ERROR,
1685 STUN_ERROR_REASON_SERVER_ERROR);
1686 msg = rport->last_stun_msg();
1687 ASSERT_TRUE(msg != NULL);
1688 EXPECT_EQ(STUN_BINDING_ERROR_RESPONSE, msg->type());
1689 EXPECT_FALSE(msg->IsLegacy());
1690 const StunErrorCodeAttribute* error_attr = msg->GetErrorCode();
1691 ASSERT_TRUE(error_attr != NULL);
1692 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, error_attr->code());
1693 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR), error_attr->reason());
1694 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY) != NULL);
1695 EXPECT_TRUE(StunMessage::ValidateMessageIntegrity(
jbauchf1f87202016-03-30 06:43:37 -07001696 rport->last_stun_buf()->data<char>(), rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001697 "rpass"));
1698 EXPECT_TRUE(msg->GetUInt32(STUN_ATTR_FINGERPRINT) != NULL);
1699 EXPECT_TRUE(StunMessage::ValidateFingerprint(
jbauchf1f87202016-03-30 06:43:37 -07001700 lport->last_stun_buf()->data<char>(), lport->last_stun_buf()->size()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001701 // No USERNAME with ICE.
1702 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USERNAME) == NULL);
1703 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_PRIORITY) == NULL);
1704
1705 // Testing STUN binding requests from rport --> lport, having ICE_CONTROLLED
1706 // and (incremented) RETRANSMIT_COUNT attributes.
1707 rport->Reset();
1708 rport->set_send_retransmit_count_attribute(true);
1709 rconn->Ping(0);
1710 rconn->Ping(0);
1711 rconn->Ping(0);
1712 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1713 msg = rport->last_stun_msg();
1714 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
1715 const StunUInt64Attribute* ice_controlled_attr =
1716 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED);
1717 ASSERT_TRUE(ice_controlled_attr != NULL);
1718 EXPECT_EQ(rport->IceTiebreaker(), ice_controlled_attr->value());
1719 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
1720
1721 // Request should include ping count.
1722 const StunUInt32Attribute* retransmit_attr =
1723 msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1724 ASSERT_TRUE(retransmit_attr != NULL);
1725 EXPECT_EQ(2U, retransmit_attr->value());
1726
1727 // Respond with a BINDING-RESPONSE.
1728 request.reset(CopyStunMessage(msg));
1729 lport->SendBindingResponse(request.get(), rport->Candidates()[0].address());
1730 msg = lport->last_stun_msg();
1731
1732 // Response should include same ping count.
1733 retransmit_attr = msg->GetUInt32(STUN_ATTR_RETRANSMIT_COUNT);
1734 ASSERT_TRUE(retransmit_attr != NULL);
1735 EXPECT_EQ(2U, retransmit_attr->value());
1736}
1737
1738TEST_F(PortTest, TestUseCandidateAttribute) {
kwiberg3ec46792016-04-27 07:22:53 -07001739 std::unique_ptr<TestPort> lport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001740 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
kwiberg3ec46792016-04-27 07:22:53 -07001741 std::unique_ptr<TestPort> rport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001742 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001743 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1744 lport->SetIceTiebreaker(kTiebreaker1);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001745 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1746 rport->SetIceTiebreaker(kTiebreaker2);
1747
1748 // Send a fake ping from lport to rport.
1749 lport->PrepareAddress();
1750 rport->PrepareAddress();
1751 ASSERT_FALSE(rport->Candidates().empty());
1752 Connection* lconn = lport->CreateConnection(
1753 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1754 lconn->Ping(0);
1755 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1756 IceMessage* msg = lport->last_stun_msg();
1757 const StunUInt64Attribute* ice_controlling_attr =
1758 msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING);
1759 ASSERT_TRUE(ice_controlling_attr != NULL);
1760 const StunByteStringAttribute* use_candidate_attr = msg->GetByteString(
1761 STUN_ATTR_USE_CANDIDATE);
1762 ASSERT_TRUE(use_candidate_attr != NULL);
1763}
1764
honghaiza0c44ea2016-03-23 16:07:48 -07001765TEST_F(PortTest, TestNetworkInfoAttribute) {
kwiberg3ec46792016-04-27 07:22:53 -07001766 std::unique_ptr<TestPort> lport(
honghaiza0c44ea2016-03-23 16:07:48 -07001767 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
1768 // Set the network type for rport to be cellular so its cost will be 999.
1769 SetNetworkType(rtc::ADAPTER_TYPE_CELLULAR);
kwiberg3ec46792016-04-27 07:22:53 -07001770 std::unique_ptr<TestPort> rport(
honghaiza0c44ea2016-03-23 16:07:48 -07001771 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
1772 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
1773 lport->SetIceTiebreaker(kTiebreaker1);
1774 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
1775 rport->SetIceTiebreaker(kTiebreaker2);
1776
1777 uint16_t lnetwork_id = 9;
1778 lport->Network()->set_id(lnetwork_id);
1779 // Send a fake ping from lport to rport.
1780 lport->PrepareAddress();
1781 rport->PrepareAddress();
1782 Connection* lconn =
1783 lport->CreateConnection(rport->Candidates()[0], Port::ORIGIN_MESSAGE);
1784 lconn->Ping(0);
1785 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
1786 IceMessage* msg = lport->last_stun_msg();
1787 const StunUInt32Attribute* network_info_attr =
1788 msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1789 ASSERT_TRUE(network_info_attr != NULL);
1790 uint32_t network_info = network_info_attr->value();
1791 EXPECT_EQ(lnetwork_id, network_info >> 16);
1792 // Default network cost is 0.
1793 EXPECT_EQ(0U, network_info & 0xFFFF);
1794
1795 // Send a fake ping from rport to lport.
1796 uint16_t rnetwork_id = 8;
1797 rport->Network()->set_id(rnetwork_id);
1798 Connection* rconn =
1799 rport->CreateConnection(lport->Candidates()[0], Port::ORIGIN_MESSAGE);
1800 rconn->Ping(0);
1801 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
1802 msg = rport->last_stun_msg();
1803 network_info_attr = msg->GetUInt32(STUN_ATTR_NETWORK_INFO);
1804 ASSERT_TRUE(network_info_attr != NULL);
1805 network_info = network_info_attr->value();
1806 EXPECT_EQ(rnetwork_id, network_info >> 16);
1807 EXPECT_EQ(cricket::kMaxNetworkCost, network_info & 0xFFFF);
1808}
1809
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001810// Test handling STUN messages.
1811TEST_F(PortTest, TestHandleStunMessage) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001812 // Our port will act as the "remote" port.
kwiberg3ec46792016-04-27 07:22:53 -07001813 std::unique_ptr<TestPort> port(CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001814
kwiberg3ec46792016-04-27 07:22:53 -07001815 std::unique_ptr<IceMessage> in_msg, out_msg;
1816 std::unique_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001817 rtc::SocketAddress addr(kLocalAddr1);
1818 std::string username;
1819
1820 // BINDING-REQUEST from local to remote with valid ICE username,
1821 // MESSAGE-INTEGRITY, and FINGERPRINT.
1822 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1823 "rfrag:lfrag"));
1824 in_msg->AddMessageIntegrity("rpass");
1825 in_msg->AddFingerprint();
1826 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001827 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1828 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001829 EXPECT_TRUE(out_msg.get() != NULL);
1830 EXPECT_EQ("lfrag", username);
1831
1832 // BINDING-RESPONSE without username, with MESSAGE-INTEGRITY and FINGERPRINT.
1833 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1834 in_msg->AddAttribute(
1835 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1836 in_msg->AddMessageIntegrity("rpass");
1837 in_msg->AddFingerprint();
1838 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001839 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1840 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001841 EXPECT_TRUE(out_msg.get() != NULL);
1842 EXPECT_EQ("", username);
1843
1844 // BINDING-ERROR-RESPONSE without username, with error, M-I, and FINGERPRINT.
1845 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
1846 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
1847 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
1848 in_msg->AddFingerprint();
1849 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001850 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1851 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001852 EXPECT_TRUE(out_msg.get() != NULL);
1853 EXPECT_EQ("", username);
1854 ASSERT_TRUE(out_msg->GetErrorCode() != NULL);
1855 EXPECT_EQ(STUN_ERROR_SERVER_ERROR, out_msg->GetErrorCode()->code());
1856 EXPECT_EQ(std::string(STUN_ERROR_REASON_SERVER_ERROR),
1857 out_msg->GetErrorCode()->reason());
1858}
1859
guoweisd12140a2015-09-10 13:32:11 -07001860// Tests handling of ICE binding requests with missing or incorrect usernames.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001861TEST_F(PortTest, TestHandleStunMessageBadUsername) {
kwiberg3ec46792016-04-27 07:22:53 -07001862 std::unique_ptr<TestPort> port(CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001863
kwiberg3ec46792016-04-27 07:22:53 -07001864 std::unique_ptr<IceMessage> in_msg, out_msg;
1865 std::unique_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001866 rtc::SocketAddress addr(kLocalAddr1);
1867 std::string username;
1868
1869 // BINDING-REQUEST with no username.
1870 in_msg.reset(CreateStunMessage(STUN_BINDING_REQUEST));
1871 in_msg->AddMessageIntegrity("rpass");
1872 in_msg->AddFingerprint();
1873 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001874 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1875 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001876 EXPECT_TRUE(out_msg.get() == NULL);
1877 EXPECT_EQ("", username);
1878 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1879
1880 // BINDING-REQUEST with empty username.
1881 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, ""));
1882 in_msg->AddMessageIntegrity("rpass");
1883 in_msg->AddFingerprint();
1884 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001885 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1886 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001887 EXPECT_TRUE(out_msg.get() == NULL);
1888 EXPECT_EQ("", username);
1889 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1890
1891 // BINDING-REQUEST with too-short username.
1892 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST, "rfra"));
1893 in_msg->AddMessageIntegrity("rpass");
1894 in_msg->AddFingerprint();
1895 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001896 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1897 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001898 EXPECT_TRUE(out_msg.get() == NULL);
1899 EXPECT_EQ("", username);
1900 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1901
1902 // BINDING-REQUEST with reversed username.
1903 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1904 "lfrag:rfrag"));
1905 in_msg->AddMessageIntegrity("rpass");
1906 in_msg->AddFingerprint();
1907 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001908 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1909 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001910 EXPECT_TRUE(out_msg.get() == NULL);
1911 EXPECT_EQ("", username);
1912 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1913
1914 // BINDING-REQUEST with garbage username.
1915 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1916 "abcd:efgh"));
1917 in_msg->AddMessageIntegrity("rpass");
1918 in_msg->AddFingerprint();
1919 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001920 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1921 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001922 EXPECT_TRUE(out_msg.get() == NULL);
1923 EXPECT_EQ("", username);
1924 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1925}
1926
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001927// Test handling STUN messages with missing or malformed M-I.
1928TEST_F(PortTest, TestHandleStunMessageBadMessageIntegrity) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001929 // Our port will act as the "remote" port.
kwiberg3ec46792016-04-27 07:22:53 -07001930 std::unique_ptr<TestPort> port(CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001931
kwiberg3ec46792016-04-27 07:22:53 -07001932 std::unique_ptr<IceMessage> in_msg, out_msg;
1933 std::unique_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001934 rtc::SocketAddress addr(kLocalAddr1);
1935 std::string username;
1936
1937 // BINDING-REQUEST from local to remote with valid ICE username and
1938 // FINGERPRINT, but no MESSAGE-INTEGRITY.
1939 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1940 "rfrag:lfrag"));
1941 in_msg->AddFingerprint();
1942 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001943 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1944 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001945 EXPECT_TRUE(out_msg.get() == NULL);
1946 EXPECT_EQ("", username);
1947 EXPECT_EQ(STUN_ERROR_BAD_REQUEST, port->last_stun_error_code());
1948
1949 // BINDING-REQUEST from local to remote with valid ICE username and
1950 // FINGERPRINT, but invalid MESSAGE-INTEGRITY.
1951 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1952 "rfrag:lfrag"));
1953 in_msg->AddMessageIntegrity("invalid");
1954 in_msg->AddFingerprint();
1955 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001956 EXPECT_TRUE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1957 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001958 EXPECT_TRUE(out_msg.get() == NULL);
1959 EXPECT_EQ("", username);
1960 EXPECT_EQ(STUN_ERROR_UNAUTHORIZED, port->last_stun_error_code());
1961
1962 // TODO: BINDING-RESPONSES and BINDING-ERROR-RESPONSES are checked
1963 // by the Connection, not the Port, since they require the remote username.
1964 // Change this test to pass in data via Connection::OnReadPacket instead.
1965}
1966
Peter Thatcher7cbd1882015-09-17 18:54:52 -07001967// Test handling STUN messages with missing or malformed FINGERPRINT.
1968TEST_F(PortTest, TestHandleStunMessageBadFingerprint) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001969 // Our port will act as the "remote" port.
kwiberg3ec46792016-04-27 07:22:53 -07001970 std::unique_ptr<TestPort> port(CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001971
kwiberg3ec46792016-04-27 07:22:53 -07001972 std::unique_ptr<IceMessage> in_msg, out_msg;
1973 std::unique_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001974 rtc::SocketAddress addr(kLocalAddr1);
1975 std::string username;
1976
1977 // BINDING-REQUEST from local to remote with valid ICE username and
1978 // MESSAGE-INTEGRITY, but no FINGERPRINT; GetStunMessage should fail.
1979 in_msg.reset(CreateStunMessageWithUsername(STUN_BINDING_REQUEST,
1980 "rfrag:lfrag"));
1981 in_msg->AddMessageIntegrity("rpass");
1982 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001983 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1984 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001985 EXPECT_EQ(0, port->last_stun_error_code());
1986
1987 // Now, add a fingerprint, but munge the message so it's not valid.
1988 in_msg->AddFingerprint();
1989 in_msg->SetTransactionID("TESTTESTBADD");
1990 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07001991 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
1992 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001993 EXPECT_EQ(0, port->last_stun_error_code());
1994
1995 // Valid BINDING-RESPONSE, except no FINGERPRINT.
1996 in_msg.reset(CreateStunMessage(STUN_BINDING_RESPONSE));
1997 in_msg->AddAttribute(
1998 new StunXorAddressAttribute(STUN_ATTR_XOR_MAPPED_ADDRESS, kLocalAddr2));
1999 in_msg->AddMessageIntegrity("rpass");
2000 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002001 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2002 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002003 EXPECT_EQ(0, port->last_stun_error_code());
2004
2005 // Now, add a fingerprint, but munge the message so it's not valid.
2006 in_msg->AddFingerprint();
2007 in_msg->SetTransactionID("TESTTESTBADD");
2008 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002009 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2010 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002011 EXPECT_EQ(0, port->last_stun_error_code());
2012
2013 // Valid BINDING-ERROR-RESPONSE, except no FINGERPRINT.
2014 in_msg.reset(CreateStunMessage(STUN_BINDING_ERROR_RESPONSE));
2015 in_msg->AddAttribute(new StunErrorCodeAttribute(STUN_ATTR_ERROR_CODE,
2016 STUN_ERROR_SERVER_ERROR, STUN_ERROR_REASON_SERVER_ERROR));
2017 in_msg->AddMessageIntegrity("rpass");
2018 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002019 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2020 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002021 EXPECT_EQ(0, port->last_stun_error_code());
2022
2023 // Now, add a fingerprint, but munge the message so it's not valid.
2024 in_msg->AddFingerprint();
2025 in_msg->SetTransactionID("TESTTESTBADD");
2026 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002027 EXPECT_FALSE(port->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2028 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002029 EXPECT_EQ(0, port->last_stun_error_code());
2030}
2031
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002032// Test handling of STUN binding indication messages . STUN binding
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002033// indications are allowed only to the connection which is in read mode.
2034TEST_F(PortTest, TestHandleStunBindingIndication) {
kwiberg3ec46792016-04-27 07:22:53 -07002035 std::unique_ptr<TestPort> lport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002036 CreateTestPort(kLocalAddr2, "lfrag", "lpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002037 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2038 lport->SetIceTiebreaker(kTiebreaker1);
2039
2040 // Verifying encoding and decoding STUN indication message.
kwiberg3ec46792016-04-27 07:22:53 -07002041 std::unique_ptr<IceMessage> in_msg, out_msg;
2042 std::unique_ptr<ByteBufferWriter> buf(new ByteBufferWriter());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002043 rtc::SocketAddress addr(kLocalAddr1);
2044 std::string username;
2045
2046 in_msg.reset(CreateStunMessage(STUN_BINDING_INDICATION));
2047 in_msg->AddFingerprint();
2048 WriteStunMessage(in_msg.get(), buf.get());
kwiberg6baec032016-03-15 11:09:39 -07002049 EXPECT_TRUE(lport->GetStunMessage(buf->Data(), buf->Length(), addr, &out_msg,
2050 &username));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002051 EXPECT_TRUE(out_msg.get() != NULL);
2052 EXPECT_EQ(out_msg->type(), STUN_BINDING_INDICATION);
2053 EXPECT_EQ("", username);
2054
2055 // Verify connection can handle STUN indication and updates
2056 // last_ping_received.
kwiberg3ec46792016-04-27 07:22:53 -07002057 std::unique_ptr<TestPort> rport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002058 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002059 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2060 rport->SetIceTiebreaker(kTiebreaker2);
2061
2062 lport->PrepareAddress();
2063 rport->PrepareAddress();
2064 ASSERT_FALSE(lport->Candidates().empty());
2065 ASSERT_FALSE(rport->Candidates().empty());
2066
2067 Connection* lconn = lport->CreateConnection(rport->Candidates()[0],
2068 Port::ORIGIN_MESSAGE);
2069 Connection* rconn = rport->CreateConnection(lport->Candidates()[0],
2070 Port::ORIGIN_MESSAGE);
2071 rconn->Ping(0);
2072
2073 ASSERT_TRUE_WAIT(rport->last_stun_msg() != NULL, 1000);
2074 IceMessage* msg = rport->last_stun_msg();
2075 EXPECT_EQ(STUN_BINDING_REQUEST, msg->type());
2076 // Send rport binding request to lport.
jbauchf1f87202016-03-30 06:43:37 -07002077 lconn->OnReadPacket(rport->last_stun_buf()->data<char>(),
2078 rport->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002079 rtc::PacketTime());
2080 ASSERT_TRUE_WAIT(lport->last_stun_msg() != NULL, 1000);
2081 EXPECT_EQ(STUN_BINDING_RESPONSE, lport->last_stun_msg()->type());
honghaiz34b11eb2016-03-16 08:55:44 -07002082 int64_t last_ping_received1 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002083
2084 // Adding a delay of 100ms.
2085 rtc::Thread::Current()->ProcessMessages(100);
2086 // Pinging lconn using stun indication message.
2087 lconn->OnReadPacket(buf->Data(), buf->Length(), rtc::PacketTime());
honghaiz34b11eb2016-03-16 08:55:44 -07002088 int64_t last_ping_received2 = lconn->last_ping_received();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002089 EXPECT_GT(last_ping_received2, last_ping_received1);
2090}
2091
2092TEST_F(PortTest, TestComputeCandidatePriority) {
kwiberg3ec46792016-04-27 07:22:53 -07002093 std::unique_ptr<TestPort> port(CreateTestPort(kLocalAddr1, "name", "pass"));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002094 port->set_type_preference(90);
2095 port->set_component(177);
2096 port->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2097 port->AddCandidateAddress(SocketAddress("2001:db8::1234", 1234));
2098 port->AddCandidateAddress(SocketAddress("fc12:3456::1234", 1234));
2099 port->AddCandidateAddress(SocketAddress("::ffff:192.168.1.4", 1234));
2100 port->AddCandidateAddress(SocketAddress("::192.168.1.4", 1234));
2101 port->AddCandidateAddress(SocketAddress("2002::1234:5678", 1234));
2102 port->AddCandidateAddress(SocketAddress("2001::1234:5678", 1234));
2103 port->AddCandidateAddress(SocketAddress("fecf::1234:5678", 1234));
2104 port->AddCandidateAddress(SocketAddress("3ffe::1234:5678", 1234));
2105 // These should all be:
2106 // (90 << 24) | ([rfc3484 pref value] << 8) | (256 - 177)
Peter Boström0c4e06b2015-10-07 12:23:21 +02002107 uint32_t expected_priority_v4 = 1509957199U;
2108 uint32_t expected_priority_v6 = 1509959759U;
2109 uint32_t expected_priority_ula = 1509962319U;
2110 uint32_t expected_priority_v4mapped = expected_priority_v4;
2111 uint32_t expected_priority_v4compat = 1509949775U;
2112 uint32_t expected_priority_6to4 = 1509954639U;
2113 uint32_t expected_priority_teredo = 1509952079U;
2114 uint32_t expected_priority_sitelocal = 1509949775U;
2115 uint32_t expected_priority_6bone = 1509949775U;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002116 ASSERT_EQ(expected_priority_v4, port->Candidates()[0].priority());
2117 ASSERT_EQ(expected_priority_v6, port->Candidates()[1].priority());
2118 ASSERT_EQ(expected_priority_ula, port->Candidates()[2].priority());
2119 ASSERT_EQ(expected_priority_v4mapped, port->Candidates()[3].priority());
2120 ASSERT_EQ(expected_priority_v4compat, port->Candidates()[4].priority());
2121 ASSERT_EQ(expected_priority_6to4, port->Candidates()[5].priority());
2122 ASSERT_EQ(expected_priority_teredo, port->Candidates()[6].priority());
2123 ASSERT_EQ(expected_priority_sitelocal, port->Candidates()[7].priority());
2124 ASSERT_EQ(expected_priority_6bone, port->Candidates()[8].priority());
2125}
2126
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002127// In the case of shared socket, one port may be shared by local and stun.
2128// Test that candidates with different types will have different foundation.
2129TEST_F(PortTest, TestFoundation) {
kwiberg3ec46792016-04-27 07:22:53 -07002130 std::unique_ptr<TestPort> testport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002131 CreateTestPort(kLocalAddr1, "name", "pass"));
2132 testport->AddCandidateAddress(kLocalAddr1, kLocalAddr1,
2133 LOCAL_PORT_TYPE,
2134 cricket::ICE_TYPE_PREFERENCE_HOST, false);
2135 testport->AddCandidateAddress(kLocalAddr2, kLocalAddr1,
2136 STUN_PORT_TYPE,
2137 cricket::ICE_TYPE_PREFERENCE_SRFLX, true);
2138 EXPECT_NE(testport->Candidates()[0].foundation(),
2139 testport->Candidates()[1].foundation());
2140}
2141
2142// This test verifies the foundation of different types of ICE candidates.
2143TEST_F(PortTest, TestCandidateFoundation) {
kwiberg3ec46792016-04-27 07:22:53 -07002144 std::unique_ptr<rtc::NATServer> nat_server(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002145 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
kwiberg3ec46792016-04-27 07:22:53 -07002146 std::unique_ptr<UDPPort> udpport1(CreateUdpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002147 udpport1->PrepareAddress();
kwiberg3ec46792016-04-27 07:22:53 -07002148 std::unique_ptr<UDPPort> udpport2(CreateUdpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002149 udpport2->PrepareAddress();
2150 EXPECT_EQ(udpport1->Candidates()[0].foundation(),
2151 udpport2->Candidates()[0].foundation());
kwiberg3ec46792016-04-27 07:22:53 -07002152 std::unique_ptr<TCPPort> tcpport1(CreateTcpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002153 tcpport1->PrepareAddress();
kwiberg3ec46792016-04-27 07:22:53 -07002154 std::unique_ptr<TCPPort> tcpport2(CreateTcpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002155 tcpport2->PrepareAddress();
2156 EXPECT_EQ(tcpport1->Candidates()[0].foundation(),
2157 tcpport2->Candidates()[0].foundation());
kwiberg3ec46792016-04-27 07:22:53 -07002158 std::unique_ptr<Port> stunport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002159 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2160 stunport->PrepareAddress();
2161 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2162 EXPECT_NE(tcpport1->Candidates()[0].foundation(),
2163 stunport->Candidates()[0].foundation());
2164 EXPECT_NE(tcpport2->Candidates()[0].foundation(),
2165 stunport->Candidates()[0].foundation());
2166 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2167 stunport->Candidates()[0].foundation());
2168 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2169 stunport->Candidates()[0].foundation());
2170 // Verify GTURN candidate foundation.
kwiberg3ec46792016-04-27 07:22:53 -07002171 std::unique_ptr<RelayPort> relayport(CreateGturnPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002172 relayport->AddServerAddress(
2173 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2174 relayport->PrepareAddress();
2175 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2176 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2177 relayport->Candidates()[0].foundation());
2178 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2179 relayport->Candidates()[0].foundation());
2180 // Verifying TURN candidate foundation.
kwiberg3ec46792016-04-27 07:22:53 -07002181 std::unique_ptr<Port> turnport1(
2182 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002183 turnport1->PrepareAddress();
2184 ASSERT_EQ_WAIT(1U, turnport1->Candidates().size(), kTimeout);
2185 EXPECT_NE(udpport1->Candidates()[0].foundation(),
2186 turnport1->Candidates()[0].foundation());
2187 EXPECT_NE(udpport2->Candidates()[0].foundation(),
2188 turnport1->Candidates()[0].foundation());
2189 EXPECT_NE(stunport->Candidates()[0].foundation(),
2190 turnport1->Candidates()[0].foundation());
kwiberg3ec46792016-04-27 07:22:53 -07002191 std::unique_ptr<Port> turnport2(
2192 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002193 turnport2->PrepareAddress();
2194 ASSERT_EQ_WAIT(1U, turnport2->Candidates().size(), kTimeout);
2195 EXPECT_EQ(turnport1->Candidates()[0].foundation(),
2196 turnport2->Candidates()[0].foundation());
2197
2198 // Running a second turn server, to get different base IP address.
2199 SocketAddress kTurnUdpIntAddr2("99.99.98.4", STUN_SERVER_PORT);
2200 SocketAddress kTurnUdpExtAddr2("99.99.98.5", 0);
2201 TestTurnServer turn_server2(
2202 rtc::Thread::Current(), kTurnUdpIntAddr2, kTurnUdpExtAddr2);
kwiberg3ec46792016-04-27 07:22:53 -07002203 std::unique_ptr<Port> turnport3(
2204 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP,
2205 kTurnUdpIntAddr2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002206 turnport3->PrepareAddress();
2207 ASSERT_EQ_WAIT(1U, turnport3->Candidates().size(), kTimeout);
2208 EXPECT_NE(turnport3->Candidates()[0].foundation(),
2209 turnport2->Candidates()[0].foundation());
Honghai Zhang80f1db92016-01-27 11:54:45 -08002210
2211 // Start a TCP turn server, and check that two turn candidates have
2212 // different foundations if their relay protocols are different.
2213 TestTurnServer turn_server3(rtc::Thread::Current(), kTurnTcpIntAddr,
2214 kTurnUdpExtAddr, PROTO_TCP);
kwiberg3ec46792016-04-27 07:22:53 -07002215 std::unique_ptr<Port> turnport4(
Honghai Zhang80f1db92016-01-27 11:54:45 -08002216 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_TCP, PROTO_UDP));
2217 turnport4->PrepareAddress();
2218 ASSERT_EQ_WAIT(1U, turnport4->Candidates().size(), kTimeout);
2219 EXPECT_NE(turnport2->Candidates()[0].foundation(),
2220 turnport4->Candidates()[0].foundation());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002221}
2222
2223// This test verifies the related addresses of different types of
2224// ICE candiates.
2225TEST_F(PortTest, TestCandidateRelatedAddress) {
kwiberg3ec46792016-04-27 07:22:53 -07002226 std::unique_ptr<rtc::NATServer> nat_server(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002227 CreateNatServer(kNatAddr1, NAT_OPEN_CONE));
kwiberg3ec46792016-04-27 07:22:53 -07002228 std::unique_ptr<UDPPort> udpport(CreateUdpPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002229 udpport->PrepareAddress();
2230 // For UDPPort, related address will be empty.
2231 EXPECT_TRUE(udpport->Candidates()[0].related_address().IsNil());
2232 // Testing related address for stun candidates.
2233 // For stun candidate related address must be equal to the base
2234 // socket address.
kwiberg3ec46792016-04-27 07:22:53 -07002235 std::unique_ptr<StunPort> stunport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002236 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2237 stunport->PrepareAddress();
2238 ASSERT_EQ_WAIT(1U, stunport->Candidates().size(), kTimeout);
2239 // Check STUN candidate address.
2240 EXPECT_EQ(stunport->Candidates()[0].address().ipaddr(),
2241 kNatAddr1.ipaddr());
2242 // Check STUN candidate related address.
2243 EXPECT_EQ(stunport->Candidates()[0].related_address(),
2244 stunport->GetLocalAddress());
2245 // Verifying the related address for the GTURN candidates.
2246 // NOTE: In case of GTURN related address will be equal to the mapped
2247 // address, but address(mapped) will not be XOR.
kwiberg3ec46792016-04-27 07:22:53 -07002248 std::unique_ptr<RelayPort> relayport(CreateGturnPort(kLocalAddr1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002249 relayport->AddServerAddress(
2250 cricket::ProtocolAddress(kRelayUdpIntAddr, cricket::PROTO_UDP));
2251 relayport->PrepareAddress();
2252 ASSERT_EQ_WAIT(1U, relayport->Candidates().size(), kTimeout);
2253 // For Gturn related address is set to "0.0.0.0:0"
2254 EXPECT_EQ(rtc::SocketAddress(),
2255 relayport->Candidates()[0].related_address());
2256 // Verifying the related address for TURN candidate.
2257 // For TURN related address must be equal to the mapped address.
kwiberg3ec46792016-04-27 07:22:53 -07002258 std::unique_ptr<Port> turnport(
2259 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002260 turnport->PrepareAddress();
2261 ASSERT_EQ_WAIT(1U, turnport->Candidates().size(), kTimeout);
2262 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
2263 turnport->Candidates()[0].address().ipaddr());
2264 EXPECT_EQ(kNatAddr1.ipaddr(),
2265 turnport->Candidates()[0].related_address().ipaddr());
2266}
2267
2268// Test priority value overflow handling when preference is set to 3.
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002269TEST_F(PortTest, TestCandidatePriority) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002270 cricket::Candidate cand1;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002271 cand1.set_priority(3);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002272 cricket::Candidate cand2;
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002273 cand2.set_priority(1);
2274 EXPECT_TRUE(cand1.priority() > cand2.priority());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002275}
2276
2277// Test the Connection priority is calculated correctly.
2278TEST_F(PortTest, TestConnectionPriority) {
kwiberg3ec46792016-04-27 07:22:53 -07002279 std::unique_ptr<TestPort> lport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002280 CreateTestPort(kLocalAddr1, "lfrag", "lpass"));
2281 lport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_HOST);
kwiberg3ec46792016-04-27 07:22:53 -07002282 std::unique_ptr<TestPort> rport(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002283 CreateTestPort(kLocalAddr2, "rfrag", "rpass"));
2284 rport->set_type_preference(cricket::ICE_TYPE_PREFERENCE_RELAY);
2285 lport->set_component(123);
2286 lport->AddCandidateAddress(SocketAddress("192.168.1.4", 1234));
2287 rport->set_component(23);
2288 rport->AddCandidateAddress(SocketAddress("10.1.1.100", 1234));
2289
2290 EXPECT_EQ(0x7E001E85U, lport->Candidates()[0].priority());
2291 EXPECT_EQ(0x2001EE9U, rport->Candidates()[0].priority());
2292
2293 // RFC 5245
2294 // pair priority = 2^32*MIN(G,D) + 2*MAX(G,D) + (G>D?1:0)
2295 lport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2296 rport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2297 Connection* lconn = lport->CreateConnection(
2298 rport->Candidates()[0], Port::ORIGIN_MESSAGE);
2299#if defined(WEBRTC_WIN)
2300 EXPECT_EQ(0x2001EE9FC003D0BU, lconn->priority());
2301#else
2302 EXPECT_EQ(0x2001EE9FC003D0BLLU, lconn->priority());
2303#endif
2304
2305 lport->SetIceRole(cricket::ICEROLE_CONTROLLED);
2306 rport->SetIceRole(cricket::ICEROLE_CONTROLLING);
2307 Connection* rconn = rport->CreateConnection(
2308 lport->Candidates()[0], Port::ORIGIN_MESSAGE);
2309#if defined(WEBRTC_WIN)
2310 EXPECT_EQ(0x2001EE9FC003D0AU, rconn->priority());
2311#else
2312 EXPECT_EQ(0x2001EE9FC003D0ALLU, rconn->priority());
2313#endif
2314}
2315
2316TEST_F(PortTest, TestWritableState) {
2317 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002318 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002319 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002320 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002321
2322 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002323 TestChannel ch1(port1);
2324 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002325
2326 // Acquire addresses.
2327 ch1.Start();
2328 ch2.Start();
2329 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2330 ASSERT_EQ_WAIT(1, ch2.complete_count(), kTimeout);
2331
2332 // Send a ping from src to dst.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002333 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002334 ASSERT_TRUE(ch1.conn() != NULL);
2335 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2336 EXPECT_TRUE_WAIT(ch1.conn()->connected(), kTimeout); // for TCP connect
2337 ch1.Ping();
2338 WAIT(!ch2.remote_address().IsNil(), kTimeout);
2339
2340 // Data should be unsendable until the connection is accepted.
2341 char data[] = "abcd";
tfarina5237aaf2015-11-10 23:44:30 -08002342 int data_size = arraysize(data);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002343 rtc::PacketOptions options;
2344 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2345
2346 // Accept the connection to return the binding response, transition to
2347 // writable, and allow data to be sent.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002348 ch2.AcceptConnection(GetCandidate(port1));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002349 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2350 kTimeout);
2351 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2352
2353 // Ask the connection to update state as if enough time has passed to lose
2354 // full writability and 5 pings went unresponded to. We'll accomplish the
2355 // latter by sending pings but not pumping messages.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002356 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002357 ch1.Ping(i);
2358 }
honghaiz34b11eb2016-03-16 08:55:44 -07002359 int unreliable_timeout_delay = CONNECTION_WRITE_CONNECT_TIMEOUT + 500;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002360 ch1.conn()->UpdateState(unreliable_timeout_delay);
2361 EXPECT_EQ(Connection::STATE_WRITE_UNRELIABLE, ch1.conn()->write_state());
2362
2363 // Data should be able to be sent in this state.
2364 EXPECT_EQ(data_size, ch1.conn()->Send(data, data_size, options));
2365
2366 // And now allow the other side to process the pings and send binding
2367 // responses.
2368 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2369 kTimeout);
2370
2371 // Wait long enough for a full timeout (past however long we've already
2372 // waited).
Peter Boström0c4e06b2015-10-07 12:23:21 +02002373 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002374 ch1.Ping(unreliable_timeout_delay + i);
2375 }
2376 ch1.conn()->UpdateState(unreliable_timeout_delay + CONNECTION_WRITE_TIMEOUT +
2377 500u);
2378 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2379
2380 // Now that the connection has completely timed out, data send should fail.
2381 EXPECT_EQ(SOCKET_ERROR, ch1.conn()->Send(data, data_size, options));
2382
2383 ch1.Stop();
2384 ch2.Stop();
2385}
2386
2387TEST_F(PortTest, TestTimeoutForNeverWritable) {
2388 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002389 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002390 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002391 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002392
2393 // Set up channels.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002394 TestChannel ch1(port1);
2395 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002396
2397 // Acquire addresses.
2398 ch1.Start();
2399 ch2.Start();
2400
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002401 ch1.CreateConnection(GetCandidate(port2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002402 ASSERT_TRUE(ch1.conn() != NULL);
2403 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2404
2405 // Attempt to go directly to write timeout.
Peter Boström0c4e06b2015-10-07 12:23:21 +02002406 for (uint32_t i = 1; i <= CONNECTION_WRITE_CONNECT_FAILURES; ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002407 ch1.Ping(i);
2408 }
2409 ch1.conn()->UpdateState(CONNECTION_WRITE_TIMEOUT + 500u);
2410 EXPECT_EQ(Connection::STATE_WRITE_TIMEOUT, ch1.conn()->write_state());
2411}
2412
2413// This test verifies the connection setup between ICEMODE_FULL
2414// and ICEMODE_LITE.
2415// In this test |ch1| behaves like FULL mode client and we have created
2416// port which responds to the ping message just like LITE client.
2417TEST_F(PortTest, TestIceLiteConnectivity) {
2418 TestPort* ice_full_port = CreateTestPort(
Peter Thatcher7cbd1882015-09-17 18:54:52 -07002419 kLocalAddr1, "lfrag", "lpass",
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002420 cricket::ICEROLE_CONTROLLING, kTiebreaker1);
2421
kwiberg3ec46792016-04-27 07:22:53 -07002422 std::unique_ptr<TestPort> ice_lite_port(
2423 CreateTestPort(kLocalAddr2, "rfrag", "rpass", cricket::ICEROLE_CONTROLLED,
2424 kTiebreaker2));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002425 // Setup TestChannel. This behaves like FULL mode client.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002426 TestChannel ch1(ice_full_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002427 ch1.SetIceMode(ICEMODE_FULL);
2428
2429 // Start gathering candidates.
2430 ch1.Start();
2431 ice_lite_port->PrepareAddress();
2432
2433 ASSERT_EQ_WAIT(1, ch1.complete_count(), kTimeout);
2434 ASSERT_FALSE(ice_lite_port->Candidates().empty());
2435
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002436 ch1.CreateConnection(GetCandidate(ice_lite_port.get()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002437 ASSERT_TRUE(ch1.conn() != NULL);
2438 EXPECT_EQ(Connection::STATE_WRITE_INIT, ch1.conn()->write_state());
2439
2440 // Send ping from full mode client.
2441 // This ping must not have USE_CANDIDATE_ATTR.
2442 ch1.Ping();
2443
2444 // Verify stun ping is without USE_CANDIDATE_ATTR. Getting message directly
2445 // from port.
2446 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2447 IceMessage* msg = ice_full_port->last_stun_msg();
2448 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) == NULL);
2449
2450 // Respond with a BINDING-RESPONSE from litemode client.
2451 // NOTE: Ideally we should't create connection at this stage from lite
2452 // port, as it should be done only after receiving ping with USE_CANDIDATE.
2453 // But we need a connection to send a response message.
2454 ice_lite_port->CreateConnection(
2455 ice_full_port->Candidates()[0], cricket::Port::ORIGIN_MESSAGE);
kwiberg3ec46792016-04-27 07:22:53 -07002456 std::unique_ptr<IceMessage> request(CopyStunMessage(msg));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002457 ice_lite_port->SendBindingResponse(
2458 request.get(), ice_full_port->Candidates()[0].address());
2459
2460 // Feeding the respone message from litemode to the full mode connection.
jbauchf1f87202016-03-30 06:43:37 -07002461 ch1.conn()->OnReadPacket(ice_lite_port->last_stun_buf()->data<char>(),
2462 ice_lite_port->last_stun_buf()->size(),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002463 rtc::PacketTime());
2464 // Verifying full mode connection becomes writable from the response.
2465 EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, ch1.conn()->write_state(),
2466 kTimeout);
2467 EXPECT_TRUE_WAIT(ch1.nominated(), kTimeout);
2468
2469 // Clear existing stun messsages. Otherwise we will process old stun
2470 // message right after we send ping.
2471 ice_full_port->Reset();
2472 // Send ping. This must have USE_CANDIDATE_ATTR.
2473 ch1.Ping();
2474 ASSERT_TRUE_WAIT(ice_full_port->last_stun_msg() != NULL, 1000);
2475 msg = ice_full_port->last_stun_msg();
2476 EXPECT_TRUE(msg->GetByteString(STUN_ATTR_USE_CANDIDATE) != NULL);
2477 ch1.Stop();
2478}
2479
2480// This test case verifies that the CONTROLLING port does not time out.
2481TEST_F(PortTest, TestControllingNoTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002482 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2483 ConnectToSignalDestroyed(port1);
2484 port1->set_timeout_delay(10); // milliseconds
2485 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2486 port1->SetIceTiebreaker(kTiebreaker1);
2487
2488 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2489 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2490 port2->SetIceTiebreaker(kTiebreaker2);
2491
2492 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002493 TestChannel ch1(port1);
2494 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002495
2496 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002497 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002498
2499 // After the connection is destroyed, the port should not be destroyed.
2500 rtc::Thread::Current()->ProcessMessages(kTimeout);
2501 EXPECT_FALSE(destroyed());
2502}
2503
2504// This test case verifies that the CONTROLLED port does time out, but only
2505// after connectivity is lost.
2506TEST_F(PortTest, TestControlledTimeout) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002507 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2508 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2509 port1->SetIceTiebreaker(kTiebreaker1);
2510
2511 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2512 ConnectToSignalDestroyed(port2);
2513 port2->set_timeout_delay(10); // milliseconds
2514 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2515 port2->SetIceTiebreaker(kTiebreaker2);
2516
2517 // The connection must not be destroyed before a connection is attempted.
2518 EXPECT_FALSE(destroyed());
2519
2520 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2521 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2522
2523 // Set up channels and ensure both ports will be deleted.
Guo-wei Shieh1eb87c72015-08-25 11:02:55 -07002524 TestChannel ch1(port1);
2525 TestChannel ch2(port2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002526
2527 // Simulate a connection that succeeds, and then is destroyed.
Guo-wei Shiehbe508a12015-04-06 12:48:47 -07002528 StartConnectAndStopChannels(&ch1, &ch2);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00002529
2530 // The controlled port should be destroyed after 10 milliseconds.
2531 EXPECT_TRUE_WAIT(destroyed(), kTimeout);
2532}
honghaizd0b31432015-09-30 12:42:17 -07002533
2534// This test case verifies that if the role of a port changes from controlled
2535// to controlling after all connections fail, the port will not be destroyed.
2536TEST_F(PortTest, TestControlledToControllingNotDestroyed) {
2537 UDPPort* port1 = CreateUdpPort(kLocalAddr1);
2538 port1->SetIceRole(cricket::ICEROLE_CONTROLLING);
2539 port1->SetIceTiebreaker(kTiebreaker1);
2540
2541 UDPPort* port2 = CreateUdpPort(kLocalAddr2);
2542 ConnectToSignalDestroyed(port2);
2543 port2->set_timeout_delay(10); // milliseconds
2544 port2->SetIceRole(cricket::ICEROLE_CONTROLLED);
2545 port2->SetIceTiebreaker(kTiebreaker2);
2546
2547 // The connection must not be destroyed before a connection is attempted.
2548 EXPECT_FALSE(destroyed());
2549
2550 port1->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2551 port2->set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
2552
2553 // Set up channels and ensure both ports will be deleted.
2554 TestChannel ch1(port1);
2555 TestChannel ch2(port2);
2556
2557 // Simulate a connection that succeeds, and then is destroyed.
2558 StartConnectAndStopChannels(&ch1, &ch2);
2559 // Switch the role after all connections are destroyed.
2560 EXPECT_TRUE_WAIT(ch2.conn() == nullptr, kTimeout);
2561 port1->SetIceRole(cricket::ICEROLE_CONTROLLED);
2562 port2->SetIceRole(cricket::ICEROLE_CONTROLLING);
2563
2564 // After the connection is destroyed, the port should not be destroyed.
2565 rtc::Thread::Current()->ProcessMessages(kTimeout);
2566 EXPECT_FALSE(destroyed());
2567}
Honghai Zhangf9945b22015-12-15 12:20:13 -08002568
2569TEST_F(PortTest, TestSupportsProtocol) {
kwiberg3ec46792016-04-27 07:22:53 -07002570 std::unique_ptr<Port> udp_port(CreateUdpPort(kLocalAddr1));
Honghai Zhangf9945b22015-12-15 12:20:13 -08002571 EXPECT_TRUE(udp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2572 EXPECT_FALSE(udp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2573
kwiberg3ec46792016-04-27 07:22:53 -07002574 std::unique_ptr<Port> stun_port(
Honghai Zhangf9945b22015-12-15 12:20:13 -08002575 CreateStunPort(kLocalAddr1, nat_socket_factory1()));
2576 EXPECT_TRUE(stun_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2577 EXPECT_FALSE(stun_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2578
kwiberg3ec46792016-04-27 07:22:53 -07002579 std::unique_ptr<Port> tcp_port(CreateTcpPort(kLocalAddr1));
Honghai Zhangf9945b22015-12-15 12:20:13 -08002580 EXPECT_TRUE(tcp_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2581 EXPECT_TRUE(tcp_port->SupportsProtocol(SSLTCP_PROTOCOL_NAME));
2582 EXPECT_FALSE(tcp_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2583
kwiberg3ec46792016-04-27 07:22:53 -07002584 std::unique_ptr<Port> turn_port(
Honghai Zhangf9945b22015-12-15 12:20:13 -08002585 CreateTurnPort(kLocalAddr1, nat_socket_factory1(), PROTO_UDP, PROTO_UDP));
2586 EXPECT_TRUE(turn_port->SupportsProtocol(UDP_PROTOCOL_NAME));
2587 EXPECT_FALSE(turn_port->SupportsProtocol(TCP_PROTOCOL_NAME));
2588}