1 /*
2 * Copyright 2012 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 #if defined(WEBRTC_POSIX)
11 #include <dirent.h>
12
13 #include "absl/strings/string_view.h"
14 #endif
15
16 #include <list>
17 #include <memory>
18 #include <utility>
19 #include <vector>
20
21 #include "absl/types/optional.h"
22 #include "api/units/time_delta.h"
23 #include "p2p/base/basic_packet_socket_factory.h"
24 #include "p2p/base/connection.h"
25 #include "p2p/base/mock_dns_resolving_packet_socket_factory.h"
26 #include "p2p/base/p2p_constants.h"
27 #include "p2p/base/port_allocator.h"
28 #include "p2p/base/stun_port.h"
29 #include "p2p/base/test_turn_customizer.h"
30 #include "p2p/base/test_turn_server.h"
31 #include "p2p/base/transport_description.h"
32 #include "p2p/base/turn_port.h"
33 #include "p2p/base/turn_server.h"
34 #include "rtc_base/buffer.h"
35 #include "rtc_base/byte_buffer.h"
36 #include "rtc_base/checks.h"
37 #include "rtc_base/fake_clock.h"
38 #include "rtc_base/gunit.h"
39 #include "rtc_base/net_helper.h"
40 #include "rtc_base/socket.h"
41 #include "rtc_base/socket_address.h"
42 #include "rtc_base/thread.h"
43 #include "rtc_base/time_utils.h"
44 #include "rtc_base/virtual_socket_server.h"
45 #include "test/gtest.h"
46 #include "test/scoped_key_value_config.h"
47
48 namespace {
49 using rtc::SocketAddress;
50
51 using ::testing::_;
52 using ::testing::DoAll;
53 using ::testing::InvokeArgument;
54 using ::testing::Return;
55 using ::testing::ReturnPointee;
56 using ::testing::SetArgPointee;
57
58 static const SocketAddress kLocalAddr1("11.11.11.11", 0);
59 static const SocketAddress kLocalAddr2("22.22.22.22", 0);
60 static const SocketAddress kLocalIPv6Addr("2401:fa00:4:1000:be30:5bff:fee5:c3",
61 0);
62 static const SocketAddress kLocalIPv6Addr2("2401:fa00:4:2000:be30:5bff:fee5:d4",
63 0);
64 static const SocketAddress kTurnUdpIntAddr("99.99.99.3",
65 cricket::TURN_SERVER_PORT);
66 static const SocketAddress kTurnTcpIntAddr("99.99.99.4",
67 cricket::TURN_SERVER_PORT);
68 static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
69 static const SocketAddress kTurnAlternateIntAddr("99.99.99.6",
70 cricket::TURN_SERVER_PORT);
71 // Port for redirecting to a TCP Web server. Should not work.
72 static const SocketAddress kTurnDangerousAddr("99.99.99.7", 81);
73 // Port 53 (the DNS port); should work.
74 static const SocketAddress kTurnPort53Addr("99.99.99.7", 53);
75 // Port 80 (the HTTP port); should work.
76 static const SocketAddress kTurnPort80Addr("99.99.99.7", 80);
77 // Port 443 (the HTTPS port); should work.
78 static const SocketAddress kTurnPort443Addr("99.99.99.7", 443);
79 // The default TURN server port.
80 static const SocketAddress kTurnIntAddr("99.99.99.7",
81 cricket::TURN_SERVER_PORT);
82 static const SocketAddress kTurnIPv6IntAddr(
83 "2400:4030:2:2c00:be30:abcd:efab:cdef",
84 cricket::TURN_SERVER_PORT);
85 static const SocketAddress kTurnUdpIPv6IntAddr(
86 "2400:4030:1:2c00:be30:abcd:efab:cdef",
87 cricket::TURN_SERVER_PORT);
88 static const SocketAddress kTurnInvalidAddr("www.google.invalid.", 3478);
89 static const SocketAddress kTurnValidAddr("www.google.valid.", 3478);
90
91 static const char kCandidateFoundation[] = "foundation";
92 static const char kIceUfrag1[] = "TESTICEUFRAG0001";
93 static const char kIceUfrag2[] = "TESTICEUFRAG0002";
94 static const char kIcePwd1[] = "TESTICEPWD00000000000001";
95 static const char kIcePwd2[] = "TESTICEPWD00000000000002";
96 static const char kTurnUsername[] = "test";
97 static const char kTurnPassword[] = "test";
98 // This test configures the virtual socket server to simulate delay so that we
99 // can verify operations take no more than the expected number of round trips.
100 static constexpr unsigned int kSimulatedRtt = 50;
101 // Connection destruction may happen asynchronously, but it should only
102 // take one simulated clock tick.
103 static constexpr unsigned int kConnectionDestructionDelay = 1;
104 // This used to be 1 second, but that's not always enough for getaddrinfo().
105 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5191
106 static constexpr unsigned int kResolverTimeout = 10000;
107
108 constexpr uint64_t kTiebreakerDefault = 44444;
109
110 static const cricket::ProtocolAddress kTurnUdpProtoAddr(kTurnUdpIntAddr,
111 cricket::PROTO_UDP);
112 static const cricket::ProtocolAddress kTurnTcpProtoAddr(kTurnTcpIntAddr,
113 cricket::PROTO_TCP);
114 static const cricket::ProtocolAddress kTurnTlsProtoAddr(kTurnTcpIntAddr,
115 cricket::PROTO_TLS);
116 static const cricket::ProtocolAddress kTurnUdpIPv6ProtoAddr(kTurnUdpIPv6IntAddr,
117 cricket::PROTO_UDP);
118 static const cricket::ProtocolAddress kTurnDangerousProtoAddr(
119 kTurnDangerousAddr,
120 cricket::PROTO_TCP);
121 static const cricket::ProtocolAddress kTurnPort53ProtoAddr(kTurnPort53Addr,
122 cricket::PROTO_TCP);
123 static const cricket::ProtocolAddress kTurnPort80ProtoAddr(kTurnPort80Addr,
124 cricket::PROTO_TCP);
125 static const cricket::ProtocolAddress kTurnPort443ProtoAddr(kTurnPort443Addr,
126 cricket::PROTO_TCP);
127 static const cricket::ProtocolAddress kTurnPortInvalidHostnameProtoAddr(
128 kTurnInvalidAddr,
129 cricket::PROTO_UDP);
130 static const cricket::ProtocolAddress kTurnPortValidHostnameProtoAddr(
131 kTurnValidAddr,
132 cricket::PROTO_UDP);
133
134 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
GetFDCount()135 static int GetFDCount() {
136 struct dirent* dp;
137 int fd_count = 0;
138 DIR* dir = opendir("/proc/self/fd/");
139 while ((dp = readdir(dir)) != NULL) {
140 if (dp->d_name[0] == '.')
141 continue;
142 ++fd_count;
143 }
144 closedir(dir);
145 return fd_count;
146 }
147 #endif
148
149 } // unnamed namespace
150
151 namespace cricket {
152
153 class TurnPortTestVirtualSocketServer : public rtc::VirtualSocketServer {
154 public:
TurnPortTestVirtualSocketServer()155 TurnPortTestVirtualSocketServer() {
156 // This configures the virtual socket server to always add a simulated
157 // delay of exactly half of kSimulatedRtt.
158 set_delay_mean(kSimulatedRtt / 2);
159 UpdateDelayDistribution();
160 }
161
162 using rtc::VirtualSocketServer::LookupBinding;
163 };
164
165 class TestConnectionWrapper : public sigslot::has_slots<> {
166 public:
TestConnectionWrapper(Connection * conn)167 explicit TestConnectionWrapper(Connection* conn) : connection_(conn) {
168 conn->SignalDestroyed.connect(
169 this, &TestConnectionWrapper::OnConnectionDestroyed);
170 }
171
~TestConnectionWrapper()172 ~TestConnectionWrapper() {
173 if (connection_) {
174 connection_->SignalDestroyed.disconnect(this);
175 }
176 }
177
connection()178 Connection* connection() { return connection_; }
179
180 private:
OnConnectionDestroyed(Connection * conn)181 void OnConnectionDestroyed(Connection* conn) {
182 ASSERT_TRUE(conn == connection_);
183 connection_ = nullptr;
184 }
185
186 Connection* connection_;
187 };
188
189 // Note: This test uses a fake clock with a simulated network round trip
190 // (between local port and TURN server) of kSimulatedRtt.
191 class TurnPortTest : public ::testing::Test,
192 public TurnPort::CallbacksForTest,
193 public sigslot::has_slots<> {
194 public:
TurnPortTest()195 TurnPortTest()
196 : ss_(new TurnPortTestVirtualSocketServer()),
197 main_(ss_.get()),
198 turn_server_(&main_, ss_.get(), kTurnUdpIntAddr, kTurnUdpExtAddr),
199 socket_factory_(ss_.get()) {
200 // Some code uses "last received time == 0" to represent "nothing received
201 // so far", so we need to start the fake clock at a nonzero time...
202 // TODO(deadbeef): Fix this.
203 fake_clock_.AdvanceTime(webrtc::TimeDelta::Seconds(1));
204 }
205
OnTurnPortComplete(Port * port)206 void OnTurnPortComplete(Port* port) { turn_ready_ = true; }
OnTurnPortError(Port * port)207 void OnTurnPortError(Port* port) { turn_error_ = true; }
OnCandidateError(Port * port,const cricket::IceCandidateErrorEvent & event)208 void OnCandidateError(Port* port,
209 const cricket::IceCandidateErrorEvent& event) {
210 error_event_ = event;
211 }
OnTurnUnknownAddress(PortInterface * port,const SocketAddress & addr,ProtocolType proto,IceMessage * msg,const std::string & rf,bool)212 void OnTurnUnknownAddress(PortInterface* port,
213 const SocketAddress& addr,
214 ProtocolType proto,
215 IceMessage* msg,
216 const std::string& rf,
217 bool /*port_muxed*/) {
218 turn_unknown_address_ = true;
219 }
OnTurnReadPacket(Connection * conn,const char * data,size_t size,int64_t packet_time_us)220 void OnTurnReadPacket(Connection* conn,
221 const char* data,
222 size_t size,
223 int64_t packet_time_us) {
224 turn_packets_.push_back(rtc::Buffer(data, size));
225 }
OnUdpPortComplete(Port * port)226 void OnUdpPortComplete(Port* port) { udp_ready_ = true; }
OnUdpReadPacket(Connection * conn,const char * data,size_t size,int64_t packet_time_us)227 void OnUdpReadPacket(Connection* conn,
228 const char* data,
229 size_t size,
230 int64_t packet_time_us) {
231 udp_packets_.push_back(rtc::Buffer(data, size));
232 }
OnSocketReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const int64_t & packet_time_us)233 void OnSocketReadPacket(rtc::AsyncPacketSocket* socket,
234 const char* data,
235 size_t size,
236 const rtc::SocketAddress& remote_addr,
237 const int64_t& packet_time_us) {
238 turn_port_->HandleIncomingPacket(socket, data, size, remote_addr,
239 packet_time_us);
240 }
OnTurnPortDestroyed(PortInterface * port)241 void OnTurnPortDestroyed(PortInterface* port) { turn_port_destroyed_ = true; }
242
243 // TurnPort::TestCallbacks
OnTurnCreatePermissionResult(int code)244 void OnTurnCreatePermissionResult(int code) override {
245 turn_create_permission_success_ = (code == 0);
246 }
OnTurnRefreshResult(int code)247 void OnTurnRefreshResult(int code) override {
248 turn_refresh_success_ = (code == 0);
249 }
OnTurnPortClosed()250 void OnTurnPortClosed() override { turn_port_closed_ = true; }
251
CreateServerSocket(const SocketAddress addr)252 rtc::Socket* CreateServerSocket(const SocketAddress addr) {
253 rtc::Socket* socket = ss_->CreateSocket(AF_INET, SOCK_STREAM);
254 EXPECT_GE(socket->Bind(addr), 0);
255 EXPECT_GE(socket->Listen(5), 0);
256 return socket;
257 }
258
MakeNetwork(const SocketAddress & addr)259 rtc::Network* MakeNetwork(const SocketAddress& addr) {
260 networks_.emplace_back("unittest", "unittest", addr.ipaddr(), 32);
261 networks_.back().AddIP(addr.ipaddr());
262 return &networks_.back();
263 }
264
CreateTurnPort(absl::string_view username,absl::string_view password,const ProtocolAddress & server_address)265 bool CreateTurnPort(absl::string_view username,
266 absl::string_view password,
267 const ProtocolAddress& server_address) {
268 return CreateTurnPortWithAllParams(MakeNetwork(kLocalAddr1), username,
269 password, server_address);
270 }
CreateTurnPort(const rtc::SocketAddress & local_address,absl::string_view username,absl::string_view password,const ProtocolAddress & server_address)271 bool CreateTurnPort(const rtc::SocketAddress& local_address,
272 absl::string_view username,
273 absl::string_view password,
274 const ProtocolAddress& server_address) {
275 return CreateTurnPortWithAllParams(MakeNetwork(local_address), username,
276 password, server_address);
277 }
278
CreateTurnPortWithNetwork(const rtc::Network * network,absl::string_view username,absl::string_view password,const ProtocolAddress & server_address)279 bool CreateTurnPortWithNetwork(const rtc::Network* network,
280 absl::string_view username,
281 absl::string_view password,
282 const ProtocolAddress& server_address) {
283 return CreateTurnPortWithAllParams(network, username, password,
284 server_address);
285 }
286
287 // Version of CreateTurnPort that takes all possible parameters; all other
288 // helper methods call this, such that "SetIceRole" and "ConnectSignals" (and
289 // possibly other things in the future) only happen in one place.
CreateTurnPortWithAllParams(const rtc::Network * network,absl::string_view username,absl::string_view password,const ProtocolAddress & server_address)290 bool CreateTurnPortWithAllParams(const rtc::Network* network,
291 absl::string_view username,
292 absl::string_view password,
293 const ProtocolAddress& server_address) {
294 RelayServerConfig config;
295 config.credentials = RelayCredentials(username, password);
296 CreateRelayPortArgs args;
297 args.network_thread = &main_;
298 args.socket_factory = socket_factory();
299 args.network = network;
300 args.username = kIceUfrag1;
301 args.password = kIcePwd1;
302 args.server_address = &server_address;
303 args.config = &config;
304 args.turn_customizer = turn_customizer_.get();
305 args.field_trials = &field_trials_;
306
307 turn_port_ = TurnPort::Create(args, 0, 0);
308 if (!turn_port_) {
309 return false;
310 }
311 // This TURN port will be the controlling.
312 turn_port_->SetIceRole(ICEROLE_CONTROLLING);
313 turn_port_->SetIceTiebreaker(kTiebreakerDefault);
314 ConnectSignals();
315
316 if (server_address.proto == cricket::PROTO_TLS) {
317 // The test TURN server has a self-signed certificate so will not pass
318 // the normal client validation. Instruct the client to ignore certificate
319 // errors for testing only.
320 turn_port_->SetTlsCertPolicy(
321 TlsCertPolicy::TLS_CERT_POLICY_INSECURE_NO_CHECK);
322 }
323 return true;
324 }
325
CreateSharedTurnPort(absl::string_view username,absl::string_view password,const ProtocolAddress & server_address)326 void CreateSharedTurnPort(absl::string_view username,
327 absl::string_view password,
328 const ProtocolAddress& server_address) {
329 RTC_CHECK(server_address.proto == PROTO_UDP);
330
331 if (!socket_) {
332 socket_.reset(socket_factory()->CreateUdpSocket(
333 rtc::SocketAddress(kLocalAddr1.ipaddr(), 0), 0, 0));
334 ASSERT_TRUE(socket_ != NULL);
335 socket_->SignalReadPacket.connect(this,
336 &TurnPortTest::OnSocketReadPacket);
337 }
338
339 RelayServerConfig config;
340 config.credentials = RelayCredentials(username, password);
341 CreateRelayPortArgs args;
342 args.network_thread = &main_;
343 args.socket_factory = socket_factory();
344 args.network = MakeNetwork(kLocalAddr1);
345 args.username = kIceUfrag1;
346 args.password = kIcePwd1;
347 args.server_address = &server_address;
348 args.config = &config;
349 args.turn_customizer = turn_customizer_.get();
350 args.field_trials = &field_trials_;
351 turn_port_ = TurnPort::Create(args, socket_.get());
352 // This TURN port will be the controlling.
353 turn_port_->SetIceRole(ICEROLE_CONTROLLING);
354 turn_port_->SetIceTiebreaker(kTiebreakerDefault);
355 ConnectSignals();
356 }
357
ConnectSignals()358 void ConnectSignals() {
359 turn_port_->SignalPortComplete.connect(this,
360 &TurnPortTest::OnTurnPortComplete);
361 turn_port_->SignalPortError.connect(this, &TurnPortTest::OnTurnPortError);
362 turn_port_->SignalCandidateError.connect(this,
363 &TurnPortTest::OnCandidateError);
364 turn_port_->SignalUnknownAddress.connect(
365 this, &TurnPortTest::OnTurnUnknownAddress);
366 turn_port_->SubscribePortDestroyed(
367 [this](PortInterface* port) { OnTurnPortDestroyed(port); });
368 turn_port_->SetCallbacksForTest(this);
369 }
370
CreateUdpPort()371 void CreateUdpPort() { CreateUdpPort(kLocalAddr2); }
372
CreateUdpPort(const SocketAddress & address)373 void CreateUdpPort(const SocketAddress& address) {
374 udp_port_ = UDPPort::Create(&main_, socket_factory(), MakeNetwork(address),
375 0, 0, kIceUfrag2, kIcePwd2, false,
376 absl::nullopt, &field_trials_);
377 // UDP port will be controlled.
378 udp_port_->SetIceRole(ICEROLE_CONTROLLED);
379 udp_port_->SetIceTiebreaker(kTiebreakerDefault);
380 udp_port_->SignalPortComplete.connect(this,
381 &TurnPortTest::OnUdpPortComplete);
382 }
383
PrepareTurnAndUdpPorts(ProtocolType protocol_type)384 void PrepareTurnAndUdpPorts(ProtocolType protocol_type) {
385 // turn_port_ should have been created.
386 ASSERT_TRUE(turn_port_ != nullptr);
387 turn_port_->PrepareAddress();
388 ASSERT_TRUE_SIMULATED_WAIT(
389 turn_ready_, TimeToGetTurnCandidate(protocol_type), fake_clock_);
390
391 CreateUdpPort();
392 udp_port_->PrepareAddress();
393 ASSERT_TRUE_SIMULATED_WAIT(udp_ready_, kSimulatedRtt, fake_clock_);
394 }
395
396 // Returns the fake clock time to establish a connection over the given
397 // protocol.
TimeToConnect(ProtocolType protocol_type)398 int TimeToConnect(ProtocolType protocol_type) {
399 switch (protocol_type) {
400 case PROTO_TCP:
401 // The virtual socket server will delay by a fixed half a round trip
402 // for a TCP connection.
403 return kSimulatedRtt / 2;
404 case PROTO_TLS:
405 // TLS operates over TCP and additionally has a round of HELLO for
406 // negotiating ciphers and a round for exchanging certificates.
407 return 2 * kSimulatedRtt + TimeToConnect(PROTO_TCP);
408 case PROTO_UDP:
409 default:
410 // UDP requires no round trips to set up the connection.
411 return 0;
412 }
413 }
414
415 // Returns the total fake clock time to establish a connection with a TURN
416 // server over the given protocol and to allocate a TURN candidate.
TimeToGetTurnCandidate(ProtocolType protocol_type)417 int TimeToGetTurnCandidate(ProtocolType protocol_type) {
418 // For a simple allocation, the first Allocate message will return with an
419 // error asking for credentials and will succeed after the second Allocate
420 // message.
421 return 2 * kSimulatedRtt + TimeToConnect(protocol_type);
422 }
423
424 // Total fake clock time to do the following:
425 // 1. Connect to primary TURN server
426 // 2. Send Allocate and receive a redirect from the primary TURN server
427 // 3. Connect to alternate TURN server
428 // 4. Send Allocate and receive a request for credentials
429 // 5. Send Allocate with credentials and receive allocation
TimeToGetAlternateTurnCandidate(ProtocolType protocol_type)430 int TimeToGetAlternateTurnCandidate(ProtocolType protocol_type) {
431 return 3 * kSimulatedRtt + 2 * TimeToConnect(protocol_type);
432 }
433
CheckConnectionFailedAndPruned(Connection * conn)434 bool CheckConnectionFailedAndPruned(Connection* conn) {
435 return conn && !conn->active() &&
436 conn->state() == IceCandidatePairState::FAILED;
437 }
438
439 // Checks that `turn_port_` has a nonempty set of connections and they are all
440 // failed and pruned.
CheckAllConnectionsFailedAndPruned()441 bool CheckAllConnectionsFailedAndPruned() {
442 auto& connections = turn_port_->connections();
443 if (connections.empty()) {
444 return false;
445 }
446 for (const auto& kv : connections) {
447 if (!CheckConnectionFailedAndPruned(kv.second)) {
448 return false;
449 }
450 }
451 return true;
452 }
453
TestTurnAllocateSucceeds(unsigned int timeout)454 void TestTurnAllocateSucceeds(unsigned int timeout) {
455 ASSERT_TRUE(turn_port_);
456 turn_port_->PrepareAddress();
457 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, timeout, fake_clock_);
458 ASSERT_EQ(1U, turn_port_->Candidates().size());
459 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
460 turn_port_->Candidates()[0].address().ipaddr());
461 EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
462 }
463
TestReconstructedServerUrl(ProtocolType protocol_type,absl::string_view expected_url)464 void TestReconstructedServerUrl(ProtocolType protocol_type,
465 absl::string_view expected_url) {
466 ASSERT_TRUE(turn_port_);
467 turn_port_->PrepareAddress();
468 ASSERT_TRUE_SIMULATED_WAIT(
469 turn_ready_, TimeToGetTurnCandidate(protocol_type), fake_clock_);
470 ASSERT_EQ(1U, turn_port_->Candidates().size());
471 EXPECT_EQ(turn_port_->Candidates()[0].url(), expected_url);
472 }
473
TestTurnAlternateServer(ProtocolType protocol_type)474 void TestTurnAlternateServer(ProtocolType protocol_type) {
475 std::vector<rtc::SocketAddress> redirect_addresses;
476 redirect_addresses.push_back(kTurnAlternateIntAddr);
477
478 TestTurnRedirector redirector(redirect_addresses);
479
480 turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
481 turn_server_.AddInternalSocket(kTurnAlternateIntAddr, protocol_type);
482 turn_server_.set_redirect_hook(&redirector);
483 CreateTurnPort(kTurnUsername, kTurnPassword,
484 ProtocolAddress(kTurnIntAddr, protocol_type));
485
486 // Retrieve the address before we run the state machine.
487 const SocketAddress old_addr = turn_port_->server_address().address;
488
489 turn_port_->PrepareAddress();
490 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_,
491 TimeToGetAlternateTurnCandidate(protocol_type),
492 fake_clock_);
493 // Retrieve the address again, the turn port's address should be
494 // changed.
495 const SocketAddress new_addr = turn_port_->server_address().address;
496 EXPECT_NE(old_addr, new_addr);
497 ASSERT_EQ(1U, turn_port_->Candidates().size());
498 EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
499 turn_port_->Candidates()[0].address().ipaddr());
500 EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
501 }
502
TestTurnAlternateServerV4toV6(ProtocolType protocol_type)503 void TestTurnAlternateServerV4toV6(ProtocolType protocol_type) {
504 std::vector<rtc::SocketAddress> redirect_addresses;
505 redirect_addresses.push_back(kTurnIPv6IntAddr);
506
507 TestTurnRedirector redirector(redirect_addresses);
508 turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
509 turn_server_.set_redirect_hook(&redirector);
510 CreateTurnPort(kTurnUsername, kTurnPassword,
511 ProtocolAddress(kTurnIntAddr, protocol_type));
512 turn_port_->PrepareAddress();
513 // Need time to connect to TURN server, send Allocate request and receive
514 // redirect notice.
515 EXPECT_TRUE_SIMULATED_WAIT(
516 turn_error_, kSimulatedRtt + TimeToConnect(protocol_type), fake_clock_);
517 }
518
TestTurnAlternateServerPingPong(ProtocolType protocol_type)519 void TestTurnAlternateServerPingPong(ProtocolType protocol_type) {
520 std::vector<rtc::SocketAddress> redirect_addresses;
521 redirect_addresses.push_back(kTurnAlternateIntAddr);
522 redirect_addresses.push_back(kTurnIntAddr);
523
524 TestTurnRedirector redirector(redirect_addresses);
525
526 turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
527 turn_server_.AddInternalSocket(kTurnAlternateIntAddr, protocol_type);
528 turn_server_.set_redirect_hook(&redirector);
529 CreateTurnPort(kTurnUsername, kTurnPassword,
530 ProtocolAddress(kTurnIntAddr, protocol_type));
531
532 turn_port_->PrepareAddress();
533 EXPECT_TRUE_SIMULATED_WAIT(turn_error_,
534 TimeToGetAlternateTurnCandidate(protocol_type),
535 fake_clock_);
536 ASSERT_EQ(0U, turn_port_->Candidates().size());
537 rtc::SocketAddress address;
538 // Verify that we have exhausted all alternate servers instead of
539 // failure caused by other errors.
540 EXPECT_FALSE(redirector.ShouldRedirect(address, &address));
541 }
542
TestTurnAlternateServerDetectRepetition(ProtocolType protocol_type)543 void TestTurnAlternateServerDetectRepetition(ProtocolType protocol_type) {
544 std::vector<rtc::SocketAddress> redirect_addresses;
545 redirect_addresses.push_back(kTurnAlternateIntAddr);
546 redirect_addresses.push_back(kTurnAlternateIntAddr);
547
548 TestTurnRedirector redirector(redirect_addresses);
549
550 turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
551 turn_server_.AddInternalSocket(kTurnAlternateIntAddr, protocol_type);
552 turn_server_.set_redirect_hook(&redirector);
553 CreateTurnPort(kTurnUsername, kTurnPassword,
554 ProtocolAddress(kTurnIntAddr, protocol_type));
555
556 turn_port_->PrepareAddress();
557 EXPECT_TRUE_SIMULATED_WAIT(turn_error_,
558 TimeToGetAlternateTurnCandidate(protocol_type),
559 fake_clock_);
560 ASSERT_EQ(0U, turn_port_->Candidates().size());
561 }
562
563 // A certain security exploit works by redirecting to a loopback address,
564 // which doesn't ever actually make sense. So redirects to loopback should
565 // be treated as errors.
566 // See: https://bugs.chromium.org/p/chromium/issues/detail?id=649118
TestTurnAlternateServerLoopback(ProtocolType protocol_type,bool ipv6)567 void TestTurnAlternateServerLoopback(ProtocolType protocol_type, bool ipv6) {
568 const SocketAddress& local_address = ipv6 ? kLocalIPv6Addr : kLocalAddr1;
569 const SocketAddress& server_address =
570 ipv6 ? kTurnIPv6IntAddr : kTurnIntAddr;
571
572 std::vector<rtc::SocketAddress> redirect_addresses;
573 // Pick an unusual address in the 127.0.0.0/8 range to make sure more than
574 // 127.0.0.1 is covered.
575 SocketAddress loopback_address(ipv6 ? "::1" : "127.1.2.3",
576 TURN_SERVER_PORT);
577 redirect_addresses.push_back(loopback_address);
578
579 // Make a socket and bind it to the local port, to make extra sure no
580 // packet is sent to this address.
581 std::unique_ptr<rtc::Socket> loopback_socket(ss_->CreateSocket(
582 AF_INET, protocol_type == PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM));
583 ASSERT_NE(nullptr, loopback_socket.get());
584 ASSERT_EQ(0, loopback_socket->Bind(loopback_address));
585 if (protocol_type == PROTO_TCP) {
586 ASSERT_EQ(0, loopback_socket->Listen(1));
587 }
588
589 TestTurnRedirector redirector(redirect_addresses);
590
591 turn_server_.AddInternalSocket(server_address, protocol_type);
592 turn_server_.set_redirect_hook(&redirector);
593 CreateTurnPort(local_address, kTurnUsername, kTurnPassword,
594 ProtocolAddress(server_address, protocol_type));
595
596 turn_port_->PrepareAddress();
597 EXPECT_TRUE_SIMULATED_WAIT(
598 turn_error_, TimeToGetTurnCandidate(protocol_type), fake_clock_);
599
600 // Wait for some extra time, and make sure no packets were received on the
601 // loopback port we created (or in the case of TCP, no connection attempt
602 // occurred).
603 SIMULATED_WAIT(false, kSimulatedRtt, fake_clock_);
604 if (protocol_type == PROTO_UDP) {
605 char buf[1];
606 EXPECT_EQ(-1, loopback_socket->Recv(&buf, 1, nullptr));
607 } else {
608 std::unique_ptr<rtc::Socket> accepted_socket(
609 loopback_socket->Accept(nullptr));
610 EXPECT_EQ(nullptr, accepted_socket.get());
611 }
612 }
613
TestTurnConnection(ProtocolType protocol_type)614 void TestTurnConnection(ProtocolType protocol_type) {
615 // Create ports and prepare addresses.
616 PrepareTurnAndUdpPorts(protocol_type);
617
618 // Send ping from UDP to TURN.
619 ASSERT_GE(turn_port_->Candidates().size(), 1U);
620 Connection* conn1 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
621 Port::ORIGIN_MESSAGE);
622 ASSERT_TRUE(conn1 != NULL);
623 conn1->Ping(0);
624 SIMULATED_WAIT(!turn_unknown_address_, kSimulatedRtt * 2, fake_clock_);
625 EXPECT_FALSE(turn_unknown_address_);
626 EXPECT_FALSE(conn1->receiving());
627 EXPECT_EQ(Connection::STATE_WRITE_INIT, conn1->write_state());
628
629 // Send ping from TURN to UDP.
630 Connection* conn2 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
631 Port::ORIGIN_MESSAGE);
632 ASSERT_TRUE(conn2 != NULL);
633 ASSERT_TRUE_SIMULATED_WAIT(turn_create_permission_success_, kSimulatedRtt,
634 fake_clock_);
635 conn2->Ping(0);
636
637 // Two hops from TURN port to UDP port through TURN server, thus two RTTs.
638 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn2->write_state(),
639 kSimulatedRtt * 2, fake_clock_);
640 EXPECT_TRUE(conn1->receiving());
641 EXPECT_TRUE(conn2->receiving());
642 EXPECT_EQ(Connection::STATE_WRITE_INIT, conn1->write_state());
643
644 // Send another ping from UDP to TURN.
645 conn1->Ping(0);
646 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn1->write_state(),
647 kSimulatedRtt * 2, fake_clock_);
648 EXPECT_TRUE(conn2->receiving());
649 }
650
TestDestroyTurnConnection()651 void TestDestroyTurnConnection() {
652 PrepareTurnAndUdpPorts(PROTO_UDP);
653
654 // Create connections on both ends.
655 Connection* conn1 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
656 Port::ORIGIN_MESSAGE);
657 Connection* conn2 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
658 Port::ORIGIN_MESSAGE);
659
660 // Increased to 10 minutes, to ensure that the TurnEntry times out before
661 // the TurnPort.
662 turn_port_->set_timeout_delay(10 * 60 * 1000);
663
664 ASSERT_TRUE(conn2 != NULL);
665 ASSERT_TRUE_SIMULATED_WAIT(turn_create_permission_success_, kSimulatedRtt,
666 fake_clock_);
667 // Make sure turn connection can receive.
668 conn1->Ping(0);
669 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn1->write_state(),
670 kSimulatedRtt * 2, fake_clock_);
671 EXPECT_FALSE(turn_unknown_address_);
672
673 // Destroy the connection on the TURN port. The TurnEntry still exists, so
674 // the TURN port should still process a ping from an unknown address.
675 turn_port_->DestroyConnection(conn2);
676
677 conn1->Ping(0);
678 EXPECT_TRUE_SIMULATED_WAIT(turn_unknown_address_, kSimulatedRtt,
679 fake_clock_);
680
681 // Wait for TurnEntry to expire. Timeout is 5 minutes.
682 // Expect that it still processes an incoming ping and signals the
683 // unknown address.
684 turn_unknown_address_ = false;
685 fake_clock_.AdvanceTime(webrtc::TimeDelta::Seconds(5 * 60));
686 conn1->Ping(0);
687 EXPECT_TRUE_SIMULATED_WAIT(turn_unknown_address_, kSimulatedRtt,
688 fake_clock_);
689
690 // If the connection is created again, it will start to receive pings.
691 conn2 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
692 Port::ORIGIN_MESSAGE);
693 conn1->Ping(0);
694 EXPECT_TRUE_SIMULATED_WAIT(conn2->receiving(), kSimulatedRtt, fake_clock_);
695 }
696
TestTurnSendData(ProtocolType protocol_type)697 void TestTurnSendData(ProtocolType protocol_type) {
698 PrepareTurnAndUdpPorts(protocol_type);
699
700 // Create connections and send pings.
701 Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
702 Port::ORIGIN_MESSAGE);
703 Connection* conn2 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
704 Port::ORIGIN_MESSAGE);
705 ASSERT_TRUE(conn1 != NULL);
706 ASSERT_TRUE(conn2 != NULL);
707 conn1->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
708 &TurnPortTest::OnTurnReadPacket);
709 conn2->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
710 &TurnPortTest::OnUdpReadPacket);
711 conn1->Ping(0);
712 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn1->write_state(),
713 kSimulatedRtt * 2, fake_clock_);
714 conn2->Ping(0);
715 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn2->write_state(),
716 kSimulatedRtt * 2, fake_clock_);
717
718 // Send some data.
719 size_t num_packets = 256;
720 for (size_t i = 0; i < num_packets; ++i) {
721 unsigned char buf[256] = {0};
722 for (size_t j = 0; j < i + 1; ++j) {
723 buf[j] = 0xFF - static_cast<unsigned char>(j);
724 }
725 conn1->Send(buf, i + 1, options);
726 conn2->Send(buf, i + 1, options);
727 SIMULATED_WAIT(false, kSimulatedRtt, fake_clock_);
728 }
729
730 // Check the data.
731 ASSERT_EQ(num_packets, turn_packets_.size());
732 ASSERT_EQ(num_packets, udp_packets_.size());
733 for (size_t i = 0; i < num_packets; ++i) {
734 EXPECT_EQ(i + 1, turn_packets_[i].size());
735 EXPECT_EQ(i + 1, udp_packets_[i].size());
736 EXPECT_EQ(turn_packets_[i], udp_packets_[i]);
737 }
738 }
739
740 // Test that a TURN allocation is released when the port is closed.
TestTurnReleaseAllocation(ProtocolType protocol_type)741 void TestTurnReleaseAllocation(ProtocolType protocol_type) {
742 PrepareTurnAndUdpPorts(protocol_type);
743 turn_port_.reset();
744 EXPECT_EQ_SIMULATED_WAIT(0U, turn_server_.server()->allocations().size(),
745 kSimulatedRtt, fake_clock_);
746 }
747
748 // Test that the TURN allocation is released by sending a refresh request
749 // with lifetime 0 when Release is called.
TestTurnGracefulReleaseAllocation(ProtocolType protocol_type)750 void TestTurnGracefulReleaseAllocation(ProtocolType protocol_type) {
751 PrepareTurnAndUdpPorts(protocol_type);
752
753 // Create connections and send pings.
754 Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
755 Port::ORIGIN_MESSAGE);
756 Connection* conn2 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
757 Port::ORIGIN_MESSAGE);
758 ASSERT_TRUE(conn1 != NULL);
759 ASSERT_TRUE(conn2 != NULL);
760 conn1->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
761 &TurnPortTest::OnTurnReadPacket);
762 conn2->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
763 &TurnPortTest::OnUdpReadPacket);
764 conn1->Ping(0);
765 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn1->write_state(),
766 kSimulatedRtt * 2, fake_clock_);
767 conn2->Ping(0);
768 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn2->write_state(),
769 kSimulatedRtt * 2, fake_clock_);
770
771 // Send some data from Udp to TurnPort.
772 unsigned char buf[256] = {0};
773 conn2->Send(buf, sizeof(buf), options);
774
775 // Now release the TurnPort allocation.
776 // This will send a REFRESH with lifetime 0 to server.
777 turn_port_->Release();
778
779 // Wait for the TurnPort to signal closed.
780 ASSERT_TRUE_SIMULATED_WAIT(turn_port_closed_, kSimulatedRtt, fake_clock_);
781
782 // But the data should have arrived first.
783 ASSERT_EQ(1ul, turn_packets_.size());
784 EXPECT_EQ(sizeof(buf), turn_packets_[0].size());
785
786 // The allocation is released at server.
787 EXPECT_EQ(0U, turn_server_.server()->allocations().size());
788 }
789
790 protected:
socket_factory()791 virtual rtc::PacketSocketFactory* socket_factory() {
792 return &socket_factory_;
793 }
794
795 webrtc::test::ScopedKeyValueConfig field_trials_;
796 rtc::ScopedFakeClock fake_clock_;
797 // When a "create port" helper method is called with an IP, we create a
798 // Network with that IP and add it to this list. Using a list instead of a
799 // vector so that when it grows, pointers aren't invalidated.
800 std::list<rtc::Network> networks_;
801 std::unique_ptr<TurnPortTestVirtualSocketServer> ss_;
802 rtc::AutoSocketServerThread main_;
803 std::unique_ptr<rtc::AsyncPacketSocket> socket_;
804 TestTurnServer turn_server_;
805 std::unique_ptr<TurnPort> turn_port_;
806 std::unique_ptr<UDPPort> udp_port_;
807 bool turn_ready_ = false;
808 bool turn_error_ = false;
809 bool turn_unknown_address_ = false;
810 bool turn_create_permission_success_ = false;
811 bool turn_port_closed_ = false;
812 bool turn_port_destroyed_ = false;
813 bool udp_ready_ = false;
814 bool test_finish_ = false;
815 bool turn_refresh_success_ = false;
816 std::vector<rtc::Buffer> turn_packets_;
817 std::vector<rtc::Buffer> udp_packets_;
818 rtc::PacketOptions options;
819 std::unique_ptr<webrtc::TurnCustomizer> turn_customizer_;
820 cricket::IceCandidateErrorEvent error_event_;
821
822 private:
823 rtc::BasicPacketSocketFactory socket_factory_;
824 };
825
TEST_F(TurnPortTest,TestTurnPortType)826 TEST_F(TurnPortTest, TestTurnPortType) {
827 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
828 EXPECT_EQ(cricket::RELAY_PORT_TYPE, turn_port_->Type());
829 }
830
831 // Tests that the URL of the servers can be correctly reconstructed when
832 // gathering the candidates.
TEST_F(TurnPortTest,TestReconstructedServerUrlForUdpIPv4)833 TEST_F(TurnPortTest, TestReconstructedServerUrlForUdpIPv4) {
834 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
835 TestReconstructedServerUrl(PROTO_UDP, "turn:99.99.99.3:3478?transport=udp");
836 }
837
TEST_F(TurnPortTest,TestReconstructedServerUrlForUdpIPv6)838 TEST_F(TurnPortTest, TestReconstructedServerUrlForUdpIPv6) {
839 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
840 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
841 kTurnUdpIPv6ProtoAddr);
842 TestReconstructedServerUrl(
843 PROTO_UDP,
844 "turn:2400:4030:1:2c00:be30:abcd:efab:cdef:3478?transport=udp");
845 }
846
TEST_F(TurnPortTest,TestReconstructedServerUrlForTcp)847 TEST_F(TurnPortTest, TestReconstructedServerUrlForTcp) {
848 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
849 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
850 TestReconstructedServerUrl(PROTO_TCP, "turn:99.99.99.4:3478?transport=tcp");
851 }
852
TEST_F(TurnPortTest,TestReconstructedServerUrlForTls)853 TEST_F(TurnPortTest, TestReconstructedServerUrlForTls) {
854 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
855 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
856 TestReconstructedServerUrl(PROTO_TLS, "turns:99.99.99.4:3478?transport=tcp");
857 }
858
TEST_F(TurnPortTest,TestReconstructedServerUrlForHostname)859 TEST_F(TurnPortTest, TestReconstructedServerUrlForHostname) {
860 CreateTurnPort(kTurnUsername, kTurnPassword,
861 kTurnPortInvalidHostnameProtoAddr);
862 // This test follows the pattern from TestTurnTcpOnAddressResolveFailure.
863 // As VSS doesn't provide DNS resolution, name resolve will fail,
864 // the error will be set and contain the url.
865 turn_port_->PrepareAddress();
866 EXPECT_TRUE_WAIT(turn_error_, kResolverTimeout);
867 std::string server_url =
868 "turn:" + kTurnInvalidAddr.ToString() + "?transport=udp";
869 ASSERT_EQ(error_event_.url, server_url);
870 }
871
872 // Do a normal TURN allocation.
TEST_F(TurnPortTest,TestTurnAllocate)873 TEST_F(TurnPortTest, TestTurnAllocate) {
874 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
875 EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10 * 1024));
876 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
877 }
878
879 class TurnLoggingIdValidator : public StunMessageObserver {
880 public:
TurnLoggingIdValidator(const char * expect_val)881 explicit TurnLoggingIdValidator(const char* expect_val)
882 : expect_val_(expect_val) {}
~TurnLoggingIdValidator()883 ~TurnLoggingIdValidator() {}
ReceivedMessage(const TurnMessage * msg)884 void ReceivedMessage(const TurnMessage* msg) override {
885 if (msg->type() == cricket::STUN_ALLOCATE_REQUEST) {
886 const StunByteStringAttribute* attr =
887 msg->GetByteString(cricket::STUN_ATTR_TURN_LOGGING_ID);
888 if (expect_val_) {
889 ASSERT_NE(nullptr, attr);
890 ASSERT_EQ(expect_val_, attr->string_view());
891 } else {
892 EXPECT_EQ(nullptr, attr);
893 }
894 }
895 }
ReceivedChannelData(const char * data,size_t size)896 void ReceivedChannelData(const char* data, size_t size) override {}
897
898 private:
899 const char* expect_val_;
900 };
901
TEST_F(TurnPortTest,TestTurnAllocateWithLoggingId)902 TEST_F(TurnPortTest, TestTurnAllocateWithLoggingId) {
903 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
904 turn_port_->SetTurnLoggingId("KESO");
905 turn_server_.server()->SetStunMessageObserver(
906 std::make_unique<TurnLoggingIdValidator>("KESO"));
907 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
908 }
909
TEST_F(TurnPortTest,TestTurnAllocateWithoutLoggingId)910 TEST_F(TurnPortTest, TestTurnAllocateWithoutLoggingId) {
911 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
912 turn_server_.server()->SetStunMessageObserver(
913 std::make_unique<TurnLoggingIdValidator>(nullptr));
914 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
915 }
916
917 // Test bad credentials.
TEST_F(TurnPortTest,TestTurnBadCredentials)918 TEST_F(TurnPortTest, TestTurnBadCredentials) {
919 CreateTurnPort(kTurnUsername, "bad", kTurnUdpProtoAddr);
920 turn_port_->PrepareAddress();
921 EXPECT_TRUE_SIMULATED_WAIT(turn_error_, kSimulatedRtt * 3, fake_clock_);
922 ASSERT_EQ(0U, turn_port_->Candidates().size());
923 EXPECT_EQ_SIMULATED_WAIT(error_event_.error_code, STUN_ERROR_UNAUTHORIZED,
924 kSimulatedRtt * 3, fake_clock_);
925 EXPECT_EQ(error_event_.error_text, "Unauthorized");
926 }
927
928 // Testing a normal UDP allocation using TCP connection.
TEST_F(TurnPortTest,TestTurnTcpAllocate)929 TEST_F(TurnPortTest, TestTurnTcpAllocate) {
930 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
931 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
932 EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10 * 1024));
933 TestTurnAllocateSucceeds(kSimulatedRtt * 3);
934 }
935
936 // Test case for WebRTC issue 3927 where a proxy binds to the local host address
937 // instead the address that TurnPort originally bound to. The candidate pair
938 // impacted by this behavior should still be used.
TEST_F(TurnPortTest,TestTurnTcpAllocationWhenProxyChangesAddressToLocalHost)939 TEST_F(TurnPortTest, TestTurnTcpAllocationWhenProxyChangesAddressToLocalHost) {
940 SocketAddress local_address("127.0.0.1", 0);
941 // After calling this, when TurnPort attempts to get a socket bound to
942 // kLocalAddr, it will end up using localhost instead.
943 ss_->SetAlternativeLocalAddress(kLocalAddr1.ipaddr(), local_address.ipaddr());
944
945 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
946 CreateTurnPort(kLocalAddr1, kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
947 EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10 * 1024));
948 TestTurnAllocateSucceeds(kSimulatedRtt * 3);
949
950 // Verify that the socket actually used localhost, otherwise this test isn't
951 // doing what it meant to.
952 ASSERT_EQ(local_address.ipaddr(),
953 turn_port_->Candidates()[0].related_address().ipaddr());
954 }
955
956 // If the address the socket ends up bound to does not match any address of the
957 // TurnPort's Network, then the socket should be discarded and no candidates
958 // should be signaled. In the context of ICE, where one TurnPort is created for
959 // each Network, when this happens it's likely that the unexpected address is
960 // associated with some other Network, which another TurnPort is already
961 // covering.
TEST_F(TurnPortTest,TurnTcpAllocationDiscardedIfBoundAddressDoesNotMatchNetwork)962 TEST_F(TurnPortTest,
963 TurnTcpAllocationDiscardedIfBoundAddressDoesNotMatchNetwork) {
964 // Sockets bound to kLocalAddr1 will actually end up with kLocalAddr2.
965 ss_->SetAlternativeLocalAddress(kLocalAddr1.ipaddr(), kLocalAddr2.ipaddr());
966
967 // Set up TURN server to use TCP (this logic only exists for TCP).
968 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
969
970 // Create TURN port and tell it to start allocation.
971 CreateTurnPort(kLocalAddr1, kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
972 turn_port_->PrepareAddress();
973
974 // Shouldn't take more than 1 RTT to realize the bound address isn't the one
975 // expected.
976 EXPECT_TRUE_SIMULATED_WAIT(turn_error_, kSimulatedRtt, fake_clock_);
977 EXPECT_EQ_SIMULATED_WAIT(error_event_.error_code, STUN_ERROR_GLOBAL_FAILURE,
978 kSimulatedRtt, fake_clock_);
979 ASSERT_NE(error_event_.error_text.find('.'), std::string::npos);
980 ASSERT_NE(error_event_.address.find(kLocalAddr2.HostAsSensitiveURIString()),
981 std::string::npos);
982 ASSERT_NE(error_event_.port, 0);
983 std::string server_url =
984 "turn:" + kTurnTcpIntAddr.ToString() + "?transport=tcp";
985 ASSERT_EQ(error_event_.url, server_url);
986 }
987
988 // A caveat for the above logic: if the socket ends up bound to one of the IPs
989 // associated with the Network, just not the "best" one, this is ok.
TEST_F(TurnPortTest,TurnTcpAllocationNotDiscardedIfNotBoundToBestIP)990 TEST_F(TurnPortTest, TurnTcpAllocationNotDiscardedIfNotBoundToBestIP) {
991 // Sockets bound to kLocalAddr1 will actually end up with kLocalAddr2.
992 ss_->SetAlternativeLocalAddress(kLocalAddr1.ipaddr(), kLocalAddr2.ipaddr());
993
994 // Set up a network with kLocalAddr1 as the "best" IP, and kLocalAddr2 as an
995 // alternate.
996 rtc::Network* network = MakeNetwork(kLocalAddr1);
997 network->AddIP(kLocalAddr2.ipaddr());
998 ASSERT_EQ(kLocalAddr1.ipaddr(), network->GetBestIP());
999
1000 // Set up TURN server to use TCP (this logic only exists for TCP).
1001 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1002
1003 // Create TURN port using our special Network, and tell it to start
1004 // allocation.
1005 CreateTurnPortWithNetwork(network, kTurnUsername, kTurnPassword,
1006 kTurnTcpProtoAddr);
1007 turn_port_->PrepareAddress();
1008
1009 // Candidate should be gathered as normally.
1010 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 3, fake_clock_);
1011 ASSERT_EQ(1U, turn_port_->Candidates().size());
1012
1013 // Verify that the socket actually used the alternate address, otherwise this
1014 // test isn't doing what it meant to.
1015 ASSERT_EQ(kLocalAddr2.ipaddr(),
1016 turn_port_->Candidates()[0].related_address().ipaddr());
1017 }
1018
1019 // Regression test for crbug.com/webrtc/8972, caused by buggy comparison
1020 // between rtc::IPAddress and rtc::InterfaceAddress.
TEST_F(TurnPortTest,TCPPortNotDiscardedIfBoundToTemporaryIP)1021 TEST_F(TurnPortTest, TCPPortNotDiscardedIfBoundToTemporaryIP) {
1022 networks_.emplace_back("unittest", "unittest", kLocalIPv6Addr.ipaddr(), 32);
1023 networks_.back().AddIP(rtc::InterfaceAddress(
1024 kLocalIPv6Addr.ipaddr(), rtc::IPV6_ADDRESS_FLAG_TEMPORARY));
1025
1026 // Set up TURN server to use TCP (this logic only exists for TCP).
1027 turn_server_.AddInternalSocket(kTurnIPv6IntAddr, PROTO_TCP);
1028
1029 // Create TURN port using our special Network, and tell it to start
1030 // allocation.
1031 CreateTurnPortWithNetwork(
1032 &networks_.back(), kTurnUsername, kTurnPassword,
1033 cricket::ProtocolAddress(kTurnIPv6IntAddr, PROTO_TCP));
1034 turn_port_->PrepareAddress();
1035
1036 // Candidate should be gathered as normally.
1037 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 3, fake_clock_);
1038 ASSERT_EQ(1U, turn_port_->Candidates().size());
1039 }
1040
1041 // Testing turn port will attempt to create TCP socket on address resolution
1042 // failure.
TEST_F(TurnPortTest,TestTurnTcpOnAddressResolveFailure)1043 TEST_F(TurnPortTest, TestTurnTcpOnAddressResolveFailure) {
1044 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1045 CreateTurnPort(kTurnUsername, kTurnPassword,
1046 ProtocolAddress(kTurnInvalidAddr, PROTO_TCP));
1047 turn_port_->PrepareAddress();
1048 EXPECT_TRUE_WAIT(turn_error_, kResolverTimeout);
1049 // As VSS doesn't provide DNS resolution, name resolve will fail. TurnPort
1050 // will proceed in creating a TCP socket which will fail as there is no
1051 // server on the above domain and error will be set to SOCKET_ERROR.
1052 EXPECT_EQ(SOCKET_ERROR, turn_port_->error());
1053 EXPECT_EQ_SIMULATED_WAIT(error_event_.error_code, SERVER_NOT_REACHABLE_ERROR,
1054 kSimulatedRtt, fake_clock_);
1055 std::string server_url =
1056 "turn:" + kTurnInvalidAddr.ToString() + "?transport=tcp";
1057 ASSERT_EQ(error_event_.url, server_url);
1058 }
1059
1060 // Testing turn port will attempt to create TLS socket on address resolution
1061 // failure.
TEST_F(TurnPortTest,TestTurnTlsOnAddressResolveFailure)1062 TEST_F(TurnPortTest, TestTurnTlsOnAddressResolveFailure) {
1063 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1064 CreateTurnPort(kTurnUsername, kTurnPassword,
1065 ProtocolAddress(kTurnInvalidAddr, PROTO_TLS));
1066 turn_port_->PrepareAddress();
1067 EXPECT_TRUE_WAIT(turn_error_, kResolverTimeout);
1068 EXPECT_EQ(SOCKET_ERROR, turn_port_->error());
1069 }
1070
1071 // In case of UDP on address resolve failure, TurnPort will not create socket
1072 // and return allocate failure.
TEST_F(TurnPortTest,TestTurnUdpOnAddressResolveFailure)1073 TEST_F(TurnPortTest, TestTurnUdpOnAddressResolveFailure) {
1074 CreateTurnPort(kTurnUsername, kTurnPassword,
1075 ProtocolAddress(kTurnInvalidAddr, PROTO_UDP));
1076 turn_port_->PrepareAddress();
1077 EXPECT_TRUE_WAIT(turn_error_, kResolverTimeout);
1078 // Error from turn port will not be socket error.
1079 EXPECT_NE(SOCKET_ERROR, turn_port_->error());
1080 }
1081
1082 // Try to do a TURN allocation with an invalid password.
TEST_F(TurnPortTest,TestTurnAllocateBadPassword)1083 TEST_F(TurnPortTest, TestTurnAllocateBadPassword) {
1084 CreateTurnPort(kTurnUsername, "bad", kTurnUdpProtoAddr);
1085 turn_port_->PrepareAddress();
1086 EXPECT_TRUE_SIMULATED_WAIT(turn_error_, kSimulatedRtt * 2, fake_clock_);
1087 ASSERT_EQ(0U, turn_port_->Candidates().size());
1088 }
1089
1090 // Tests that TURN port nonce will be reset when receiving an ALLOCATE MISMATCH
1091 // error.
TEST_F(TurnPortTest,TestTurnAllocateNonceResetAfterAllocateMismatch)1092 TEST_F(TurnPortTest, TestTurnAllocateNonceResetAfterAllocateMismatch) {
1093 // Do a normal allocation first.
1094 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1095 turn_port_->PrepareAddress();
1096 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 2, fake_clock_);
1097 rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
1098 // Destroy the turnport while keeping the drop probability to 1 to
1099 // suppress the release of the allocation at the server.
1100 ss_->set_drop_probability(1.0);
1101 turn_port_.reset();
1102 SIMULATED_WAIT(false, kSimulatedRtt, fake_clock_);
1103 ss_->set_drop_probability(0.0);
1104
1105 // Force the socket server to assign the same port.
1106 ss_->SetNextPortForTesting(first_addr.port());
1107 turn_ready_ = false;
1108 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1109
1110 // It is expected that the turn port will first get a nonce from the server
1111 // using timestamp `ts_before` but then get an allocate mismatch error and
1112 // receive an even newer nonce based on the system clock. `ts_before` is
1113 // chosen so that the two NONCEs generated by the server will be different.
1114 int64_t ts_before = rtc::TimeMillis() - 1;
1115 std::string first_nonce =
1116 turn_server_.server()->SetTimestampForNextNonce(ts_before);
1117 turn_port_->PrepareAddress();
1118
1119 // Four round trips; first we'll get "stale nonce", then
1120 // "allocate mismatch", then "stale nonce" again, then finally it will
1121 // succeed.
1122 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 4, fake_clock_);
1123 EXPECT_NE(first_nonce, turn_port_->nonce());
1124 }
1125
1126 // Tests that a new local address is created after
1127 // STUN_ERROR_ALLOCATION_MISMATCH.
TEST_F(TurnPortTest,TestTurnAllocateMismatch)1128 TEST_F(TurnPortTest, TestTurnAllocateMismatch) {
1129 // Do a normal allocation first.
1130 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1131 turn_port_->PrepareAddress();
1132 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 2, fake_clock_);
1133 rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
1134
1135 // Clear connected_ flag on turnport to suppress the release of
1136 // the allocation.
1137 turn_port_->OnSocketClose(turn_port_->socket(), 0);
1138
1139 // Forces the socket server to assign the same port.
1140 ss_->SetNextPortForTesting(first_addr.port());
1141
1142 turn_ready_ = false;
1143 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1144 turn_port_->PrepareAddress();
1145
1146 // Verifies that the new port has the same address.
1147 EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
1148
1149 // Four round trips; first we'll get "stale nonce", then
1150 // "allocate mismatch", then "stale nonce" again, then finally it will
1151 // succeed.
1152 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 4, fake_clock_);
1153
1154 // Verifies that the new port has a different address now.
1155 EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
1156
1157 // Verify that all packets received from the shared socket are ignored.
1158 std::string test_packet = "Test packet";
1159 EXPECT_FALSE(turn_port_->HandleIncomingPacket(
1160 socket_.get(), test_packet.data(), test_packet.size(),
1161 rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0), rtc::TimeMicros()));
1162 }
1163
1164 // Tests that a shared-socket-TurnPort creates its own socket after
1165 // STUN_ERROR_ALLOCATION_MISMATCH.
TEST_F(TurnPortTest,TestSharedSocketAllocateMismatch)1166 TEST_F(TurnPortTest, TestSharedSocketAllocateMismatch) {
1167 // Do a normal allocation first.
1168 CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1169 turn_port_->PrepareAddress();
1170 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 2, fake_clock_);
1171 rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
1172
1173 // Clear connected_ flag on turnport to suppress the release of
1174 // the allocation.
1175 turn_port_->OnSocketClose(turn_port_->socket(), 0);
1176
1177 turn_ready_ = false;
1178 CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1179
1180 // Verifies that the new port has the same address.
1181 EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
1182 EXPECT_TRUE(turn_port_->SharedSocket());
1183
1184 turn_port_->PrepareAddress();
1185 // Extra 2 round trips due to allocate mismatch.
1186 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 4, fake_clock_);
1187
1188 // Verifies that the new port has a different address now.
1189 EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
1190 EXPECT_FALSE(turn_port_->SharedSocket());
1191 }
1192
TEST_F(TurnPortTest,TestTurnTcpAllocateMismatch)1193 TEST_F(TurnPortTest, TestTurnTcpAllocateMismatch) {
1194 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1195 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1196
1197 // Do a normal allocation first.
1198 turn_port_->PrepareAddress();
1199 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 3, fake_clock_);
1200 rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
1201
1202 // Clear connected_ flag on turnport to suppress the release of
1203 // the allocation.
1204 turn_port_->OnSocketClose(turn_port_->socket(), 0);
1205
1206 // Forces the socket server to assign the same port.
1207 ss_->SetNextPortForTesting(first_addr.port());
1208
1209 turn_ready_ = false;
1210 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1211 turn_port_->PrepareAddress();
1212
1213 // Verifies that the new port has the same address.
1214 EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
1215
1216 // Extra 2 round trips due to allocate mismatch.
1217 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 5, fake_clock_);
1218
1219 // Verifies that the new port has a different address now.
1220 EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
1221 }
1222
TEST_F(TurnPortTest,TestRefreshRequestGetsErrorResponse)1223 TEST_F(TurnPortTest, TestRefreshRequestGetsErrorResponse) {
1224 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1225 PrepareTurnAndUdpPorts(PROTO_UDP);
1226 turn_port_->CreateConnection(udp_port_->Candidates()[0],
1227 Port::ORIGIN_MESSAGE);
1228 // Set bad credentials.
1229 RelayCredentials bad_credentials("bad_user", "bad_pwd");
1230 turn_port_->set_credentials(bad_credentials);
1231 turn_refresh_success_ = false;
1232 // This sends out the first RefreshRequest with correct credentials.
1233 // When this succeeds, it will schedule a new RefreshRequest with the bad
1234 // credential.
1235 turn_port_->request_manager().FlushForTest(TURN_REFRESH_REQUEST);
1236 EXPECT_TRUE_SIMULATED_WAIT(turn_refresh_success_, kSimulatedRtt, fake_clock_);
1237 // Flush it again, it will receive a bad response.
1238 turn_port_->request_manager().FlushForTest(TURN_REFRESH_REQUEST);
1239 EXPECT_TRUE_SIMULATED_WAIT(!turn_refresh_success_, kSimulatedRtt,
1240 fake_clock_);
1241 EXPECT_FALSE(turn_port_->connected());
1242 EXPECT_TRUE(CheckAllConnectionsFailedAndPruned());
1243 EXPECT_FALSE(turn_port_->HasRequests());
1244 }
1245
1246 // Test that TurnPort will not handle any incoming packets once it has been
1247 // closed.
TEST_F(TurnPortTest,TestStopProcessingPacketsAfterClosed)1248 TEST_F(TurnPortTest, TestStopProcessingPacketsAfterClosed) {
1249 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1250 PrepareTurnAndUdpPorts(PROTO_UDP);
1251 Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1252 Port::ORIGIN_MESSAGE);
1253 Connection* conn2 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
1254 Port::ORIGIN_MESSAGE);
1255 ASSERT_TRUE(conn1 != NULL);
1256 ASSERT_TRUE(conn2 != NULL);
1257 // Make sure conn2 is writable.
1258 conn2->Ping(0);
1259 EXPECT_EQ_SIMULATED_WAIT(Connection::STATE_WRITABLE, conn2->write_state(),
1260 kSimulatedRtt * 2, fake_clock_);
1261
1262 turn_port_->CloseForTest();
1263 SIMULATED_WAIT(false, kSimulatedRtt, fake_clock_);
1264 turn_unknown_address_ = false;
1265 conn2->Ping(0);
1266 SIMULATED_WAIT(false, kSimulatedRtt, fake_clock_);
1267 // Since the turn port does not handle packets any more, it should not
1268 // SignalUnknownAddress.
1269 EXPECT_FALSE(turn_unknown_address_);
1270 }
1271
1272 // Test that CreateConnection will return null if port becomes disconnected.
TEST_F(TurnPortTest,TestCreateConnectionWhenSocketClosed)1273 TEST_F(TurnPortTest, TestCreateConnectionWhenSocketClosed) {
1274 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1275 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1276 PrepareTurnAndUdpPorts(PROTO_TCP);
1277 // Create a connection.
1278 Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1279 Port::ORIGIN_MESSAGE);
1280 ASSERT_TRUE(conn1 != NULL);
1281
1282 // Close the socket and create a connection again.
1283 turn_port_->OnSocketClose(turn_port_->socket(), 1);
1284 conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1285 Port::ORIGIN_MESSAGE);
1286 ASSERT_TRUE(conn1 == NULL);
1287 }
1288
1289 // Tests that when a TCP socket is closed, the respective TURN connection will
1290 // be destroyed.
TEST_F(TurnPortTest,TestSocketCloseWillDestroyConnection)1291 TEST_F(TurnPortTest, TestSocketCloseWillDestroyConnection) {
1292 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1293 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1294 PrepareTurnAndUdpPorts(PROTO_TCP);
1295 Connection* conn = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1296 Port::ORIGIN_MESSAGE);
1297 EXPECT_NE(nullptr, conn);
1298 EXPECT_TRUE(!turn_port_->connections().empty());
1299 turn_port_->socket()->NotifyClosedForTest(1);
1300 EXPECT_TRUE_SIMULATED_WAIT(turn_port_->connections().empty(),
1301 kConnectionDestructionDelay, fake_clock_);
1302 }
1303
1304 // Test try-alternate-server feature.
TEST_F(TurnPortTest,TestTurnAlternateServerUDP)1305 TEST_F(TurnPortTest, TestTurnAlternateServerUDP) {
1306 TestTurnAlternateServer(PROTO_UDP);
1307 }
1308
TEST_F(TurnPortTest,TestTurnAlternateServerTCP)1309 TEST_F(TurnPortTest, TestTurnAlternateServerTCP) {
1310 TestTurnAlternateServer(PROTO_TCP);
1311 }
1312
TEST_F(TurnPortTest,TestTurnAlternateServerTLS)1313 TEST_F(TurnPortTest, TestTurnAlternateServerTLS) {
1314 TestTurnAlternateServer(PROTO_TLS);
1315 }
1316
1317 // Test that we fail when we redirect to an address different from
1318 // current IP family.
TEST_F(TurnPortTest,TestTurnAlternateServerV4toV6UDP)1319 TEST_F(TurnPortTest, TestTurnAlternateServerV4toV6UDP) {
1320 TestTurnAlternateServerV4toV6(PROTO_UDP);
1321 }
1322
TEST_F(TurnPortTest,TestTurnAlternateServerV4toV6TCP)1323 TEST_F(TurnPortTest, TestTurnAlternateServerV4toV6TCP) {
1324 TestTurnAlternateServerV4toV6(PROTO_TCP);
1325 }
1326
TEST_F(TurnPortTest,TestTurnAlternateServerV4toV6TLS)1327 TEST_F(TurnPortTest, TestTurnAlternateServerV4toV6TLS) {
1328 TestTurnAlternateServerV4toV6(PROTO_TLS);
1329 }
1330
1331 // Test try-alternate-server catches the case of pingpong.
TEST_F(TurnPortTest,TestTurnAlternateServerPingPongUDP)1332 TEST_F(TurnPortTest, TestTurnAlternateServerPingPongUDP) {
1333 TestTurnAlternateServerPingPong(PROTO_UDP);
1334 }
1335
TEST_F(TurnPortTest,TestTurnAlternateServerPingPongTCP)1336 TEST_F(TurnPortTest, TestTurnAlternateServerPingPongTCP) {
1337 TestTurnAlternateServerPingPong(PROTO_TCP);
1338 }
1339
TEST_F(TurnPortTest,TestTurnAlternateServerPingPongTLS)1340 TEST_F(TurnPortTest, TestTurnAlternateServerPingPongTLS) {
1341 TestTurnAlternateServerPingPong(PROTO_TLS);
1342 }
1343
1344 // Test try-alternate-server catch the case of repeated server.
TEST_F(TurnPortTest,TestTurnAlternateServerDetectRepetitionUDP)1345 TEST_F(TurnPortTest, TestTurnAlternateServerDetectRepetitionUDP) {
1346 TestTurnAlternateServerDetectRepetition(PROTO_UDP);
1347 }
1348
TEST_F(TurnPortTest,TestTurnAlternateServerDetectRepetitionTCP)1349 TEST_F(TurnPortTest, TestTurnAlternateServerDetectRepetitionTCP) {
1350 TestTurnAlternateServerDetectRepetition(PROTO_TCP);
1351 }
1352
TEST_F(TurnPortTest,TestTurnAlternateServerDetectRepetitionTLS)1353 TEST_F(TurnPortTest, TestTurnAlternateServerDetectRepetitionTLS) {
1354 TestTurnAlternateServerDetectRepetition(PROTO_TCP);
1355 }
1356
1357 // Test catching the case of a redirect to loopback.
TEST_F(TurnPortTest,TestTurnAlternateServerLoopbackUdpIpv4)1358 TEST_F(TurnPortTest, TestTurnAlternateServerLoopbackUdpIpv4) {
1359 TestTurnAlternateServerLoopback(PROTO_UDP, false);
1360 }
1361
TEST_F(TurnPortTest,TestTurnAlternateServerLoopbackUdpIpv6)1362 TEST_F(TurnPortTest, TestTurnAlternateServerLoopbackUdpIpv6) {
1363 TestTurnAlternateServerLoopback(PROTO_UDP, true);
1364 }
1365
TEST_F(TurnPortTest,TestTurnAlternateServerLoopbackTcpIpv4)1366 TEST_F(TurnPortTest, TestTurnAlternateServerLoopbackTcpIpv4) {
1367 TestTurnAlternateServerLoopback(PROTO_TCP, false);
1368 }
1369
TEST_F(TurnPortTest,TestTurnAlternateServerLoopbackTcpIpv6)1370 TEST_F(TurnPortTest, TestTurnAlternateServerLoopbackTcpIpv6) {
1371 TestTurnAlternateServerLoopback(PROTO_TCP, true);
1372 }
1373
TEST_F(TurnPortTest,TestTurnAlternateServerLoopbackTlsIpv4)1374 TEST_F(TurnPortTest, TestTurnAlternateServerLoopbackTlsIpv4) {
1375 TestTurnAlternateServerLoopback(PROTO_TLS, false);
1376 }
1377
TEST_F(TurnPortTest,TestTurnAlternateServerLoopbackTlsIpv6)1378 TEST_F(TurnPortTest, TestTurnAlternateServerLoopbackTlsIpv6) {
1379 TestTurnAlternateServerLoopback(PROTO_TLS, true);
1380 }
1381
1382 // Do a TURN allocation and try to send a packet to it from the outside.
1383 // The packet should be dropped. Then, try to send a packet from TURN to the
1384 // outside. It should reach its destination. Finally, try again from the
1385 // outside. It should now work as well.
TEST_F(TurnPortTest,TestTurnConnection)1386 TEST_F(TurnPortTest, TestTurnConnection) {
1387 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1388 TestTurnConnection(PROTO_UDP);
1389 }
1390
1391 // Similar to above, except that this test will use the shared socket.
TEST_F(TurnPortTest,TestTurnConnectionUsingSharedSocket)1392 TEST_F(TurnPortTest, TestTurnConnectionUsingSharedSocket) {
1393 CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1394 TestTurnConnection(PROTO_UDP);
1395 }
1396
1397 // Test that we can establish a TCP connection with TURN server.
TEST_F(TurnPortTest,TestTurnTcpConnection)1398 TEST_F(TurnPortTest, TestTurnTcpConnection) {
1399 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1400 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1401 TestTurnConnection(PROTO_TCP);
1402 }
1403
1404 // Test that we can establish a TLS connection with TURN server.
TEST_F(TurnPortTest,TestTurnTlsConnection)1405 TEST_F(TurnPortTest, TestTurnTlsConnection) {
1406 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1407 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1408 TestTurnConnection(PROTO_TLS);
1409 }
1410
1411 // Test that if a connection on a TURN port is destroyed, the TURN port can
1412 // still receive ping on that connection as if it is from an unknown address.
1413 // If the connection is created again, it will be used to receive ping.
TEST_F(TurnPortTest,TestDestroyTurnConnection)1414 TEST_F(TurnPortTest, TestDestroyTurnConnection) {
1415 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1416 TestDestroyTurnConnection();
1417 }
1418
1419 // Similar to above, except that this test will use the shared socket.
TEST_F(TurnPortTest,TestDestroyTurnConnectionUsingSharedSocket)1420 TEST_F(TurnPortTest, TestDestroyTurnConnectionUsingSharedSocket) {
1421 CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1422 TestDestroyTurnConnection();
1423 }
1424
1425 // Run TurnConnectionTest with one-time-use nonce feature.
1426 // Here server will send a 438 STALE_NONCE error message for
1427 // every TURN transaction.
TEST_F(TurnPortTest,TestTurnConnectionUsingOTUNonce)1428 TEST_F(TurnPortTest, TestTurnConnectionUsingOTUNonce) {
1429 turn_server_.set_enable_otu_nonce(true);
1430 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1431 TestTurnConnection(PROTO_UDP);
1432 }
1433
1434 // Test that CreatePermissionRequest will be scheduled after the success
1435 // of the first create permission request and the request will get an
1436 // ErrorResponse if the ufrag and pwd are incorrect.
TEST_F(TurnPortTest,TestRefreshCreatePermissionRequest)1437 TEST_F(TurnPortTest, TestRefreshCreatePermissionRequest) {
1438 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1439 PrepareTurnAndUdpPorts(PROTO_UDP);
1440
1441 Connection* conn = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1442 Port::ORIGIN_MESSAGE);
1443 ASSERT_TRUE(conn != NULL);
1444 EXPECT_TRUE_SIMULATED_WAIT(turn_create_permission_success_, kSimulatedRtt,
1445 fake_clock_);
1446 turn_create_permission_success_ = false;
1447 // A create-permission-request should be pending.
1448 // After the next create-permission-response is received, it will schedule
1449 // another request with bad_ufrag and bad_pwd.
1450 RelayCredentials bad_credentials("bad_user", "bad_pwd");
1451 turn_port_->set_credentials(bad_credentials);
1452 turn_port_->request_manager().FlushForTest(kAllRequestsForTest);
1453 EXPECT_TRUE_SIMULATED_WAIT(turn_create_permission_success_, kSimulatedRtt,
1454 fake_clock_);
1455 // Flush the requests again; the create-permission-request will fail.
1456 turn_port_->request_manager().FlushForTest(kAllRequestsForTest);
1457 EXPECT_TRUE_SIMULATED_WAIT(!turn_create_permission_success_, kSimulatedRtt,
1458 fake_clock_);
1459 EXPECT_TRUE(CheckConnectionFailedAndPruned(conn));
1460 }
1461
TEST_F(TurnPortTest,TestChannelBindGetErrorResponse)1462 TEST_F(TurnPortTest, TestChannelBindGetErrorResponse) {
1463 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1464 PrepareTurnAndUdpPorts(PROTO_UDP);
1465 Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1466 Port::ORIGIN_MESSAGE);
1467 ASSERT_TRUE(conn1 != nullptr);
1468 Connection* conn2 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
1469 Port::ORIGIN_MESSAGE);
1470
1471 ASSERT_TRUE(conn2 != nullptr);
1472 conn1->Ping(0);
1473 EXPECT_TRUE_SIMULATED_WAIT(conn1->writable(), kSimulatedRtt * 2, fake_clock_);
1474 // TODO(deadbeef): SetEntryChannelId should not be a public method.
1475 // Instead we should set an option on the fake TURN server to force it to
1476 // send a channel bind errors.
1477 ASSERT_TRUE(
1478 turn_port_->SetEntryChannelId(udp_port_->Candidates()[0].address(), -1));
1479
1480 std::string data = "ABC";
1481 conn1->Send(data.data(), data.length(), options);
1482
1483 EXPECT_TRUE_SIMULATED_WAIT(CheckConnectionFailedAndPruned(conn1),
1484 kSimulatedRtt, fake_clock_);
1485 // Verify that packets are allowed to be sent after a bind request error.
1486 // They'll just use a send indication instead.
1487 conn2->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
1488 &TurnPortTest::OnUdpReadPacket);
1489 conn1->Send(data.data(), data.length(), options);
1490 EXPECT_TRUE_SIMULATED_WAIT(!udp_packets_.empty(), kSimulatedRtt, fake_clock_);
1491 }
1492
1493 // Do a TURN allocation, establish a UDP connection, and send some data.
TEST_F(TurnPortTest,TestTurnSendDataTurnUdpToUdp)1494 TEST_F(TurnPortTest, TestTurnSendDataTurnUdpToUdp) {
1495 // Create ports and prepare addresses.
1496 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1497 TestTurnSendData(PROTO_UDP);
1498 EXPECT_EQ(UDP_PROTOCOL_NAME, turn_port_->Candidates()[0].relay_protocol());
1499 }
1500
1501 // Do a TURN allocation, establish a TCP connection, and send some data.
TEST_F(TurnPortTest,TestTurnSendDataTurnTcpToUdp)1502 TEST_F(TurnPortTest, TestTurnSendDataTurnTcpToUdp) {
1503 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1504 // Create ports and prepare addresses.
1505 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1506 TestTurnSendData(PROTO_TCP);
1507 EXPECT_EQ(TCP_PROTOCOL_NAME, turn_port_->Candidates()[0].relay_protocol());
1508 }
1509
1510 // Do a TURN allocation, establish a TLS connection, and send some data.
TEST_F(TurnPortTest,TestTurnSendDataTurnTlsToUdp)1511 TEST_F(TurnPortTest, TestTurnSendDataTurnTlsToUdp) {
1512 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1513 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1514 TestTurnSendData(PROTO_TLS);
1515 EXPECT_EQ(TLS_PROTOCOL_NAME, turn_port_->Candidates()[0].relay_protocol());
1516 }
1517
1518 // Test TURN fails to make a connection from IPv6 address to a server which has
1519 // IPv4 address.
TEST_F(TurnPortTest,TestTurnLocalIPv6AddressServerIPv4)1520 TEST_F(TurnPortTest, TestTurnLocalIPv6AddressServerIPv4) {
1521 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1522 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1523 kTurnUdpProtoAddr);
1524 turn_port_->PrepareAddress();
1525 ASSERT_TRUE_SIMULATED_WAIT(turn_error_, kSimulatedRtt, fake_clock_);
1526 EXPECT_TRUE(turn_port_->Candidates().empty());
1527 }
1528
1529 // Test TURN make a connection from IPv6 address to a server which has
1530 // IPv6 intenal address. But in this test external address is a IPv4 address,
1531 // hence allocated address will be a IPv4 address.
TEST_F(TurnPortTest,TestTurnLocalIPv6AddressServerIPv6ExtenalIPv4)1532 TEST_F(TurnPortTest, TestTurnLocalIPv6AddressServerIPv6ExtenalIPv4) {
1533 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1534 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1535 kTurnUdpIPv6ProtoAddr);
1536 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
1537 }
1538
1539 // Tests that the local and remote candidate address families should match when
1540 // a connection is created. Specifically, if a TURN port has an IPv6 address,
1541 // its local candidate will still be an IPv4 address and it can only create
1542 // connections with IPv4 remote candidates.
TEST_F(TurnPortTest,TestCandidateAddressFamilyMatch)1543 TEST_F(TurnPortTest, TestCandidateAddressFamilyMatch) {
1544 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1545
1546 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1547 kTurnUdpIPv6ProtoAddr);
1548 turn_port_->PrepareAddress();
1549 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 2, fake_clock_);
1550 ASSERT_EQ(1U, turn_port_->Candidates().size());
1551
1552 // Create an IPv4 candidate. It will match the TURN candidate.
1553 Candidate remote_candidate(ICE_CANDIDATE_COMPONENT_RTP, "udp", kLocalAddr2, 0,
1554 "", "", "local", 0, kCandidateFoundation);
1555 remote_candidate.set_address(kLocalAddr2);
1556 Connection* conn =
1557 turn_port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
1558 EXPECT_NE(nullptr, conn);
1559
1560 // Set the candidate address family to IPv6. It won't match the TURN
1561 // candidate.
1562 remote_candidate.set_address(kLocalIPv6Addr2);
1563 conn = turn_port_->CreateConnection(remote_candidate, Port::ORIGIN_MESSAGE);
1564 EXPECT_EQ(nullptr, conn);
1565 }
1566
1567 // Test that a CreatePermission failure will result in the connection being
1568 // pruned and failed.
TEST_F(TurnPortTest,TestConnectionFailedAndPrunedOnCreatePermissionFailure)1569 TEST_F(TurnPortTest, TestConnectionFailedAndPrunedOnCreatePermissionFailure) {
1570 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1571 turn_server_.server()->set_reject_private_addresses(true);
1572 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1573 turn_port_->PrepareAddress();
1574 EXPECT_TRUE_SIMULATED_WAIT(turn_ready_, kSimulatedRtt * 3, fake_clock_);
1575
1576 CreateUdpPort(SocketAddress("10.0.0.10", 0));
1577 udp_port_->PrepareAddress();
1578 EXPECT_TRUE_SIMULATED_WAIT(udp_ready_, kSimulatedRtt, fake_clock_);
1579 // Create a connection.
1580 TestConnectionWrapper conn(turn_port_->CreateConnection(
1581 udp_port_->Candidates()[0], Port::ORIGIN_MESSAGE));
1582 EXPECT_TRUE(conn.connection() != nullptr);
1583
1584 // Asynchronously, CreatePermission request should be sent and fail, which
1585 // will make the connection pruned and failed.
1586 EXPECT_TRUE_SIMULATED_WAIT(CheckConnectionFailedAndPruned(conn.connection()),
1587 kSimulatedRtt, fake_clock_);
1588 EXPECT_TRUE_SIMULATED_WAIT(!turn_create_permission_success_, kSimulatedRtt,
1589 fake_clock_);
1590 // Check that the connection is not deleted asynchronously.
1591 SIMULATED_WAIT(conn.connection() == nullptr, kConnectionDestructionDelay,
1592 fake_clock_);
1593 EXPECT_NE(nullptr, conn.connection());
1594 }
1595
1596 // Test that a TURN allocation is released when the port is closed.
TEST_F(TurnPortTest,TestTurnReleaseAllocation)1597 TEST_F(TurnPortTest, TestTurnReleaseAllocation) {
1598 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1599 TestTurnReleaseAllocation(PROTO_UDP);
1600 }
1601
1602 // Test that a TURN TCP allocation is released when the port is closed.
TEST_F(TurnPortTest,TestTurnTCPReleaseAllocation)1603 TEST_F(TurnPortTest, TestTurnTCPReleaseAllocation) {
1604 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1605 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1606 TestTurnReleaseAllocation(PROTO_TCP);
1607 }
1608
TEST_F(TurnPortTest,TestTurnTLSReleaseAllocation)1609 TEST_F(TurnPortTest, TestTurnTLSReleaseAllocation) {
1610 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1611 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1612 TestTurnReleaseAllocation(PROTO_TLS);
1613 }
1614
TEST_F(TurnPortTest,TestTurnUDPGracefulReleaseAllocation)1615 TEST_F(TurnPortTest, TestTurnUDPGracefulReleaseAllocation) {
1616 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_UDP);
1617 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1618 TestTurnGracefulReleaseAllocation(PROTO_UDP);
1619 }
1620
TEST_F(TurnPortTest,TestTurnTCPGracefulReleaseAllocation)1621 TEST_F(TurnPortTest, TestTurnTCPGracefulReleaseAllocation) {
1622 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
1623 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
1624 TestTurnGracefulReleaseAllocation(PROTO_TCP);
1625 }
1626
TEST_F(TurnPortTest,TestTurnTLSGracefulReleaseAllocation)1627 TEST_F(TurnPortTest, TestTurnTLSGracefulReleaseAllocation) {
1628 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1629 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1630 TestTurnGracefulReleaseAllocation(PROTO_TLS);
1631 }
1632
1633 // Test that nothing bad happens if we try to create a connection to the same
1634 // remote address twice. Previously there was a bug that caused this to hit a
1635 // DCHECK.
TEST_F(TurnPortTest,CanCreateTwoConnectionsToSameAddress)1636 TEST_F(TurnPortTest, CanCreateTwoConnectionsToSameAddress) {
1637 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
1638 PrepareTurnAndUdpPorts(PROTO_UDP);
1639 Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1640 Port::ORIGIN_MESSAGE);
1641 Connection* conn2 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
1642 Port::ORIGIN_MESSAGE);
1643 EXPECT_NE(conn1, conn2);
1644 }
1645
1646 // This test verifies any FD's are not leaked after TurnPort is destroyed.
1647 // https://code.google.com/p/webrtc/issues/detail?id=2651
1648 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
1649
TEST_F(TurnPortTest,TestResolverShutdown)1650 TEST_F(TurnPortTest, TestResolverShutdown) {
1651 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1652 int last_fd_count = GetFDCount();
1653 // Need to supply unresolved address to kick off resolver.
1654 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1655 ProtocolAddress(kTurnInvalidAddr, PROTO_UDP));
1656 turn_port_->PrepareAddress();
1657 ASSERT_TRUE_WAIT(turn_error_, kResolverTimeout);
1658 EXPECT_TRUE(turn_port_->Candidates().empty());
1659 turn_port_.reset();
1660 rtc::Thread::Current()->PostTask([this] { test_finish_ = true; });
1661 // Waiting for above message to be processed.
1662 ASSERT_TRUE_SIMULATED_WAIT(test_finish_, 1, fake_clock_);
1663 EXPECT_EQ(last_fd_count, GetFDCount());
1664 }
1665 #endif
1666
1667 class MessageObserver : public StunMessageObserver {
1668 public:
MessageObserver(unsigned int * message_counter,unsigned int * channel_data_counter,unsigned int * attr_counter)1669 MessageObserver(unsigned int* message_counter,
1670 unsigned int* channel_data_counter,
1671 unsigned int* attr_counter)
1672 : message_counter_(message_counter),
1673 channel_data_counter_(channel_data_counter),
1674 attr_counter_(attr_counter) {}
~MessageObserver()1675 virtual ~MessageObserver() {}
ReceivedMessage(const TurnMessage * msg)1676 void ReceivedMessage(const TurnMessage* msg) override {
1677 if (message_counter_ != nullptr) {
1678 (*message_counter_)++;
1679 }
1680 // Implementation defined attributes are returned as ByteString
1681 const StunByteStringAttribute* attr =
1682 msg->GetByteString(TestTurnCustomizer::STUN_ATTR_COUNTER);
1683 if (attr != nullptr && attr_counter_ != nullptr) {
1684 rtc::ByteBufferReader buf(attr->bytes(), attr->length());
1685 unsigned int val = ~0u;
1686 buf.ReadUInt32(&val);
1687 (*attr_counter_)++;
1688 }
1689 }
1690
ReceivedChannelData(const char * data,size_t size)1691 void ReceivedChannelData(const char* data, size_t size) override {
1692 if (channel_data_counter_ != nullptr) {
1693 (*channel_data_counter_)++;
1694 }
1695 }
1696
1697 // Number of TurnMessages observed.
1698 unsigned int* message_counter_ = nullptr;
1699
1700 // Number of channel data observed.
1701 unsigned int* channel_data_counter_ = nullptr;
1702
1703 // Number of TurnMessages that had STUN_ATTR_COUNTER.
1704 unsigned int* attr_counter_ = nullptr;
1705 };
1706
1707 // Do a TURN allocation, establish a TLS connection, and send some data.
1708 // Add customizer and check that it get called.
TEST_F(TurnPortTest,TestTurnCustomizerCount)1709 TEST_F(TurnPortTest, TestTurnCustomizerCount) {
1710 unsigned int observer_message_counter = 0;
1711 unsigned int observer_channel_data_counter = 0;
1712 unsigned int observer_attr_counter = 0;
1713 TestTurnCustomizer* customizer = new TestTurnCustomizer();
1714 std::unique_ptr<MessageObserver> validator(new MessageObserver(
1715 &observer_message_counter, &observer_channel_data_counter,
1716 &observer_attr_counter));
1717
1718 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1719 turn_customizer_.reset(customizer);
1720 turn_server_.server()->SetStunMessageObserver(std::move(validator));
1721
1722 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1723 TestTurnSendData(PROTO_TLS);
1724 EXPECT_EQ(TLS_PROTOCOL_NAME, turn_port_->Candidates()[0].relay_protocol());
1725
1726 // There should have been at least turn_packets_.size() calls to `customizer`.
1727 EXPECT_GE(customizer->modify_cnt_ + customizer->allow_channel_data_cnt_,
1728 turn_packets_.size());
1729
1730 // Some channel data should be received.
1731 EXPECT_GE(observer_channel_data_counter, 0u);
1732
1733 // Need to release TURN port before the customizer.
1734 turn_port_.reset(nullptr);
1735 }
1736
1737 // Do a TURN allocation, establish a TLS connection, and send some data.
1738 // Add customizer and check that it can can prevent usage of channel data.
TEST_F(TurnPortTest,TestTurnCustomizerDisallowChannelData)1739 TEST_F(TurnPortTest, TestTurnCustomizerDisallowChannelData) {
1740 unsigned int observer_message_counter = 0;
1741 unsigned int observer_channel_data_counter = 0;
1742 unsigned int observer_attr_counter = 0;
1743 TestTurnCustomizer* customizer = new TestTurnCustomizer();
1744 std::unique_ptr<MessageObserver> validator(new MessageObserver(
1745 &observer_message_counter, &observer_channel_data_counter,
1746 &observer_attr_counter));
1747 customizer->allow_channel_data_ = false;
1748 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1749 turn_customizer_.reset(customizer);
1750 turn_server_.server()->SetStunMessageObserver(std::move(validator));
1751
1752 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1753 TestTurnSendData(PROTO_TLS);
1754 EXPECT_EQ(TLS_PROTOCOL_NAME, turn_port_->Candidates()[0].relay_protocol());
1755
1756 // There should have been at least turn_packets_.size() calls to `customizer`.
1757 EXPECT_GE(customizer->modify_cnt_, turn_packets_.size());
1758
1759 // No channel data should be received.
1760 EXPECT_EQ(observer_channel_data_counter, 0u);
1761
1762 // Need to release TURN port before the customizer.
1763 turn_port_.reset(nullptr);
1764 }
1765
1766 // Do a TURN allocation, establish a TLS connection, and send some data.
1767 // Add customizer and check that it can add attribute to messages.
TEST_F(TurnPortTest,TestTurnCustomizerAddAttribute)1768 TEST_F(TurnPortTest, TestTurnCustomizerAddAttribute) {
1769 unsigned int observer_message_counter = 0;
1770 unsigned int observer_channel_data_counter = 0;
1771 unsigned int observer_attr_counter = 0;
1772 TestTurnCustomizer* customizer = new TestTurnCustomizer();
1773 std::unique_ptr<MessageObserver> validator(new MessageObserver(
1774 &observer_message_counter, &observer_channel_data_counter,
1775 &observer_attr_counter));
1776 customizer->allow_channel_data_ = false;
1777 customizer->add_counter_ = true;
1778 turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TLS);
1779 turn_customizer_.reset(customizer);
1780 turn_server_.server()->SetStunMessageObserver(std::move(validator));
1781
1782 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTlsProtoAddr);
1783 TestTurnSendData(PROTO_TLS);
1784 EXPECT_EQ(TLS_PROTOCOL_NAME, turn_port_->Candidates()[0].relay_protocol());
1785
1786 // There should have been at least turn_packets_.size() calls to `customizer`.
1787 EXPECT_GE(customizer->modify_cnt_, turn_packets_.size());
1788
1789 // Everything will be sent as messages since channel data is disallowed.
1790 EXPECT_GE(customizer->modify_cnt_, observer_message_counter);
1791
1792 // All messages should have attribute.
1793 EXPECT_EQ(observer_message_counter, observer_attr_counter);
1794
1795 // At least allow_channel_data_cnt_ messages should have been sent.
1796 EXPECT_GE(customizer->modify_cnt_, customizer->allow_channel_data_cnt_);
1797 EXPECT_GE(customizer->allow_channel_data_cnt_, 0u);
1798
1799 // No channel data should be received.
1800 EXPECT_EQ(observer_channel_data_counter, 0u);
1801
1802 // Need to release TURN port before the customizer.
1803 turn_port_.reset(nullptr);
1804 }
1805
TEST_F(TurnPortTest,TestOverlongUsername)1806 TEST_F(TurnPortTest, TestOverlongUsername) {
1807 std::string overlong_username(513, 'x');
1808 RelayCredentials credentials(overlong_username, kTurnPassword);
1809 EXPECT_FALSE(
1810 CreateTurnPort(overlong_username, kTurnPassword, kTurnTlsProtoAddr));
1811 }
1812
TEST_F(TurnPortTest,TestTurnDangerousServer)1813 TEST_F(TurnPortTest, TestTurnDangerousServer) {
1814 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnDangerousProtoAddr);
1815 ASSERT_FALSE(turn_port_);
1816 }
1817
TEST_F(TurnPortTest,TestTurnDangerousServerPermits53)1818 TEST_F(TurnPortTest, TestTurnDangerousServerPermits53) {
1819 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnPort53ProtoAddr);
1820 ASSERT_TRUE(turn_port_);
1821 }
1822
TEST_F(TurnPortTest,TestTurnDangerousServerPermits80)1823 TEST_F(TurnPortTest, TestTurnDangerousServerPermits80) {
1824 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnPort80ProtoAddr);
1825 ASSERT_TRUE(turn_port_);
1826 }
1827
TEST_F(TurnPortTest,TestTurnDangerousServerPermits443)1828 TEST_F(TurnPortTest, TestTurnDangerousServerPermits443) {
1829 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnPort443ProtoAddr);
1830 ASSERT_TRUE(turn_port_);
1831 }
1832
TEST_F(TurnPortTest,TestTurnDangerousAlternateServer)1833 TEST_F(TurnPortTest, TestTurnDangerousAlternateServer) {
1834 const ProtocolType protocol_type = PROTO_TCP;
1835 std::vector<rtc::SocketAddress> redirect_addresses;
1836 redirect_addresses.push_back(kTurnDangerousAddr);
1837
1838 TestTurnRedirector redirector(redirect_addresses);
1839
1840 turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
1841 turn_server_.AddInternalSocket(kTurnDangerousAddr, protocol_type);
1842 turn_server_.set_redirect_hook(&redirector);
1843 CreateTurnPort(kTurnUsername, kTurnPassword,
1844 ProtocolAddress(kTurnIntAddr, protocol_type));
1845
1846 // Retrieve the address before we run the state machine.
1847 const SocketAddress old_addr = turn_port_->server_address().address;
1848
1849 turn_port_->PrepareAddress();
1850 // This should result in an error event.
1851 EXPECT_TRUE_SIMULATED_WAIT(error_event_.error_code != 0,
1852 TimeToGetAlternateTurnCandidate(protocol_type),
1853 fake_clock_);
1854 // but should NOT result in the port turning ready, and no candidates
1855 // should be gathered.
1856 EXPECT_FALSE(turn_ready_);
1857 ASSERT_EQ(0U, turn_port_->Candidates().size());
1858 }
1859
TEST_F(TurnPortTest,TestTurnDangerousServerAllowedWithFieldTrial)1860 TEST_F(TurnPortTest, TestTurnDangerousServerAllowedWithFieldTrial) {
1861 webrtc::test::ScopedKeyValueConfig override_field_trials(
1862 field_trials_, "WebRTC-Turn-AllowSystemPorts/Enabled/");
1863 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnDangerousProtoAddr);
1864 ASSERT_TRUE(turn_port_);
1865 }
1866
1867 class TurnPortWithMockDnsResolverTest : public TurnPortTest {
1868 public:
TurnPortWithMockDnsResolverTest()1869 TurnPortWithMockDnsResolverTest()
1870 : TurnPortTest(), socket_factory_(ss_.get()) {}
1871
socket_factory()1872 rtc::PacketSocketFactory* socket_factory() override {
1873 return &socket_factory_;
1874 }
1875
SetDnsResolverExpectations(rtc::MockDnsResolvingPacketSocketFactory::Expectations expectations)1876 void SetDnsResolverExpectations(
1877 rtc::MockDnsResolvingPacketSocketFactory::Expectations expectations) {
1878 socket_factory_.SetExpectations(expectations);
1879 }
1880
1881 private:
1882 rtc::MockDnsResolvingPacketSocketFactory socket_factory_;
1883 };
1884
1885 // Test an allocation from a TURN server specified by a hostname.
TEST_F(TurnPortWithMockDnsResolverTest,TestHostnameResolved)1886 TEST_F(TurnPortWithMockDnsResolverTest, TestHostnameResolved) {
1887 CreateTurnPort(kTurnUsername, kTurnPassword, kTurnPortValidHostnameProtoAddr);
1888 SetDnsResolverExpectations(
1889 [](webrtc::MockAsyncDnsResolver* resolver,
1890 webrtc::MockAsyncDnsResolverResult* resolver_result) {
1891 EXPECT_CALL(*resolver, Start(kTurnValidAddr, _))
1892 .WillOnce(InvokeArgument<1>());
1893 EXPECT_CALL(*resolver, result)
1894 .WillRepeatedly(ReturnPointee(resolver_result));
1895 EXPECT_CALL(*resolver_result, GetError).WillRepeatedly(Return(0));
1896 EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET, _))
1897 .WillOnce(DoAll(SetArgPointee<1>(kTurnUdpIntAddr), Return(true)));
1898 });
1899 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
1900 }
1901
1902 // Test an allocation from a TURN server specified by a hostname on an IPv6
1903 // network.
TEST_F(TurnPortWithMockDnsResolverTest,TestHostnameResolvedIPv6Network)1904 TEST_F(TurnPortWithMockDnsResolverTest, TestHostnameResolvedIPv6Network) {
1905 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1906 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1907 kTurnPortValidHostnameProtoAddr);
1908 SetDnsResolverExpectations(
1909 [](webrtc::MockAsyncDnsResolver* resolver,
1910 webrtc::MockAsyncDnsResolverResult* resolver_result) {
1911 EXPECT_CALL(*resolver, Start(kTurnValidAddr, _))
1912 .WillOnce(InvokeArgument<1>());
1913 EXPECT_CALL(*resolver, result)
1914 .WillRepeatedly(ReturnPointee(resolver_result));
1915 EXPECT_CALL(*resolver_result, GetError).WillRepeatedly(Return(0));
1916 EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET6, _))
1917 .WillOnce(
1918 DoAll(SetArgPointee<1>(kTurnUdpIPv6IntAddr), Return(true)));
1919 });
1920 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
1921 }
1922
1923 // Test an allocation from a TURN server specified by a hostname on an IPv6
1924 // network, without network family-specific resolution.
TEST_F(TurnPortWithMockDnsResolverTest,TestHostnameResolvedIPv6NetworkFamilyFieldTrialDisabled)1925 TEST_F(TurnPortWithMockDnsResolverTest,
1926 TestHostnameResolvedIPv6NetworkFamilyFieldTrialDisabled) {
1927 webrtc::test::ScopedKeyValueConfig override_field_trials(
1928 field_trials_, "WebRTC-IPv6NetworkResolutionFixes/Disabled/");
1929 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1930 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1931 kTurnPortValidHostnameProtoAddr);
1932 SetDnsResolverExpectations(
1933 [](webrtc::MockAsyncDnsResolver* resolver,
1934 webrtc::MockAsyncDnsResolverResult* resolver_result) {
1935 // Expect to call Resolver::Start without family arg.
1936 EXPECT_CALL(*resolver, Start(kTurnValidAddr, _))
1937 .WillOnce(InvokeArgument<1>());
1938 EXPECT_CALL(*resolver, result)
1939 .WillRepeatedly(ReturnPointee(resolver_result));
1940 EXPECT_CALL(*resolver_result, GetError).WillRepeatedly(Return(0));
1941 EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET6, _))
1942 .WillOnce(
1943 DoAll(SetArgPointee<1>(kTurnUdpIPv6IntAddr), Return(true)));
1944 });
1945 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
1946 }
1947
1948 // Test an allocation from a TURN server specified by a hostname on an IPv6
1949 // network, without network family-specific resolution.
TEST_F(TurnPortWithMockDnsResolverTest,TestHostnameResolvedIPv6NetworkFamilyFieldTrialParamDisabled)1950 TEST_F(TurnPortWithMockDnsResolverTest,
1951 TestHostnameResolvedIPv6NetworkFamilyFieldTrialParamDisabled) {
1952 webrtc::test::ScopedKeyValueConfig override_field_trials(
1953 field_trials_,
1954 "WebRTC-IPv6NetworkResolutionFixes/"
1955 "Enabled,ResolveTurnHostnameForFamily:false/");
1956 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1957 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1958 kTurnPortValidHostnameProtoAddr);
1959 SetDnsResolverExpectations(
1960 [](webrtc::MockAsyncDnsResolver* resolver,
1961 webrtc::MockAsyncDnsResolverResult* resolver_result) {
1962 // Expect to call Resolver::Start without family arg.
1963 EXPECT_CALL(*resolver, Start(kTurnValidAddr, _))
1964 .WillOnce(InvokeArgument<1>());
1965 EXPECT_CALL(*resolver, result)
1966 .WillRepeatedly(ReturnPointee(resolver_result));
1967 EXPECT_CALL(*resolver_result, GetError).WillRepeatedly(Return(0));
1968 EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET6, _))
1969 .WillOnce(
1970 DoAll(SetArgPointee<1>(kTurnUdpIPv6IntAddr), Return(true)));
1971 });
1972 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
1973 }
1974
1975 // Test an allocation from a TURN server specified by a hostname on an IPv6
1976 // network, with network family-specific resolution.
TEST_F(TurnPortWithMockDnsResolverTest,TestHostnameResolvedIPv6NetworkFieldTrialEnabled)1977 TEST_F(TurnPortWithMockDnsResolverTest,
1978 TestHostnameResolvedIPv6NetworkFieldTrialEnabled) {
1979 webrtc::test::ScopedKeyValueConfig override_field_trials(
1980 field_trials_,
1981 "WebRTC-IPv6NetworkResolutionFixes/"
1982 "Enabled,ResolveTurnHostnameForFamily:true/");
1983 turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, PROTO_UDP);
1984 CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
1985 kTurnPortValidHostnameProtoAddr);
1986 SetDnsResolverExpectations(
1987 [](webrtc::MockAsyncDnsResolver* resolver,
1988 webrtc::MockAsyncDnsResolverResult* resolver_result) {
1989 // Expect to call Resolver::Start _with_ family arg.
1990 EXPECT_CALL(*resolver, Start(kTurnValidAddr, /*family=*/AF_INET6, _))
1991 .WillOnce(InvokeArgument<2>());
1992 EXPECT_CALL(*resolver, result)
1993 .WillRepeatedly(ReturnPointee(resolver_result));
1994 EXPECT_CALL(*resolver_result, GetError).WillRepeatedly(Return(0));
1995 EXPECT_CALL(*resolver_result, GetResolvedAddress(AF_INET6, _))
1996 .WillOnce(
1997 DoAll(SetArgPointee<1>(kTurnUdpIPv6IntAddr), Return(true)));
1998 });
1999 TestTurnAllocateSucceeds(kSimulatedRtt * 2);
2000 }
2001
2002 } // namespace cricket
2003