Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / p2p / base / relayport_unittest.cc
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 "webrtc/p2p/base/basicpacketsocketfactory.h"
29 #include "webrtc/p2p/base/relayport.h"
30 #include "webrtc/p2p/base/relayserver.h"
31 #include "webrtc/base/gunit.h"
32 #include "webrtc/base/helpers.h"
33 #include "webrtc/base/logging.h"
34 #include "webrtc/base/physicalsocketserver.h"
35 #include "webrtc/base/scoped_ptr.h"
36 #include "webrtc/base/socketadapters.h"
37 #include "webrtc/base/socketaddress.h"
38 #include "webrtc/base/ssladapter.h"
39 #include "webrtc/base/thread.h"
40 #include "webrtc/base/virtualsocketserver.h"
41
42 using rtc::SocketAddress;
43
44 static const SocketAddress kLocalAddress = SocketAddress("192.168.1.2", 0);
45 static const SocketAddress kRelayUdpAddr = SocketAddress("99.99.99.1", 5000);
46 static const SocketAddress kRelayTcpAddr = SocketAddress("99.99.99.2", 5001);
47 static const SocketAddress kRelaySslAddr = SocketAddress("99.99.99.3", 443);
48 static const SocketAddress kRelayExtAddr = SocketAddress("99.99.99.3", 5002);
49
50 static const int kTimeoutMs = 1000;
51 static const int kMaxTimeoutMs = 5000;
52
53 // Tests connecting a RelayPort to a fake relay server
54 // (cricket::RelayServer) using all currently available protocols. The
55 // network layer is faked out by using a VirtualSocketServer for
56 // creating sockets. The test will monitor the current state of the
57 // RelayPort and created sockets by listening for signals such as,
58 // SignalConnectFailure, SignalConnectTimeout, SignalSocketClosed and
59 // SignalReadPacket.
60 class RelayPortTest : public testing::Test,
61                       public sigslot::has_slots<> {
62  public:
63   RelayPortTest()
64       : main_(rtc::Thread::Current()),
65         physical_socket_server_(new rtc::PhysicalSocketServer),
66         virtual_socket_server_(new rtc::VirtualSocketServer(
67             physical_socket_server_.get())),
68         ss_scope_(virtual_socket_server_.get()),
69         network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
70         socket_factory_(rtc::Thread::Current()),
71         username_(rtc::CreateRandomString(16)),
72         password_(rtc::CreateRandomString(16)),
73         relay_port_(cricket::RelayPort::Create(main_, &socket_factory_,
74                                                &network_,
75                                                kLocalAddress.ipaddr(),
76                                                0, 0, username_, password_)),
77         relay_server_(new cricket::RelayServer(main_)) {
78   }
79
80   void OnReadPacket(rtc::AsyncPacketSocket* socket,
81                     const char* data, size_t size,
82                     const rtc::SocketAddress& remote_addr,
83                     const rtc::PacketTime& packet_time) {
84     received_packet_count_[socket]++;
85   }
86
87   void OnConnectFailure(const cricket::ProtocolAddress* addr) {
88     failed_connections_.push_back(*addr);
89   }
90
91   void OnSoftTimeout(const cricket::ProtocolAddress* addr) {
92     soft_timedout_connections_.push_back(*addr);
93   }
94
95  protected:
96   virtual void SetUp() {
97     // The relay server needs an external socket to work properly.
98     rtc::AsyncUDPSocket* ext_socket =
99         CreateAsyncUdpSocket(kRelayExtAddr);
100     relay_server_->AddExternalSocket(ext_socket);
101
102     // Listen for failures.
103     relay_port_->SignalConnectFailure.
104         connect(this, &RelayPortTest::OnConnectFailure);
105
106     // Listen for soft timeouts.
107     relay_port_->SignalSoftTimeout.
108         connect(this, &RelayPortTest::OnSoftTimeout);
109   }
110
111   // Udp has the highest 'goodness' value of the three different
112   // protocols used for connecting to the relay server. As soon as
113   // PrepareAddress is called, the RelayPort will start trying to
114   // connect to the given UDP address. As soon as a response to the
115   // sent STUN allocate request message has been received, the
116   // RelayPort will consider the connection to be complete and will
117   // abort any other connection attempts.
118   void TestConnectUdp() {
119     // Add a UDP socket to the relay server.
120     rtc::AsyncUDPSocket* internal_udp_socket =
121         CreateAsyncUdpSocket(kRelayUdpAddr);
122     rtc::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
123
124     relay_server_->AddInternalSocket(internal_udp_socket);
125     relay_server_->AddInternalServerSocket(server_socket, cricket::PROTO_TCP);
126
127     // Now add our relay addresses to the relay port and let it start.
128     relay_port_->AddServerAddress(
129         cricket::ProtocolAddress(kRelayUdpAddr, cricket::PROTO_UDP));
130     relay_port_->AddServerAddress(
131         cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP));
132     relay_port_->PrepareAddress();
133
134     // Should be connected.
135     EXPECT_TRUE_WAIT(relay_port_->IsReady(), kTimeoutMs);
136
137     // Make sure that we are happy with UDP, ie. not continuing with
138     // TCP, SSLTCP, etc.
139     WAIT(relay_server_->HasConnection(kRelayTcpAddr), kTimeoutMs);
140
141     // Should have only one connection.
142     EXPECT_EQ(1, relay_server_->GetConnectionCount());
143
144     // Should be the UDP address.
145     EXPECT_TRUE(relay_server_->HasConnection(kRelayUdpAddr));
146   }
147
148   // TCP has the second best 'goodness' value, and as soon as UDP
149   // connection has failed, the RelayPort will attempt to connect via
150   // TCP. Here we add a fake UDP address together with a real TCP
151   // address to simulate an UDP failure. As soon as UDP has failed the
152   // RelayPort will try the TCP adress and succed.
153   void TestConnectTcp() {
154     // Create a fake UDP address for relay port to simulate a failure.
155     cricket::ProtocolAddress fake_protocol_address =
156         cricket::ProtocolAddress(kRelayUdpAddr, cricket::PROTO_UDP);
157
158     // Create a server socket for the RelayServer.
159     rtc::AsyncSocket* server_socket = CreateServerSocket(kRelayTcpAddr);
160     relay_server_->AddInternalServerSocket(server_socket, cricket::PROTO_TCP);
161
162     // Add server addresses to the relay port and let it start.
163     relay_port_->AddServerAddress(
164         cricket::ProtocolAddress(fake_protocol_address));
165     relay_port_->AddServerAddress(
166         cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP));
167     relay_port_->PrepareAddress();
168
169     EXPECT_FALSE(relay_port_->IsReady());
170
171     // Should have timed out in 200 + 200 + 400 + 800 + 1600 ms.
172     EXPECT_TRUE_WAIT(HasFailed(&fake_protocol_address), 3600);
173
174     // Wait until relayport is ready.
175     EXPECT_TRUE_WAIT(relay_port_->IsReady(), kMaxTimeoutMs);
176
177     // Should have only one connection.
178     EXPECT_EQ(1, relay_server_->GetConnectionCount());
179
180     // Should be the TCP address.
181     EXPECT_TRUE(relay_server_->HasConnection(kRelayTcpAddr));
182   }
183
184   void TestConnectSslTcp() {
185     // Create a fake TCP address for relay port to simulate a failure.
186     // We skip UDP here since transition from UDP to TCP has been
187     // tested above.
188     cricket::ProtocolAddress fake_protocol_address =
189         cricket::ProtocolAddress(kRelayTcpAddr, cricket::PROTO_TCP);
190
191     // Create a ssl server socket for the RelayServer.
192     rtc::AsyncSocket* ssl_server_socket =
193         CreateServerSocket(kRelaySslAddr);
194     relay_server_->AddInternalServerSocket(ssl_server_socket,
195                                            cricket::PROTO_SSLTCP);
196
197     // Create a tcp server socket that listens on the fake address so
198     // the relay port can attempt to connect to it.
199     rtc::scoped_ptr<rtc::AsyncSocket> tcp_server_socket(
200         CreateServerSocket(kRelayTcpAddr));
201
202     // Add server addresses to the relay port and let it start.
203     relay_port_->AddServerAddress(fake_protocol_address);
204     relay_port_->AddServerAddress(
205         cricket::ProtocolAddress(kRelaySslAddr, cricket::PROTO_SSLTCP));
206     relay_port_->PrepareAddress();
207     EXPECT_FALSE(relay_port_->IsReady());
208
209     // Should have timed out in 3000 ms(relayport.cc, kSoftConnectTimeoutMs).
210     EXPECT_TRUE_WAIT_MARGIN(HasTimedOut(&fake_protocol_address), 3000, 100);
211
212     // Wait until relayport is ready.
213     EXPECT_TRUE_WAIT(relay_port_->IsReady(), kMaxTimeoutMs);
214
215     // Should have only one connection.
216     EXPECT_EQ(1, relay_server_->GetConnectionCount());
217
218     // Should be the SSLTCP address.
219     EXPECT_TRUE(relay_server_->HasConnection(kRelaySslAddr));
220   }
221
222  private:
223   rtc::AsyncUDPSocket* CreateAsyncUdpSocket(const SocketAddress addr) {
224     rtc::AsyncSocket* socket =
225         virtual_socket_server_->CreateAsyncSocket(SOCK_DGRAM);
226     rtc::AsyncUDPSocket* packet_socket =
227         rtc::AsyncUDPSocket::Create(socket, addr);
228     EXPECT_TRUE(packet_socket != NULL);
229     packet_socket->SignalReadPacket.connect(this, &RelayPortTest::OnReadPacket);
230     return packet_socket;
231   }
232
233   rtc::AsyncSocket* CreateServerSocket(const SocketAddress addr) {
234     rtc::AsyncSocket* socket =
235         virtual_socket_server_->CreateAsyncSocket(SOCK_STREAM);
236     EXPECT_GE(socket->Bind(addr), 0);
237     EXPECT_GE(socket->Listen(5), 0);
238     return socket;
239   }
240
241   bool HasFailed(cricket::ProtocolAddress* addr) {
242     for (size_t i = 0; i < failed_connections_.size(); i++) {
243       if (failed_connections_[i].address == addr->address &&
244           failed_connections_[i].proto == addr->proto) {
245         return true;
246       }
247     }
248     return false;
249   }
250
251   bool HasTimedOut(cricket::ProtocolAddress* addr) {
252     for (size_t i = 0; i < soft_timedout_connections_.size(); i++) {
253       if (soft_timedout_connections_[i].address == addr->address &&
254           soft_timedout_connections_[i].proto == addr->proto) {
255         return true;
256       }
257     }
258     return false;
259   }
260
261   typedef std::map<rtc::AsyncPacketSocket*, int> PacketMap;
262
263   rtc::Thread* main_;
264   rtc::scoped_ptr<rtc::PhysicalSocketServer>
265       physical_socket_server_;
266   rtc::scoped_ptr<rtc::VirtualSocketServer> virtual_socket_server_;
267   rtc::SocketServerScope ss_scope_;
268   rtc::Network network_;
269   rtc::BasicPacketSocketFactory socket_factory_;
270   std::string username_;
271   std::string password_;
272   rtc::scoped_ptr<cricket::RelayPort> relay_port_;
273   rtc::scoped_ptr<cricket::RelayServer> relay_server_;
274   std::vector<cricket::ProtocolAddress> failed_connections_;
275   std::vector<cricket::ProtocolAddress> soft_timedout_connections_;
276   PacketMap received_packet_count_;
277 };
278
279 TEST_F(RelayPortTest, ConnectUdp) {
280   TestConnectUdp();
281 }
282
283 TEST_F(RelayPortTest, ConnectTcp) {
284   TestConnectTcp();
285 }
286
287 TEST_F(RelayPortTest, ConnectSslTcp) {
288   TestConnectSslTcp();
289 }