1 /*
2 * libjingle
3 * Copyright 2009 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include "talk/base/logging.h"
29 #include "talk/base/gunit.h"
30 #include "talk/base/helpers.h"
31 #include "talk/base/physicalsocketserver.h"
32 #include "talk/base/scoped_ptr.h"
33 #include "talk/base/socketadapters.h"
34 #include "talk/base/socketaddress.h"
35 #include "talk/base/thread.h"
36 #include "talk/base/virtualsocketserver.h"
37 #include "talk/p2p/base/basicpacketsocketfactory.h"
38 #include "talk/p2p/base/relayport.h"
39 #include "talk/p2p/base/relayserver.h"
40
41 using talk_base::SocketAddress;
42
43 static const SocketAddress kLocalAddress = SocketAddress("192.168.1.2", 0);
44 static const SocketAddress kRelayUdpAddr = SocketAddress("99.99.99.1", 5000);
45 static const SocketAddress kRelayTcpAddr = SocketAddress("99.99.99.2", 5001);
46 static const SocketAddress kRelaySslAddr = SocketAddress("99.99.99.3", 443);
47 static const SocketAddress kRelayExtAddr = SocketAddress("99.99.99.3", 5002);
48
49 static const int kTimeoutMs = 1000;
50 static const int kMaxTimeoutMs = 5000;
51
52 // Tests connecting a RelayPort to a fake relay server
53 // (cricket::RelayServer) using all currently available protocols. The
54 // network layer is faked out by using a VirtualSocketServer for
55 // creating sockets. The test will monitor the current state of the
56 // RelayPort and created sockets by listening for signals such as,
57 // SignalConnectFailure, SignalConnectTimeout, SignalSocketClosed and
58 // SignalReadPacket.
59 class RelayPortTest : public testing::Test,
60 public sigslot::has_slots<> {
61 public:
RelayPortTest()62 RelayPortTest()
63 : main_(talk_base::Thread::Current()),
64 physical_socket_server_(new talk_base::PhysicalSocketServer),
65 virtual_socket_server_(new talk_base::VirtualSocketServer(
66 physical_socket_server_.get())),
67 ss_scope_(virtual_socket_server_.get()),
68 network_("unittest", "unittest", talk_base::IPAddress(INADDR_ANY), 32),
69 socket_factory_(talk_base::Thread::Current()),
70 username_(talk_base::CreateRandomString(16)),
71 password_(talk_base::CreateRandomString(16)),
72 relay_port_(cricket::RelayPort::Create(main_, &socket_factory_,
73 &network_,
74 kLocalAddress.ipaddr(),
75 0, 0, username_, password_)),
76 relay_server_(new cricket::RelayServer(main_)) {
77 }
78
OnReadPacket(talk_base::AsyncPacketSocket * socket,const char * data,size_t size,const talk_base::SocketAddress & remote_addr,const talk_base::PacketTime & packet_time)79 void OnReadPacket(talk_base::AsyncPacketSocket* socket,
80 const char* data, size_t size,
81 const talk_base::SocketAddress& remote_addr,
82 const talk_base::PacketTime& packet_time) {
83 received_packet_count_[socket]++;
84 }
85
OnConnectFailure(const cricket::ProtocolAddress * addr)86 void OnConnectFailure(const cricket::ProtocolAddress* addr) {
87 failed_connections_.push_back(*addr);
88 }
89
OnSoftTimeout(const cricket::ProtocolAddress * addr)90 void OnSoftTimeout(const cricket::ProtocolAddress* addr) {
91 soft_timedout_connections_.push_back(*addr);
92 }
93
94 protected:
SetUpTestCase()95 static void SetUpTestCase() {
96 // Ensure the RNG is inited.
97 talk_base::InitRandom(NULL, 0);
98 }
99
SetUp()100 virtual void SetUp() {
101 // The relay server needs an external socket to work properly.
102 talk_base::AsyncUDPSocket* ext_socket =
103 CreateAsyncUdpSocket(kRelayExtAddr);
104 relay_server_->AddExternalSocket(ext_socket);
105
106 // Listen for failures.
107 relay_port_->SignalConnectFailure.
108 connect(this, &RelayPortTest::OnConnectFailure);
109
110 // Listen for soft timeouts.
111 relay_port_->SignalSoftTimeout.
112 connect(this, &RelayPortTest::OnSoftTimeout);
113 }
114
115 // Udp has the highest 'goodness' value of the three different
116 // protocols used for connecting to the relay server. As soon as
117 // PrepareAddress is called, the RelayPort will start trying to
118 // connect to the given UDP address. As soon as a response to the
119 // sent STUN allocate request message has been received, the
120 // RelayPort will consider the connection to be complete and will
121 // abort any other connection attempts.
TestConnectUdp()122 void TestConnectUdp() {
123 // Add a UDP socket to the relay server.
124 talk_base::AsyncUDPSocket* internal_udp_socket =
125 CreateAsyncUdpSocket(kRelayUdpAddr);
126 talk_base::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
127
128 relay_server_->AddInternalSocket(internal_udp_socket);
129 relay_server_->AddInternalServerSocket(server_socket, cricket::PROTO_TCP);
130
131 // Now add our relay addresses to the relay port and let it start.
132 relay_port_->AddServerAddress(
133 cricket::ProtocolAddress(kRelayUdpAddr, cricket::PROTO_UDP));
134 relay_port_->AddServerAddress(
135 cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP));
136 relay_port_->PrepareAddress();
137
138 // Should be connected.
139 EXPECT_TRUE_WAIT(relay_port_->IsReady(), kTimeoutMs);
140
141 // Make sure that we are happy with UDP, ie. not continuing with
142 // TCP, SSLTCP, etc.
143 WAIT(relay_server_->HasConnection(kRelayTcpAddr), kTimeoutMs);
144
145 // Should have only one connection.
146 EXPECT_EQ(1, relay_server_->GetConnectionCount());
147
148 // Should be the UDP address.
149 EXPECT_TRUE(relay_server_->HasConnection(kRelayUdpAddr));
150 }
151
152 // TCP has the second best 'goodness' value, and as soon as UDP
153 // connection has failed, the RelayPort will attempt to connect via
154 // TCP. Here we add a fake UDP address together with a real TCP
155 // address to simulate an UDP failure. As soon as UDP has failed the
156 // RelayPort will try the TCP adress and succed.
TestConnectTcp()157 void TestConnectTcp() {
158 // Create a fake UDP address for relay port to simulate a failure.
159 cricket::ProtocolAddress fake_protocol_address =
160 cricket::ProtocolAddress(kRelayUdpAddr, cricket::PROTO_UDP);
161
162 // Create a server socket for the RelayServer.
163 talk_base::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
164 relay_server_->AddInternalServerSocket(server_socket, cricket::PROTO_TCP);
165
166 // Add server addresses to the relay port and let it start.
167 relay_port_->AddServerAddress(
168 cricket::ProtocolAddress(fake_protocol_address));
169 relay_port_->AddServerAddress(
170 cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP));
171 relay_port_->PrepareAddress();
172
173 EXPECT_FALSE(relay_port_->IsReady());
174
175 // Should have timed out in 200 + 200 + 400 + 800 + 1600 ms.
176 EXPECT_TRUE_WAIT(HasFailed(&fake_protocol_address), 3600);
177
178 // Wait until relayport is ready.
179 EXPECT_TRUE_WAIT(relay_port_->IsReady(), kMaxTimeoutMs);
180
181 // Should have only one connection.
182 EXPECT_EQ(1, relay_server_->GetConnectionCount());
183
184 // Should be the TCP address.
185 EXPECT_TRUE(relay_server_->HasConnection(kRelayTcpAddr));
186 }
187
TestConnectSslTcp()188 void TestConnectSslTcp() {
189 // Create a fake TCP address for relay port to simulate a failure.
190 // We skip UDP here since transition from UDP to TCP has been
191 // tested above.
192 cricket::ProtocolAddress fake_protocol_address =
193 cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP);
194
195 // Create a ssl server socket for the RelayServer.
196 talk_base::AsyncSocket* ssl_server_socket =
197 CreateServerSocket(kRelaySslAddr);
198 relay_server_->AddInternalServerSocket(ssl_server_socket,
199 cricket::PROTO_SSLTCP);
200
201 // Create a tcp server socket that listens on the fake address so
202 // the relay port can attempt to connect to it.
203 talk_base::scoped_ptr<talk_base::AsyncSocket> tcp_server_socket(
204 CreateServerSocket(kRelayTcpAddr));
205
206 // Add server addresses to the relay port and let it start.
207 relay_port_->AddServerAddress(fake_protocol_address);
208 relay_port_->AddServerAddress(
209 cricket::ProtocolAddress(kRelaySslAddr, cricket::PROTO_SSLTCP));
210 relay_port_->PrepareAddress();
211 EXPECT_FALSE(relay_port_->IsReady());
212
213 // Should have timed out in 3000 ms(relayport.cc, kSoftConnectTimeoutMs).
214 EXPECT_TRUE_WAIT_MARGIN(HasTimedOut(&fake_protocol_address), 3000, 100);
215
216 // Wait until relayport is ready.
217 EXPECT_TRUE_WAIT(relay_port_->IsReady(), kMaxTimeoutMs);
218
219 // Should have only one connection.
220 EXPECT_EQ(1, relay_server_->GetConnectionCount());
221
222 // Should be the SSLTCP address.
223 EXPECT_TRUE(relay_server_->HasConnection(kRelaySslAddr));
224 }
225
226 private:
CreateAsyncUdpSocket(const SocketAddress addr)227 talk_base::AsyncUDPSocket* CreateAsyncUdpSocket(const SocketAddress addr) {
228 talk_base::AsyncSocket* socket =
229 virtual_socket_server_->CreateAsyncSocket(SOCK_DGRAM);
230 talk_base::AsyncUDPSocket* packet_socket =
231 talk_base::AsyncUDPSocket::Create(socket, addr);
232 EXPECT_TRUE(packet_socket != NULL);
233 packet_socket->SignalReadPacket.connect(this, &RelayPortTest::OnReadPacket);
234 return packet_socket;
235 }
236
CreateServerSocket(const SocketAddress addr)237 talk_base::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
238 talk_base::AsyncSocket* socket =
239 virtual_socket_server_->CreateAsyncSocket(SOCK_STREAM);
240 EXPECT_GE(socket->Bind(addr), 0);
241 EXPECT_GE(socket->Listen(5), 0);
242 return socket;
243 }
244
HasFailed(cricket::ProtocolAddress * addr)245 bool HasFailed(cricket::ProtocolAddress* addr) {
246 for (size_t i = 0; i < failed_connections_.size(); i++) {
247 if (failed_connections_[i].address == addr->address &&
248 failed_connections_[i].proto == addr->proto) {
249 return true;
250 }
251 }
252 return false;
253 }
254
HasTimedOut(cricket::ProtocolAddress * addr)255 bool HasTimedOut(cricket::ProtocolAddress* addr) {
256 for (size_t i = 0; i < soft_timedout_connections_.size(); i++) {
257 if (soft_timedout_connections_[i].address == addr->address &&
258 soft_timedout_connections_[i].proto == addr->proto) {
259 return true;
260 }
261 }
262 return false;
263 }
264
265 typedef std::map<talk_base::AsyncPacketSocket*, int> PacketMap;
266
267 talk_base::Thread* main_;
268 talk_base::scoped_ptr<talk_base::PhysicalSocketServer>
269 physical_socket_server_;
270 talk_base::scoped_ptr<talk_base::VirtualSocketServer> virtual_socket_server_;
271 talk_base::SocketServerScope ss_scope_;
272 talk_base::Network network_;
273 talk_base::BasicPacketSocketFactory socket_factory_;
274 std::string username_;
275 std::string password_;
276 talk_base::scoped_ptr<cricket::RelayPort> relay_port_;
277 talk_base::scoped_ptr<cricket::RelayServer> relay_server_;
278 std::vector<cricket::ProtocolAddress> failed_connections_;
279 std::vector<cricket::ProtocolAddress> soft_timedout_connections_;
280 PacketMap received_packet_count_;
281 };
282
TEST_F(RelayPortTest,ConnectUdp)283 TEST_F(RelayPortTest, ConnectUdp) {
284 TestConnectUdp();
285 }
286
TEST_F(RelayPortTest,ConnectTcp)287 TEST_F(RelayPortTest, ConnectTcp) {
288 TestConnectTcp();
289 }
290
TEST_F(RelayPortTest,ConnectSslTcp)291 TEST_F(RelayPortTest, ConnectSslTcp) {
292 TestConnectSslTcp();
293 }
294