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 #endif
13 
14 #include "webrtc/p2p/base/basicpacketsocketfactory.h"
15 #include "webrtc/p2p/base/constants.h"
16 #include "webrtc/p2p/base/portallocator.h"
17 #include "webrtc/p2p/base/tcpport.h"
18 #include "webrtc/p2p/base/testturnserver.h"
19 #include "webrtc/p2p/base/turnport.h"
20 #include "webrtc/p2p/base/udpport.h"
21 #include "webrtc/base/asynctcpsocket.h"
22 #include "webrtc/base/buffer.h"
23 #include "webrtc/base/dscp.h"
24 #include "webrtc/base/firewallsocketserver.h"
25 #include "webrtc/base/gunit.h"
26 #include "webrtc/base/helpers.h"
27 #include "webrtc/base/logging.h"
28 #include "webrtc/base/physicalsocketserver.h"
29 #include "webrtc/base/scoped_ptr.h"
30 #include "webrtc/base/socketaddress.h"
31 #include "webrtc/base/ssladapter.h"
32 #include "webrtc/base/thread.h"
33 #include "webrtc/base/virtualsocketserver.h"
34 
35 using rtc::SocketAddress;
36 using cricket::Connection;
37 using cricket::Port;
38 using cricket::PortInterface;
39 using cricket::TurnPort;
40 using cricket::UDPPort;
41 
42 static const SocketAddress kLocalAddr1("11.11.11.11", 0);
43 static const SocketAddress kLocalAddr2("22.22.22.22", 0);
44 static const SocketAddress kLocalIPv6Addr(
45     "2401:fa00:4:1000:be30:5bff:fee5:c3", 0);
46 static const SocketAddress kTurnUdpIntAddr("99.99.99.3",
47                                            cricket::TURN_SERVER_PORT);
48 static const SocketAddress kTurnTcpIntAddr("99.99.99.4",
49                                            cricket::TURN_SERVER_PORT);
50 static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
51 static const SocketAddress kTurnAlternateIntAddr("99.99.99.6",
52                                                  cricket::TURN_SERVER_PORT);
53 static const SocketAddress kTurnIntAddr("99.99.99.7",
54                                         cricket::TURN_SERVER_PORT);
55 static const SocketAddress kTurnIPv6IntAddr(
56     "2400:4030:2:2c00:be30:abcd:efab:cdef",
57     cricket::TURN_SERVER_PORT);
58 static const SocketAddress kTurnUdpIPv6IntAddr(
59     "2400:4030:1:2c00:be30:abcd:efab:cdef", cricket::TURN_SERVER_PORT);
60 static const SocketAddress kTurnUdpIPv6ExtAddr(
61   "2620:0:1000:1b03:2e41:38ff:fea6:f2a4", 0);
62 
63 static const char kIceUfrag1[] = "TESTICEUFRAG0001";
64 static const char kIceUfrag2[] = "TESTICEUFRAG0002";
65 static const char kIcePwd1[] = "TESTICEPWD00000000000001";
66 static const char kIcePwd2[] = "TESTICEPWD00000000000002";
67 static const char kTurnUsername[] = "test";
68 static const char kTurnPassword[] = "test";
69 static const char kTestOrigin[] = "http://example.com";
70 static const unsigned int kTimeout = 1000;
71 
72 static const cricket::ProtocolAddress kTurnUdpProtoAddr(
73     kTurnUdpIntAddr, cricket::PROTO_UDP);
74 static const cricket::ProtocolAddress kTurnTcpProtoAddr(
75     kTurnTcpIntAddr, cricket::PROTO_TCP);
76 static const cricket::ProtocolAddress kTurnUdpIPv6ProtoAddr(
77     kTurnUdpIPv6IntAddr, cricket::PROTO_UDP);
78 
79 static const unsigned int MSG_TESTFINISH = 0;
80 
81 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
GetFDCount()82 static int GetFDCount() {
83   struct dirent *dp;
84   int fd_count = 0;
85   DIR *dir = opendir("/proc/self/fd/");
86   while ((dp = readdir(dir)) != NULL) {
87     if (dp->d_name[0] == '.')
88       continue;
89     ++fd_count;
90   }
91   closedir(dir);
92   return fd_count;
93 }
94 #endif
95 
96 class TurnPortTestVirtualSocketServer : public rtc::VirtualSocketServer {
97  public:
TurnPortTestVirtualSocketServer(SocketServer * ss)98   explicit TurnPortTestVirtualSocketServer(SocketServer* ss)
99       : VirtualSocketServer(ss) {}
100 
101   using rtc::VirtualSocketServer::LookupBinding;
102 };
103 
104 class TestConnectionWrapper : public sigslot::has_slots<> {
105  public:
TestConnectionWrapper(Connection * conn)106   TestConnectionWrapper(Connection* conn) : connection_(conn) {
107     conn->SignalDestroyed.connect(
108         this, &TestConnectionWrapper::OnConnectionDestroyed);
109   }
110 
connection()111   Connection* connection() { return connection_; }
112 
113  private:
OnConnectionDestroyed(Connection * conn)114   void OnConnectionDestroyed(Connection* conn) {
115     ASSERT_TRUE(conn == connection_);
116     connection_ = nullptr;
117   }
118 
119   Connection* connection_;
120 };
121 
122 class TurnPortTest : public testing::Test,
123                      public sigslot::has_slots<>,
124                      public rtc::MessageHandler {
125  public:
TurnPortTest()126   TurnPortTest()
127       : main_(rtc::Thread::Current()),
128         pss_(new rtc::PhysicalSocketServer),
129         ss_(new TurnPortTestVirtualSocketServer(pss_.get())),
130         ss_scope_(ss_.get()),
131         network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
132         socket_factory_(rtc::Thread::Current()),
133         turn_server_(main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
134         turn_ready_(false),
135         turn_error_(false),
136         turn_unknown_address_(false),
137         turn_create_permission_success_(false),
138         udp_ready_(false),
139         test_finish_(false) {
140     network_.AddIP(rtc::IPAddress(INADDR_ANY));
141   }
142 
OnMessage(rtc::Message * msg)143   virtual void OnMessage(rtc::Message* msg) {
144     ASSERT(msg->message_id == MSG_TESTFINISH);
145     if (msg->message_id == MSG_TESTFINISH)
146       test_finish_ = true;
147   }
148 
ConnectSignalAddressReadyToSetLocalhostAsAltenertativeLocalAddress()149   void ConnectSignalAddressReadyToSetLocalhostAsAltenertativeLocalAddress() {
150     rtc::AsyncPacketSocket* socket = turn_port_->socket();
151     rtc::VirtualSocket* virtual_socket =
152         ss_->LookupBinding(socket->GetLocalAddress());
153     virtual_socket->SignalAddressReady.connect(
154         this, &TurnPortTest::SetLocalhostAsAltenertativeLocalAddress);
155   }
156 
SetLocalhostAsAltenertativeLocalAddress(rtc::VirtualSocket * socket,const rtc::SocketAddress & address)157   void SetLocalhostAsAltenertativeLocalAddress(
158       rtc::VirtualSocket* socket,
159       const rtc::SocketAddress& address) {
160     SocketAddress local_address("127.0.0.1", 2000);
161     socket->SetAlternativeLocalAddress(local_address);
162   }
163 
OnTurnPortComplete(Port * port)164   void OnTurnPortComplete(Port* port) {
165     turn_ready_ = true;
166   }
OnTurnPortError(Port * port)167   void OnTurnPortError(Port* port) {
168     turn_error_ = true;
169   }
OnTurnUnknownAddress(PortInterface * port,const SocketAddress & addr,cricket::ProtocolType proto,cricket::IceMessage * msg,const std::string & rf,bool)170   void OnTurnUnknownAddress(PortInterface* port, const SocketAddress& addr,
171                             cricket::ProtocolType proto,
172                             cricket::IceMessage* msg, const std::string& rf,
173                             bool /*port_muxed*/) {
174     turn_unknown_address_ = true;
175   }
OnTurnCreatePermissionResult(TurnPort * port,const SocketAddress & addr,int code)176   void OnTurnCreatePermissionResult(TurnPort* port,
177                                     const SocketAddress& addr,
178                                     int code) {
179     // Ignoring the address.
180     turn_create_permission_success_ = (code == 0);
181   }
182 
OnTurnRefreshResult(TurnPort * port,int code)183   void OnTurnRefreshResult(TurnPort* port, int code) {
184     turn_refresh_success_ = (code == 0);
185   }
OnTurnReadPacket(Connection * conn,const char * data,size_t size,const rtc::PacketTime & packet_time)186   void OnTurnReadPacket(Connection* conn, const char* data, size_t size,
187                         const rtc::PacketTime& packet_time) {
188     turn_packets_.push_back(rtc::Buffer(data, size));
189   }
OnUdpPortComplete(Port * port)190   void OnUdpPortComplete(Port* port) {
191     udp_ready_ = true;
192   }
OnUdpReadPacket(Connection * conn,const char * data,size_t size,const rtc::PacketTime & packet_time)193   void OnUdpReadPacket(Connection* conn, const char* data, size_t size,
194                        const rtc::PacketTime& packet_time) {
195     udp_packets_.push_back(rtc::Buffer(data, size));
196   }
OnConnectionDestroyed(Connection * conn)197   void OnConnectionDestroyed(Connection* conn) { connection_destroyed_ = true; }
OnSocketReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const rtc::PacketTime & packet_time)198   void OnSocketReadPacket(rtc::AsyncPacketSocket* socket,
199                           const char* data, size_t size,
200                           const rtc::SocketAddress& remote_addr,
201                           const rtc::PacketTime& packet_time) {
202     turn_port_->HandleIncomingPacket(socket, data, size, remote_addr,
203                                      packet_time);
204   }
CreateServerSocket(const SocketAddress addr)205   rtc::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
206     rtc::AsyncSocket* socket = ss_->CreateAsyncSocket(SOCK_STREAM);
207     EXPECT_GE(socket->Bind(addr), 0);
208     EXPECT_GE(socket->Listen(5), 0);
209     return socket;
210   }
211 
CreateTurnPort(const std::string & username,const std::string & password,const cricket::ProtocolAddress & server_address)212   void CreateTurnPort(const std::string& username,
213                       const std::string& password,
214                       const cricket::ProtocolAddress& server_address) {
215     CreateTurnPort(kLocalAddr1, username, password, server_address);
216   }
CreateTurnPort(const rtc::SocketAddress & local_address,const std::string & username,const std::string & password,const cricket::ProtocolAddress & server_address)217   void CreateTurnPort(const rtc::SocketAddress& local_address,
218                       const std::string& username,
219                       const std::string& password,
220                       const cricket::ProtocolAddress& server_address) {
221     cricket::RelayCredentials credentials(username, password);
222     turn_port_.reset(TurnPort::Create(main_, &socket_factory_, &network_,
223                                  local_address.ipaddr(), 0, 0,
224                                  kIceUfrag1, kIcePwd1,
225                                  server_address, credentials, 0,
226                                  std::string()));
227     // This TURN port will be the controlling.
228     turn_port_->SetIceRole(cricket::ICEROLE_CONTROLLING);
229     ConnectSignals();
230   }
231 
232   // Should be identical to CreateTurnPort but specifies an origin value
233   // when creating the instance of TurnPort.
CreateTurnPortWithOrigin(const rtc::SocketAddress & local_address,const std::string & username,const std::string & password,const cricket::ProtocolAddress & server_address,const std::string & origin)234   void CreateTurnPortWithOrigin(const rtc::SocketAddress& local_address,
235                                 const std::string& username,
236                                 const std::string& password,
237                                 const cricket::ProtocolAddress& server_address,
238                                 const std::string& origin) {
239     cricket::RelayCredentials credentials(username, password);
240     turn_port_.reset(TurnPort::Create(main_, &socket_factory_, &network_,
241                                  local_address.ipaddr(), 0, 0,
242                                  kIceUfrag1, kIcePwd1,
243                                  server_address, credentials, 0,
244                                  origin));
245     // This TURN port will be the controlling.
246     turn_port_->SetIceRole(cricket::ICEROLE_CONTROLLING);
247     ConnectSignals();
248   }
249 
CreateSharedTurnPort(const std::string & username,const std::string & password,const cricket::ProtocolAddress & server_address)250   void CreateSharedTurnPort(const std::string& username,
251                             const std::string& password,
252                             const cricket::ProtocolAddress& server_address) {
253     ASSERT(server_address.proto == cricket::PROTO_UDP);
254 
255     if (!socket_) {
256       socket_.reset(socket_factory_.CreateUdpSocket(
257           rtc::SocketAddress(kLocalAddr1.ipaddr(), 0), 0, 0));
258       ASSERT_TRUE(socket_ != NULL);
259       socket_->SignalReadPacket.connect(
260           this, &TurnPortTest::OnSocketReadPacket);
261     }
262 
263     cricket::RelayCredentials credentials(username, password);
264     turn_port_.reset(cricket::TurnPort::Create(
265         main_, &socket_factory_, &network_, socket_.get(),
266         kIceUfrag1, kIcePwd1, server_address, credentials, 0, std::string()));
267     // This TURN port will be the controlling.
268     turn_port_->SetIceRole(cricket::ICEROLE_CONTROLLING);
269     ConnectSignals();
270   }
271 
ConnectSignals()272   void ConnectSignals() {
273     turn_port_->SignalPortComplete.connect(this,
274         &TurnPortTest::OnTurnPortComplete);
275     turn_port_->SignalPortError.connect(this,
276         &TurnPortTest::OnTurnPortError);
277     turn_port_->SignalUnknownAddress.connect(this,
278         &TurnPortTest::OnTurnUnknownAddress);
279     turn_port_->SignalCreatePermissionResult.connect(this,
280         &TurnPortTest::OnTurnCreatePermissionResult);
281     turn_port_->SignalTurnRefreshResult.connect(
282         this, &TurnPortTest::OnTurnRefreshResult);
283   }
ConnectConnectionDestroyedSignal(Connection * conn)284   void ConnectConnectionDestroyedSignal(Connection* conn) {
285     conn->SignalDestroyed.connect(this, &TurnPortTest::OnConnectionDestroyed);
286   }
287 
CreateUdpPort()288   void CreateUdpPort() { CreateUdpPort(kLocalAddr2); }
289 
CreateUdpPort(const SocketAddress & address)290   void CreateUdpPort(const SocketAddress& address) {
291     udp_port_.reset(UDPPort::Create(main_, &socket_factory_, &network_,
292                                     address.ipaddr(), 0, 0, kIceUfrag2,
293                                     kIcePwd2, std::string(), false));
294     // UDP port will be controlled.
295     udp_port_->SetIceRole(cricket::ICEROLE_CONTROLLED);
296     udp_port_->SignalPortComplete.connect(
297         this, &TurnPortTest::OnUdpPortComplete);
298   }
299 
PrepareTurnAndUdpPorts()300   void PrepareTurnAndUdpPorts() {
301     // turn_port_ should have been created.
302     ASSERT_TRUE(turn_port_ != nullptr);
303     turn_port_->PrepareAddress();
304     ASSERT_TRUE_WAIT(turn_ready_, kTimeout);
305 
306     CreateUdpPort();
307     udp_port_->PrepareAddress();
308     ASSERT_TRUE_WAIT(udp_ready_, kTimeout);
309   }
310 
CheckConnectionDestroyed()311   bool CheckConnectionDestroyed() {
312     turn_port_->FlushRequests(cricket::kAllRequests);
313     rtc::Thread::Current()->ProcessMessages(50);
314     return connection_destroyed_;
315   }
316 
TestTurnAlternateServer(cricket::ProtocolType protocol_type)317   void TestTurnAlternateServer(cricket::ProtocolType protocol_type) {
318     std::vector<rtc::SocketAddress> redirect_addresses;
319     redirect_addresses.push_back(kTurnAlternateIntAddr);
320 
321     cricket::TestTurnRedirector redirector(redirect_addresses);
322 
323     turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
324     turn_server_.AddInternalSocket(kTurnAlternateIntAddr, protocol_type);
325     turn_server_.set_redirect_hook(&redirector);
326     CreateTurnPort(kTurnUsername, kTurnPassword,
327                    cricket::ProtocolAddress(kTurnIntAddr, protocol_type));
328 
329     // Retrieve the address before we run the state machine.
330     const SocketAddress old_addr = turn_port_->server_address().address;
331 
332     turn_port_->PrepareAddress();
333     EXPECT_TRUE_WAIT(turn_ready_, kTimeout * 100);
334     // Retrieve the address again, the turn port's address should be
335     // changed.
336     const SocketAddress new_addr = turn_port_->server_address().address;
337     EXPECT_NE(old_addr, new_addr);
338     ASSERT_EQ(1U, turn_port_->Candidates().size());
339     EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
340               turn_port_->Candidates()[0].address().ipaddr());
341     EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
342   }
343 
TestTurnAlternateServerV4toV6(cricket::ProtocolType protocol_type)344   void TestTurnAlternateServerV4toV6(cricket::ProtocolType protocol_type) {
345     std::vector<rtc::SocketAddress> redirect_addresses;
346     redirect_addresses.push_back(kTurnIPv6IntAddr);
347 
348     cricket::TestTurnRedirector redirector(redirect_addresses);
349     turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
350     turn_server_.set_redirect_hook(&redirector);
351     CreateTurnPort(kTurnUsername, kTurnPassword,
352                    cricket::ProtocolAddress(kTurnIntAddr, protocol_type));
353     turn_port_->PrepareAddress();
354     EXPECT_TRUE_WAIT(turn_error_, kTimeout);
355   }
356 
TestTurnAlternateServerPingPong(cricket::ProtocolType protocol_type)357   void TestTurnAlternateServerPingPong(cricket::ProtocolType protocol_type) {
358     std::vector<rtc::SocketAddress> redirect_addresses;
359     redirect_addresses.push_back(kTurnAlternateIntAddr);
360     redirect_addresses.push_back(kTurnIntAddr);
361 
362     cricket::TestTurnRedirector redirector(redirect_addresses);
363 
364     turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
365     turn_server_.AddInternalSocket(kTurnAlternateIntAddr, protocol_type);
366     turn_server_.set_redirect_hook(&redirector);
367     CreateTurnPort(kTurnUsername, kTurnPassword,
368                    cricket::ProtocolAddress(kTurnIntAddr, protocol_type));
369 
370     turn_port_->PrepareAddress();
371     EXPECT_TRUE_WAIT(turn_error_, kTimeout);
372     ASSERT_EQ(0U, turn_port_->Candidates().size());
373     rtc::SocketAddress address;
374     // Verify that we have exhausted all alternate servers instead of
375     // failure caused by other errors.
376     EXPECT_FALSE(redirector.ShouldRedirect(address, &address));
377   }
378 
TestTurnAlternateServerDetectRepetition(cricket::ProtocolType protocol_type)379   void TestTurnAlternateServerDetectRepetition(
380       cricket::ProtocolType protocol_type) {
381     std::vector<rtc::SocketAddress> redirect_addresses;
382     redirect_addresses.push_back(kTurnAlternateIntAddr);
383     redirect_addresses.push_back(kTurnAlternateIntAddr);
384 
385     cricket::TestTurnRedirector redirector(redirect_addresses);
386 
387     turn_server_.AddInternalSocket(kTurnIntAddr, protocol_type);
388     turn_server_.AddInternalSocket(kTurnAlternateIntAddr, protocol_type);
389     turn_server_.set_redirect_hook(&redirector);
390     CreateTurnPort(kTurnUsername, kTurnPassword,
391                    cricket::ProtocolAddress(kTurnIntAddr, protocol_type));
392 
393     turn_port_->PrepareAddress();
394     EXPECT_TRUE_WAIT(turn_error_, kTimeout);
395     ASSERT_EQ(0U, turn_port_->Candidates().size());
396   }
397 
TestTurnConnection()398   void TestTurnConnection() {
399     // Create ports and prepare addresses.
400     PrepareTurnAndUdpPorts();
401 
402     // Send ping from UDP to TURN.
403     Connection* conn1 = udp_port_->CreateConnection(
404                     turn_port_->Candidates()[0], Port::ORIGIN_MESSAGE);
405     ASSERT_TRUE(conn1 != NULL);
406     conn1->Ping(0);
407     WAIT(!turn_unknown_address_, kTimeout);
408     EXPECT_FALSE(turn_unknown_address_);
409     EXPECT_FALSE(conn1->receiving());
410     EXPECT_EQ(Connection::STATE_WRITE_INIT, conn1->write_state());
411 
412     // Send ping from TURN to UDP.
413     Connection* conn2 = turn_port_->CreateConnection(
414                     udp_port_->Candidates()[0], Port::ORIGIN_MESSAGE);
415     ASSERT_TRUE(conn2 != NULL);
416     ASSERT_TRUE_WAIT(turn_create_permission_success_, kTimeout);
417     conn2->Ping(0);
418 
419     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, conn2->write_state(), kTimeout);
420     EXPECT_TRUE(conn1->receiving());
421     EXPECT_TRUE(conn2->receiving());
422     EXPECT_EQ(Connection::STATE_WRITE_INIT, conn1->write_state());
423 
424     // Send another ping from UDP to TURN.
425     conn1->Ping(0);
426     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, conn1->write_state(), kTimeout);
427     EXPECT_TRUE(conn2->receiving());
428   }
429 
TestDestroyTurnConnection()430   void TestDestroyTurnConnection() {
431     PrepareTurnAndUdpPorts();
432 
433     // Create connections on both ends.
434     Connection* conn1 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
435                                                     Port::ORIGIN_MESSAGE);
436     Connection* conn2 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
437                                                      Port::ORIGIN_MESSAGE);
438     ASSERT_TRUE(conn2 != NULL);
439     ASSERT_TRUE_WAIT(turn_create_permission_success_, kTimeout);
440     // Make sure turn connection can receive.
441     conn1->Ping(0);
442     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, conn1->write_state(), kTimeout);
443     EXPECT_FALSE(turn_unknown_address_);
444 
445     // Destroy the connection on the turn port. The TurnEntry is still
446     // there. So the turn port gets ping from unknown address if it is pinged.
447     conn2->Destroy();
448     conn1->Ping(0);
449     EXPECT_TRUE_WAIT(turn_unknown_address_, kTimeout);
450 
451     // Flush all requests in the invoker to destroy the TurnEntry.
452     // Now the turn port cannot receive the ping.
453     turn_unknown_address_ = false;
454     turn_port_->invoker()->Flush(rtc::Thread::Current());
455     conn1->Ping(0);
456     rtc::Thread::Current()->ProcessMessages(500);
457     EXPECT_FALSE(turn_unknown_address_);
458 
459     // If the connection is created again, it will start to receive pings.
460     conn2 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
461                                          Port::ORIGIN_MESSAGE);
462     conn1->Ping(0);
463     EXPECT_TRUE_WAIT(conn2->receiving(), kTimeout);
464     EXPECT_FALSE(turn_unknown_address_);
465   }
466 
TestTurnSendData()467   void TestTurnSendData() {
468     PrepareTurnAndUdpPorts();
469 
470     // Create connections and send pings.
471     Connection* conn1 = turn_port_->CreateConnection(
472         udp_port_->Candidates()[0], Port::ORIGIN_MESSAGE);
473     Connection* conn2 = udp_port_->CreateConnection(
474         turn_port_->Candidates()[0], Port::ORIGIN_MESSAGE);
475     ASSERT_TRUE(conn1 != NULL);
476     ASSERT_TRUE(conn2 != NULL);
477     conn1->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
478                                     &TurnPortTest::OnTurnReadPacket);
479     conn2->SignalReadPacket.connect(static_cast<TurnPortTest*>(this),
480                                     &TurnPortTest::OnUdpReadPacket);
481     conn1->Ping(0);
482     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, conn1->write_state(), kTimeout);
483     conn2->Ping(0);
484     EXPECT_EQ_WAIT(Connection::STATE_WRITABLE, conn2->write_state(), kTimeout);
485 
486     // Send some data.
487     size_t num_packets = 256;
488     for (size_t i = 0; i < num_packets; ++i) {
489       unsigned char buf[256] = { 0 };
490       for (size_t j = 0; j < i + 1; ++j) {
491         buf[j] = 0xFF - static_cast<unsigned char>(j);
492       }
493       conn1->Send(buf, i + 1, options);
494       conn2->Send(buf, i + 1, options);
495       main_->ProcessMessages(0);
496     }
497 
498     // Check the data.
499     ASSERT_EQ_WAIT(num_packets, turn_packets_.size(), kTimeout);
500     ASSERT_EQ_WAIT(num_packets, udp_packets_.size(), kTimeout);
501     for (size_t i = 0; i < num_packets; ++i) {
502       EXPECT_EQ(i + 1, turn_packets_[i].size());
503       EXPECT_EQ(i + 1, udp_packets_[i].size());
504       EXPECT_EQ(turn_packets_[i], udp_packets_[i]);
505     }
506   }
507 
508  protected:
509   rtc::Thread* main_;
510   rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
511   rtc::scoped_ptr<TurnPortTestVirtualSocketServer> ss_;
512   rtc::SocketServerScope ss_scope_;
513   rtc::Network network_;
514   rtc::BasicPacketSocketFactory socket_factory_;
515   rtc::scoped_ptr<rtc::AsyncPacketSocket> socket_;
516   cricket::TestTurnServer turn_server_;
517   rtc::scoped_ptr<TurnPort> turn_port_;
518   rtc::scoped_ptr<UDPPort> udp_port_;
519   bool turn_ready_;
520   bool turn_error_;
521   bool turn_unknown_address_;
522   bool turn_create_permission_success_;
523   bool udp_ready_;
524   bool test_finish_;
525   bool turn_refresh_success_ = false;
526   bool connection_destroyed_ = false;
527   std::vector<rtc::Buffer> turn_packets_;
528   std::vector<rtc::Buffer> udp_packets_;
529   rtc::PacketOptions options;
530 };
531 
532 // Do a normal TURN allocation.
TEST_F(TurnPortTest,TestTurnAllocate)533 TEST_F(TurnPortTest, TestTurnAllocate) {
534   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
535   EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10*1024));
536   turn_port_->PrepareAddress();
537   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
538   ASSERT_EQ(1U, turn_port_->Candidates().size());
539   EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
540             turn_port_->Candidates()[0].address().ipaddr());
541   EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
542 }
543 
544 // Testing a normal UDP allocation using TCP connection.
TEST_F(TurnPortTest,TestTurnTcpAllocate)545 TEST_F(TurnPortTest, TestTurnTcpAllocate) {
546   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
547   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
548   EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10*1024));
549   turn_port_->PrepareAddress();
550   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
551   ASSERT_EQ(1U, turn_port_->Candidates().size());
552   EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
553             turn_port_->Candidates()[0].address().ipaddr());
554   EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
555 }
556 
557 // Test case for WebRTC issue 3927 where a proxy binds to the local host address
558 // instead the address that TurnPort originally bound to. The candidate pair
559 // impacted by this behavior should still be used.
TEST_F(TurnPortTest,TestTurnTcpAllocationWhenProxyChangesAddressToLocalHost)560 TEST_F(TurnPortTest, TestTurnTcpAllocationWhenProxyChangesAddressToLocalHost) {
561   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
562   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
563   EXPECT_EQ(0, turn_port_->SetOption(rtc::Socket::OPT_SNDBUF, 10 * 1024));
564   turn_port_->PrepareAddress();
565   ConnectSignalAddressReadyToSetLocalhostAsAltenertativeLocalAddress();
566   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
567   ASSERT_EQ(1U, turn_port_->Candidates().size());
568   EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
569             turn_port_->Candidates()[0].address().ipaddr());
570   EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
571 }
572 
573 // Testing turn port will attempt to create TCP socket on address resolution
574 // failure.
TEST_F(TurnPortTest,DISABLED_TestTurnTcpOnAddressResolveFailure)575 TEST_F(TurnPortTest, DISABLED_TestTurnTcpOnAddressResolveFailure) {
576   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
577   CreateTurnPort(kTurnUsername, kTurnPassword, cricket::ProtocolAddress(
578       rtc::SocketAddress("www.webrtc-blah-blah.com", 3478),
579       cricket::PROTO_TCP));
580   turn_port_->PrepareAddress();
581   EXPECT_TRUE_WAIT(turn_error_, kTimeout);
582   // As VSS doesn't provide a DNS resolution, name resolve will fail. TurnPort
583   // will proceed in creating a TCP socket which will fail as there is no
584   // server on the above domain and error will be set to SOCKET_ERROR.
585   EXPECT_EQ(SOCKET_ERROR, turn_port_->error());
586 }
587 
588 // In case of UDP on address resolve failure, TurnPort will not create socket
589 // and return allocate failure.
TEST_F(TurnPortTest,DISABLED_TestTurnUdpOnAdressResolveFailure)590 TEST_F(TurnPortTest, DISABLED_TestTurnUdpOnAdressResolveFailure) {
591   CreateTurnPort(kTurnUsername, kTurnPassword, cricket::ProtocolAddress(
592       rtc::SocketAddress("www.webrtc-blah-blah.com", 3478),
593       cricket::PROTO_UDP));
594   turn_port_->PrepareAddress();
595   EXPECT_TRUE_WAIT(turn_error_, kTimeout);
596   // Error from turn port will not be socket error.
597   EXPECT_NE(SOCKET_ERROR, turn_port_->error());
598 }
599 
600 // Try to do a TURN allocation with an invalid password.
TEST_F(TurnPortTest,TestTurnAllocateBadPassword)601 TEST_F(TurnPortTest, TestTurnAllocateBadPassword) {
602   CreateTurnPort(kTurnUsername, "bad", kTurnUdpProtoAddr);
603   turn_port_->PrepareAddress();
604   EXPECT_TRUE_WAIT(turn_error_, kTimeout);
605   ASSERT_EQ(0U, turn_port_->Candidates().size());
606 }
607 
608 // Tests that a new local address is created after
609 // STUN_ERROR_ALLOCATION_MISMATCH.
TEST_F(TurnPortTest,TestTurnAllocateMismatch)610 TEST_F(TurnPortTest, TestTurnAllocateMismatch) {
611   // Do a normal allocation first.
612   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
613   turn_port_->PrepareAddress();
614   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
615   rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
616 
617   // Clear connected_ flag on turnport to suppress the release of
618   // the allocation.
619   turn_port_->OnSocketClose(turn_port_->socket(), 0);
620 
621   // Forces the socket server to assign the same port.
622   ss_->SetNextPortForTesting(first_addr.port());
623 
624   turn_ready_ = false;
625   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
626   turn_port_->PrepareAddress();
627 
628   // Verifies that the new port has the same address.
629   EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
630 
631   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
632 
633   // Verifies that the new port has a different address now.
634   EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
635 }
636 
637 // Tests that a shared-socket-TurnPort creates its own socket after
638 // STUN_ERROR_ALLOCATION_MISMATCH.
TEST_F(TurnPortTest,TestSharedSocketAllocateMismatch)639 TEST_F(TurnPortTest, TestSharedSocketAllocateMismatch) {
640   // Do a normal allocation first.
641   CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
642   turn_port_->PrepareAddress();
643   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
644   rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
645 
646   // Clear connected_ flag on turnport to suppress the release of
647   // the allocation.
648   turn_port_->OnSocketClose(turn_port_->socket(), 0);
649 
650   turn_ready_ = false;
651   CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
652 
653   // Verifies that the new port has the same address.
654   EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
655   EXPECT_TRUE(turn_port_->SharedSocket());
656 
657   turn_port_->PrepareAddress();
658   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
659 
660   // Verifies that the new port has a different address now.
661   EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
662   EXPECT_FALSE(turn_port_->SharedSocket());
663 }
664 
TEST_F(TurnPortTest,TestTurnTcpAllocateMismatch)665 TEST_F(TurnPortTest, TestTurnTcpAllocateMismatch) {
666   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
667   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
668 
669   // Do a normal allocation first.
670   turn_port_->PrepareAddress();
671   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
672   rtc::SocketAddress first_addr(turn_port_->socket()->GetLocalAddress());
673 
674   // Clear connected_ flag on turnport to suppress the release of
675   // the allocation.
676   turn_port_->OnSocketClose(turn_port_->socket(), 0);
677 
678   // Forces the socket server to assign the same port.
679   ss_->SetNextPortForTesting(first_addr.port());
680 
681   turn_ready_ = false;
682   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
683   turn_port_->PrepareAddress();
684 
685   // Verifies that the new port has the same address.
686   EXPECT_EQ(first_addr, turn_port_->socket()->GetLocalAddress());
687 
688   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
689 
690   // Verifies that the new port has a different address now.
691   EXPECT_NE(first_addr, turn_port_->socket()->GetLocalAddress());
692 }
693 
TEST_F(TurnPortTest,TestRefreshRequestGetsErrorResponse)694 TEST_F(TurnPortTest, TestRefreshRequestGetsErrorResponse) {
695   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
696   PrepareTurnAndUdpPorts();
697   turn_port_->CreateConnection(udp_port_->Candidates()[0],
698                                Port::ORIGIN_MESSAGE);
699   // Set bad credentials.
700   cricket::RelayCredentials bad_credentials("bad_user", "bad_pwd");
701   turn_port_->set_credentials(bad_credentials);
702   turn_refresh_success_ = false;
703   // This sends out the first RefreshRequest with correct credentials.
704   // When this succeeds, it will schedule a new RefreshRequest with the bad
705   // credential.
706   turn_port_->FlushRequests(cricket::TURN_REFRESH_REQUEST);
707   EXPECT_TRUE_WAIT(turn_refresh_success_, kTimeout);
708   // Flush it again, it will receive a bad response.
709   turn_port_->FlushRequests(cricket::TURN_REFRESH_REQUEST);
710   EXPECT_TRUE_WAIT(!turn_refresh_success_, kTimeout);
711   EXPECT_TRUE_WAIT(!turn_port_->connected(), kTimeout);
712   EXPECT_TRUE_WAIT(turn_port_->connections().empty(), kTimeout);
713   EXPECT_FALSE(turn_port_->HasRequests());
714 }
715 
716 // Test that CreateConnection will return null if port becomes disconnected.
TEST_F(TurnPortTest,TestCreateConnectionWhenSocketClosed)717 TEST_F(TurnPortTest, TestCreateConnectionWhenSocketClosed) {
718   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
719   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
720   PrepareTurnAndUdpPorts();
721   // Create a connection.
722   Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
723                                                    Port::ORIGIN_MESSAGE);
724   ASSERT_TRUE(conn1 != NULL);
725 
726   // Close the socket and create a connection again.
727   turn_port_->OnSocketClose(turn_port_->socket(), 1);
728   conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
729                                        Port::ORIGIN_MESSAGE);
730   ASSERT_TRUE(conn1 == NULL);
731 }
732 
733 // Test try-alternate-server feature.
TEST_F(TurnPortTest,TestTurnAlternateServerUDP)734 TEST_F(TurnPortTest, TestTurnAlternateServerUDP) {
735   TestTurnAlternateServer(cricket::PROTO_UDP);
736 }
737 
TEST_F(TurnPortTest,TestTurnAlternateServerTCP)738 TEST_F(TurnPortTest, TestTurnAlternateServerTCP) {
739   TestTurnAlternateServer(cricket::PROTO_TCP);
740 }
741 
742 // Test that we fail when we redirect to an address different from
743 // current IP family.
TEST_F(TurnPortTest,TestTurnAlternateServerV4toV6UDP)744 TEST_F(TurnPortTest, TestTurnAlternateServerV4toV6UDP) {
745   TestTurnAlternateServerV4toV6(cricket::PROTO_UDP);
746 }
747 
TEST_F(TurnPortTest,TestTurnAlternateServerV4toV6TCP)748 TEST_F(TurnPortTest, TestTurnAlternateServerV4toV6TCP) {
749   TestTurnAlternateServerV4toV6(cricket::PROTO_TCP);
750 }
751 
752 // Test try-alternate-server catches the case of pingpong.
TEST_F(TurnPortTest,TestTurnAlternateServerPingPongUDP)753 TEST_F(TurnPortTest, TestTurnAlternateServerPingPongUDP) {
754   TestTurnAlternateServerPingPong(cricket::PROTO_UDP);
755 }
756 
TEST_F(TurnPortTest,TestTurnAlternateServerPingPongTCP)757 TEST_F(TurnPortTest, TestTurnAlternateServerPingPongTCP) {
758   TestTurnAlternateServerPingPong(cricket::PROTO_TCP);
759 }
760 
761 // Test try-alternate-server catch the case of repeated server.
TEST_F(TurnPortTest,TestTurnAlternateServerDetectRepetitionUDP)762 TEST_F(TurnPortTest, TestTurnAlternateServerDetectRepetitionUDP) {
763   TestTurnAlternateServerDetectRepetition(cricket::PROTO_UDP);
764 }
765 
TEST_F(TurnPortTest,TestTurnAlternateServerDetectRepetitionTCP)766 TEST_F(TurnPortTest, TestTurnAlternateServerDetectRepetitionTCP) {
767   TestTurnAlternateServerDetectRepetition(cricket::PROTO_TCP);
768 }
769 
770 // Do a TURN allocation and try to send a packet to it from the outside.
771 // The packet should be dropped. Then, try to send a packet from TURN to the
772 // outside. It should reach its destination. Finally, try again from the
773 // outside. It should now work as well.
TEST_F(TurnPortTest,TestTurnConnection)774 TEST_F(TurnPortTest, TestTurnConnection) {
775   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
776   TestTurnConnection();
777 }
778 
779 // Similar to above, except that this test will use the shared socket.
TEST_F(TurnPortTest,TestTurnConnectionUsingSharedSocket)780 TEST_F(TurnPortTest, TestTurnConnectionUsingSharedSocket) {
781   CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
782   TestTurnConnection();
783 }
784 
785 // Test that we can establish a TCP connection with TURN server.
TEST_F(TurnPortTest,TestTurnTcpConnection)786 TEST_F(TurnPortTest, TestTurnTcpConnection) {
787   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
788   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
789   TestTurnConnection();
790 }
791 
792 // Test that if a connection on a TURN port is destroyed, the TURN port can
793 // still receive ping on that connection as if it is from an unknown address.
794 // If the connection is created again, it will be used to receive ping.
TEST_F(TurnPortTest,TestDestroyTurnConnection)795 TEST_F(TurnPortTest, TestDestroyTurnConnection) {
796   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
797   TestDestroyTurnConnection();
798 }
799 
800 // Similar to above, except that this test will use the shared socket.
TEST_F(TurnPortTest,TestDestroyTurnConnectionUsingSharedSocket)801 TEST_F(TurnPortTest, TestDestroyTurnConnectionUsingSharedSocket) {
802   CreateSharedTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
803   TestDestroyTurnConnection();
804 }
805 
806 // Test that we fail to create a connection when we want to use TLS over TCP.
807 // This test should be removed once we have TLS support.
TEST_F(TurnPortTest,TestTurnTlsTcpConnectionFails)808 TEST_F(TurnPortTest, TestTurnTlsTcpConnectionFails) {
809   cricket::ProtocolAddress secure_addr(kTurnTcpProtoAddr.address,
810                                        kTurnTcpProtoAddr.proto,
811                                        true);
812   CreateTurnPort(kTurnUsername, kTurnPassword, secure_addr);
813   turn_port_->PrepareAddress();
814   EXPECT_TRUE_WAIT(turn_error_, kTimeout);
815   ASSERT_EQ(0U, turn_port_->Candidates().size());
816 }
817 
818 // Run TurnConnectionTest with one-time-use nonce feature.
819 // Here server will send a 438 STALE_NONCE error message for
820 // every TURN transaction.
TEST_F(TurnPortTest,TestTurnConnectionUsingOTUNonce)821 TEST_F(TurnPortTest, TestTurnConnectionUsingOTUNonce) {
822   turn_server_.set_enable_otu_nonce(true);
823   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
824   TestTurnConnection();
825 }
826 
827 // Test that CreatePermissionRequest will be scheduled after the success
828 // of the first create permission request and the request will get an
829 // ErrorResponse if the ufrag and pwd are incorrect.
TEST_F(TurnPortTest,TestRefreshCreatePermissionRequest)830 TEST_F(TurnPortTest, TestRefreshCreatePermissionRequest) {
831   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
832   PrepareTurnAndUdpPorts();
833 
834   Connection* conn = turn_port_->CreateConnection(udp_port_->Candidates()[0],
835                                                   Port::ORIGIN_MESSAGE);
836   ConnectConnectionDestroyedSignal(conn);
837   ASSERT_TRUE(conn != NULL);
838   ASSERT_TRUE_WAIT(turn_create_permission_success_, kTimeout);
839   turn_create_permission_success_ = false;
840   // A create-permission-request should be pending.
841   // After the next create-permission-response is received, it will schedule
842   // another request with bad_ufrag and bad_pwd.
843   cricket::RelayCredentials bad_credentials("bad_user", "bad_pwd");
844   turn_port_->set_credentials(bad_credentials);
845   turn_port_->FlushRequests(cricket::kAllRequests);
846   ASSERT_TRUE_WAIT(turn_create_permission_success_, kTimeout);
847   // Flush the requests again; the create-permission-request will fail.
848   turn_port_->FlushRequests(cricket::kAllRequests);
849   EXPECT_TRUE_WAIT(!turn_create_permission_success_, kTimeout);
850   EXPECT_TRUE_WAIT(connection_destroyed_, kTimeout);
851 }
852 
TEST_F(TurnPortTest,TestChannelBindGetErrorResponse)853 TEST_F(TurnPortTest, TestChannelBindGetErrorResponse) {
854   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
855   PrepareTurnAndUdpPorts();
856   Connection* conn1 = turn_port_->CreateConnection(udp_port_->Candidates()[0],
857                                                    Port::ORIGIN_MESSAGE);
858   ASSERT_TRUE(conn1 != nullptr);
859   Connection* conn2 = udp_port_->CreateConnection(turn_port_->Candidates()[0],
860                                                   Port::ORIGIN_MESSAGE);
861   ASSERT_TRUE(conn2 != nullptr);
862   ConnectConnectionDestroyedSignal(conn1);
863   conn1->Ping(0);
864   ASSERT_TRUE_WAIT(conn1->writable(), kTimeout);
865 
866   std::string data = "ABC";
867   conn1->Send(data.data(), data.length(), options);
868   bool success =
869       turn_port_->SetEntryChannelId(udp_port_->Candidates()[0].address(), -1);
870   ASSERT_TRUE(success);
871   // Next time when the binding request is sent, it will get an ErrorResponse.
872   EXPECT_TRUE_WAIT(CheckConnectionDestroyed(), kTimeout);
873 }
874 
875 // Do a TURN allocation, establish a UDP connection, and send some data.
TEST_F(TurnPortTest,TestTurnSendDataTurnUdpToUdp)876 TEST_F(TurnPortTest, TestTurnSendDataTurnUdpToUdp) {
877   // Create ports and prepare addresses.
878   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
879   TestTurnSendData();
880   EXPECT_EQ(cricket::UDP_PROTOCOL_NAME,
881             turn_port_->Candidates()[0].relay_protocol());
882 }
883 
884 // Do a TURN allocation, establish a TCP connection, and send some data.
TEST_F(TurnPortTest,TestTurnSendDataTurnTcpToUdp)885 TEST_F(TurnPortTest, TestTurnSendDataTurnTcpToUdp) {
886   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
887   // Create ports and prepare addresses.
888   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
889   TestTurnSendData();
890   EXPECT_EQ(cricket::TCP_PROTOCOL_NAME,
891             turn_port_->Candidates()[0].relay_protocol());
892 }
893 
894 // Test TURN fails to make a connection from IPv6 address to a server which has
895 // IPv4 address.
TEST_F(TurnPortTest,TestTurnLocalIPv6AddressServerIPv4)896 TEST_F(TurnPortTest, TestTurnLocalIPv6AddressServerIPv4) {
897   turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, cricket::PROTO_UDP);
898   CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
899                  kTurnUdpProtoAddr);
900   turn_port_->PrepareAddress();
901   ASSERT_TRUE_WAIT(turn_error_, kTimeout);
902   EXPECT_TRUE(turn_port_->Candidates().empty());
903 }
904 
905 // Test TURN make a connection from IPv6 address to a server which has
906 // IPv6 intenal address. But in this test external address is a IPv4 address,
907 // hence allocated address will be a IPv4 address.
TEST_F(TurnPortTest,TestTurnLocalIPv6AddressServerIPv6ExtenalIPv4)908 TEST_F(TurnPortTest, TestTurnLocalIPv6AddressServerIPv6ExtenalIPv4) {
909   turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, cricket::PROTO_UDP);
910   CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
911                  kTurnUdpIPv6ProtoAddr);
912   turn_port_->PrepareAddress();
913   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
914   ASSERT_EQ(1U, turn_port_->Candidates().size());
915   EXPECT_EQ(kTurnUdpExtAddr.ipaddr(),
916             turn_port_->Candidates()[0].address().ipaddr());
917   EXPECT_NE(0, turn_port_->Candidates()[0].address().port());
918 }
919 
TEST_F(TurnPortTest,TestOriginHeader)920 TEST_F(TurnPortTest, TestOriginHeader) {
921   CreateTurnPortWithOrigin(kLocalAddr1, kTurnUsername, kTurnPassword,
922                            kTurnUdpProtoAddr, kTestOrigin);
923   turn_port_->PrepareAddress();
924   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
925   ASSERT_GT(turn_server_.server()->allocations().size(), 0U);
926   SocketAddress local_address = turn_port_->GetLocalAddress();
927   ASSERT_TRUE(turn_server_.FindAllocation(local_address) != NULL);
928   EXPECT_EQ(kTestOrigin, turn_server_.FindAllocation(local_address)->origin());
929 }
930 
931 // Test that a CreatePermission failure will result in the connection being
932 // destroyed.
TEST_F(TurnPortTest,TestConnectionDestroyedOnCreatePermissionFailure)933 TEST_F(TurnPortTest, TestConnectionDestroyedOnCreatePermissionFailure) {
934   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
935   turn_server_.server()->set_reject_private_addresses(true);
936   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
937   turn_port_->PrepareAddress();
938   ASSERT_TRUE_WAIT(turn_ready_, kTimeout);
939 
940   CreateUdpPort(SocketAddress("10.0.0.10", 0));
941   udp_port_->PrepareAddress();
942   ASSERT_TRUE_WAIT(udp_ready_, kTimeout);
943   // Create a connection.
944   TestConnectionWrapper conn(turn_port_->CreateConnection(
945       udp_port_->Candidates()[0], Port::ORIGIN_MESSAGE));
946   ASSERT_TRUE(conn.connection() != nullptr);
947 
948   // Asynchronously, CreatePermission request should be sent and fail, closing
949   // the connection.
950   EXPECT_TRUE_WAIT(conn.connection() == nullptr, kTimeout);
951   EXPECT_FALSE(turn_create_permission_success_);
952 }
953 
954 // Test that a TURN allocation is released when the port is closed.
TEST_F(TurnPortTest,TestTurnReleaseAllocation)955 TEST_F(TurnPortTest, TestTurnReleaseAllocation) {
956   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnUdpProtoAddr);
957   turn_port_->PrepareAddress();
958   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
959 
960   ASSERT_GT(turn_server_.server()->allocations().size(), 0U);
961   turn_port_.reset();
962   EXPECT_EQ_WAIT(0U, turn_server_.server()->allocations().size(), kTimeout);
963 }
964 
965 // Test that a TURN TCP allocation is released when the port is closed.
TEST_F(TurnPortTest,DISABLED_TestTurnTCPReleaseAllocation)966 TEST_F(TurnPortTest, DISABLED_TestTurnTCPReleaseAllocation) {
967   turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
968   CreateTurnPort(kTurnUsername, kTurnPassword, kTurnTcpProtoAddr);
969   turn_port_->PrepareAddress();
970   EXPECT_TRUE_WAIT(turn_ready_, kTimeout);
971 
972   ASSERT_GT(turn_server_.server()->allocations().size(), 0U);
973   turn_port_.reset();
974   EXPECT_EQ_WAIT(0U, turn_server_.server()->allocations().size(), kTimeout);
975 }
976 
977 // This test verifies any FD's are not leaked after TurnPort is destroyed.
978 // https://code.google.com/p/webrtc/issues/detail?id=2651
979 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
980 // 1 second is not always enough for getaddrinfo().
981 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=5191
982 static const unsigned int kResolverTimeout = 10000;
983 
TEST_F(TurnPortTest,TestResolverShutdown)984 TEST_F(TurnPortTest, TestResolverShutdown) {
985   turn_server_.AddInternalSocket(kTurnUdpIPv6IntAddr, cricket::PROTO_UDP);
986   int last_fd_count = GetFDCount();
987   // Need to supply unresolved address to kick off resolver.
988   CreateTurnPort(kLocalIPv6Addr, kTurnUsername, kTurnPassword,
989                  cricket::ProtocolAddress(rtc::SocketAddress(
990                     "www.google.invalid", 3478), cricket::PROTO_UDP));
991   turn_port_->PrepareAddress();
992   ASSERT_TRUE_WAIT(turn_error_, kResolverTimeout);
993   EXPECT_TRUE(turn_port_->Candidates().empty());
994   turn_port_.reset();
995   rtc::Thread::Current()->Post(this, MSG_TESTFINISH);
996   // Waiting for above message to be processed.
997   ASSERT_TRUE_WAIT(test_finish_, kTimeout);
998   EXPECT_EQ(last_fd_count, GetFDCount());
999 }
1000 #endif
1001