• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2016 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "p2p/base/tcp_port.h"
12 
13 #include <list>
14 #include <memory>
15 #include <vector>
16 
17 #include "p2p/base/basic_packet_socket_factory.h"
18 #include "p2p/base/p2p_constants.h"
19 #include "p2p/base/transport_description.h"
20 #include "rtc_base/gunit.h"
21 #include "rtc_base/helpers.h"
22 #include "rtc_base/ip_address.h"
23 #include "rtc_base/third_party/sigslot/sigslot.h"
24 #include "rtc_base/thread.h"
25 #include "rtc_base/time_utils.h"
26 #include "rtc_base/virtual_socket_server.h"
27 #include "test/gtest.h"
28 
29 using cricket::Connection;
30 using cricket::ICE_PWD_LENGTH;
31 using cricket::ICE_UFRAG_LENGTH;
32 using cricket::Port;
33 using cricket::TCPPort;
34 using rtc::SocketAddress;
35 
36 static int kTimeout = 1000;
37 static const SocketAddress kLocalAddr("11.11.11.11", 0);
38 static const SocketAddress kLocalIPv6Addr("2401:fa00:4:1000:be30:5bff:fee5:c3",
39                                           0);
40 static const SocketAddress kAlternateLocalAddr("1.2.3.4", 0);
41 static const SocketAddress kRemoteAddr("22.22.22.22", 0);
42 static const SocketAddress kRemoteIPv6Addr("2401:fa00:4:1000:be30:5bff:fee5:c4",
43                                            0);
44 
45 class ConnectionObserver : public sigslot::has_slots<> {
46  public:
ConnectionObserver(Connection * conn)47   explicit ConnectionObserver(Connection* conn) {
48     conn->SignalDestroyed.connect(this, &ConnectionObserver::OnDestroyed);
49   }
50 
connection_destroyed()51   bool connection_destroyed() { return connection_destroyed_; }
52 
53  private:
OnDestroyed(Connection *)54   void OnDestroyed(Connection*) { connection_destroyed_ = true; }
55 
56   bool connection_destroyed_ = false;
57 };
58 
59 class TCPPortTest : public ::testing::Test, public sigslot::has_slots<> {
60  public:
TCPPortTest()61   TCPPortTest()
62       : ss_(new rtc::VirtualSocketServer()),
63         main_(ss_.get()),
64         socket_factory_(rtc::Thread::Current()),
65         username_(rtc::CreateRandomString(ICE_UFRAG_LENGTH)),
66         password_(rtc::CreateRandomString(ICE_PWD_LENGTH)) {}
67 
MakeNetwork(const SocketAddress & addr)68   rtc::Network* MakeNetwork(const SocketAddress& addr) {
69     networks_.emplace_back("unittest", "unittest", addr.ipaddr(), 32);
70     networks_.back().AddIP(addr.ipaddr());
71     return &networks_.back();
72   }
73 
CreateTCPPort(const SocketAddress & addr)74   std::unique_ptr<TCPPort> CreateTCPPort(const SocketAddress& addr) {
75     return std::unique_ptr<TCPPort>(
76         TCPPort::Create(&main_, &socket_factory_, MakeNetwork(addr), 0, 0,
77                         username_, password_, true));
78   }
79 
CreateTCPPort(rtc::Network * network)80   std::unique_ptr<TCPPort> CreateTCPPort(rtc::Network* network) {
81     return std::unique_ptr<TCPPort>(TCPPort::Create(
82         &main_, &socket_factory_, network, 0, 0, username_, password_, true));
83   }
84 
85  protected:
86   // When a "create port" helper method is called with an IP, we create a
87   // Network with that IP and add it to this list. Using a list instead of a
88   // vector so that when it grows, pointers aren't invalidated.
89   std::list<rtc::Network> networks_;
90   std::unique_ptr<rtc::VirtualSocketServer> ss_;
91   rtc::AutoSocketServerThread main_;
92   rtc::BasicPacketSocketFactory socket_factory_;
93   std::string username_;
94   std::string password_;
95 };
96 
TEST_F(TCPPortTest,TestTCPPortWithLocalhostAddress)97 TEST_F(TCPPortTest, TestTCPPortWithLocalhostAddress) {
98   SocketAddress local_address("127.0.0.1", 0);
99   // After calling this, when TCPPort attempts to get a socket bound to
100   // kLocalAddr, it will end up using localhost instead.
101   ss_->SetAlternativeLocalAddress(kLocalAddr.ipaddr(), local_address.ipaddr());
102   auto local_port = CreateTCPPort(kLocalAddr);
103   auto remote_port = CreateTCPPort(kRemoteAddr);
104   local_port->PrepareAddress();
105   remote_port->PrepareAddress();
106   Connection* conn = local_port->CreateConnection(remote_port->Candidates()[0],
107                                                   Port::ORIGIN_MESSAGE);
108   EXPECT_TRUE_WAIT(conn->connected(), kTimeout);
109   // Verify that the socket actually used localhost, otherwise this test isn't
110   // doing what it meant to.
111   ASSERT_EQ(local_address.ipaddr(),
112             local_port->Candidates()[0].address().ipaddr());
113 }
114 
115 // If the address the socket ends up bound to does not match any address of the
116 // TCPPort's Network, then the socket should be discarded and no candidates
117 // should be signaled. In the context of ICE, where one TCPPort is created for
118 // each Network, when this happens it's likely that the unexpected address is
119 // associated with some other Network, which another TCPPort is already
120 // covering.
TEST_F(TCPPortTest,TCPPortDiscardedIfBoundAddressDoesNotMatchNetwork)121 TEST_F(TCPPortTest, TCPPortDiscardedIfBoundAddressDoesNotMatchNetwork) {
122   // Sockets bound to kLocalAddr will actually end up with kAlternateLocalAddr.
123   ss_->SetAlternativeLocalAddress(kLocalAddr.ipaddr(),
124                                   kAlternateLocalAddr.ipaddr());
125 
126   // Create ports (local_port is the one whose IP will end up reassigned).
127   auto local_port = CreateTCPPort(kLocalAddr);
128   auto remote_port = CreateTCPPort(kRemoteAddr);
129   local_port->PrepareAddress();
130   remote_port->PrepareAddress();
131 
132   // Tell port to create a connection; it should be destroyed when it's
133   // realized that it's using an unexpected address.
134   Connection* conn = local_port->CreateConnection(remote_port->Candidates()[0],
135                                                   Port::ORIGIN_MESSAGE);
136   ConnectionObserver observer(conn);
137   EXPECT_TRUE_WAIT(observer.connection_destroyed(), kTimeout);
138 }
139 
140 // A caveat for the above logic: if the socket ends up bound to one of the IPs
141 // associated with the Network, just not the "best" one, this is ok.
TEST_F(TCPPortTest,TCPPortNotDiscardedIfNotBoundToBestIP)142 TEST_F(TCPPortTest, TCPPortNotDiscardedIfNotBoundToBestIP) {
143   // Sockets bound to kLocalAddr will actually end up with kAlternateLocalAddr.
144   ss_->SetAlternativeLocalAddress(kLocalAddr.ipaddr(),
145                                   kAlternateLocalAddr.ipaddr());
146 
147   // Set up a network with kLocalAddr1 as the "best" IP, and kAlternateLocalAddr
148   // as an alternate.
149   rtc::Network* network = MakeNetwork(kLocalAddr);
150   network->AddIP(kAlternateLocalAddr.ipaddr());
151   ASSERT_EQ(kLocalAddr.ipaddr(), network->GetBestIP());
152 
153   // Create ports (using our special 2-IP Network for local_port).
154   auto local_port = CreateTCPPort(network);
155   auto remote_port = CreateTCPPort(kRemoteAddr);
156   local_port->PrepareAddress();
157   remote_port->PrepareAddress();
158 
159   // Expect connection to succeed.
160   Connection* conn = local_port->CreateConnection(remote_port->Candidates()[0],
161                                                   Port::ORIGIN_MESSAGE);
162   EXPECT_TRUE_WAIT(conn->connected(), kTimeout);
163 
164   // Verify that the socket actually used the alternate address, otherwise this
165   // test isn't doing what it meant to.
166   ASSERT_EQ(kAlternateLocalAddr.ipaddr(),
167             local_port->Candidates()[0].address().ipaddr());
168 }
169 
170 // Regression test for crbug.com/webrtc/8972, caused by buggy comparison
171 // between rtc::IPAddress and rtc::InterfaceAddress.
TEST_F(TCPPortTest,TCPPortNotDiscardedIfBoundToTemporaryIP)172 TEST_F(TCPPortTest, TCPPortNotDiscardedIfBoundToTemporaryIP) {
173   networks_.emplace_back("unittest", "unittest", kLocalIPv6Addr.ipaddr(), 32);
174   networks_.back().AddIP(rtc::InterfaceAddress(
175       kLocalIPv6Addr.ipaddr(), rtc::IPV6_ADDRESS_FLAG_TEMPORARY));
176 
177   auto local_port = CreateTCPPort(&networks_.back());
178   auto remote_port = CreateTCPPort(kRemoteIPv6Addr);
179   local_port->PrepareAddress();
180   remote_port->PrepareAddress();
181 
182   // Connection should succeed if the port isn't discarded.
183   Connection* conn = local_port->CreateConnection(remote_port->Candidates()[0],
184                                                   Port::ORIGIN_MESSAGE);
185   ASSERT_NE(nullptr, conn);
186   EXPECT_TRUE_WAIT(conn->connected(), kTimeout);
187 }
188 
189 class SentPacketCounter : public sigslot::has_slots<> {
190  public:
SentPacketCounter(TCPPort * p)191   explicit SentPacketCounter(TCPPort* p) {
192     p->SignalSentPacket.connect(this, &SentPacketCounter::OnSentPacket);
193   }
194 
sent_packets() const195   int sent_packets() const { return sent_packets_; }
196 
197  private:
OnSentPacket(const rtc::SentPacket &)198   void OnSentPacket(const rtc::SentPacket&) { ++sent_packets_; }
199 
200   int sent_packets_ = 0;
201 };
202 
203 // Test that SignalSentPacket is fired when a packet is successfully sent, for
204 // both TCP client and server sockets.
TEST_F(TCPPortTest,SignalSentPacket)205 TEST_F(TCPPortTest, SignalSentPacket) {
206   std::unique_ptr<TCPPort> client(CreateTCPPort(kLocalAddr));
207   std::unique_ptr<TCPPort> server(CreateTCPPort(kRemoteAddr));
208   client->SetIceRole(cricket::ICEROLE_CONTROLLING);
209   server->SetIceRole(cricket::ICEROLE_CONTROLLED);
210   client->PrepareAddress();
211   server->PrepareAddress();
212 
213   Connection* client_conn =
214       client->CreateConnection(server->Candidates()[0], Port::ORIGIN_MESSAGE);
215   ASSERT_NE(nullptr, client_conn);
216   ASSERT_TRUE_WAIT(client_conn->connected(), kTimeout);
217 
218   // Need to get the port of the actual outgoing socket, not the server socket..
219   cricket::Candidate client_candidate = client->Candidates()[0];
220   client_candidate.set_address(static_cast<cricket::TCPConnection*>(client_conn)
221                                    ->socket()
222                                    ->GetLocalAddress());
223   Connection* server_conn =
224       server->CreateConnection(client_candidate, Port::ORIGIN_THIS_PORT);
225   ASSERT_NE(nullptr, server_conn);
226   ASSERT_TRUE_WAIT(server_conn->connected(), kTimeout);
227 
228   client_conn->Ping(rtc::TimeMillis());
229   server_conn->Ping(rtc::TimeMillis());
230   ASSERT_TRUE_WAIT(client_conn->writable(), kTimeout);
231   ASSERT_TRUE_WAIT(server_conn->writable(), kTimeout);
232 
233   SentPacketCounter client_counter(client.get());
234   SentPacketCounter server_counter(server.get());
235   static const char kData[] = "hello";
236   for (int i = 0; i < 10; ++i) {
237     client_conn->Send(&kData, sizeof(kData), rtc::PacketOptions());
238     server_conn->Send(&kData, sizeof(kData), rtc::PacketOptions());
239   }
240   EXPECT_EQ_WAIT(10, client_counter.sent_packets(), kTimeout);
241   EXPECT_EQ_WAIT(10, server_counter.sent_packets(), kTimeout);
242 }
243