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/p2p/base/basicpacketsocketfactory.h"
29#include "talk/p2p/base/stunport.h"
30#include "talk/p2p/base/teststunserver.h"
31#include "webrtc/base/gunit.h"
32#include "webrtc/base/helpers.h"
33#include "webrtc/base/physicalsocketserver.h"
34#include "webrtc/base/scoped_ptr.h"
35#include "webrtc/base/socketaddress.h"
36#include "webrtc/base/ssladapter.h"
37#include "webrtc/base/virtualsocketserver.h"
38
39using cricket::ServerAddresses;
40using rtc::SocketAddress;
41
42static const SocketAddress kLocalAddr("127.0.0.1", 0);
43static const SocketAddress kStunAddr1("127.0.0.1", 5000);
44static const SocketAddress kStunAddr2("127.0.0.1", 4000);
45static const SocketAddress kBadAddr("0.0.0.1", 5000);
46static const SocketAddress kStunHostnameAddr("localhost", 5000);
47static const SocketAddress kBadHostnameAddr("not-a-real-hostname", 5000);
48static const int kTimeoutMs = 10000;
49// stun prio = 100 << 24 | 30 (IPV4) << 8 | 256 - 0
50static const uint32 kStunCandidatePriority = 1677729535;
51
52// Tests connecting a StunPort to a fake STUN server (cricket::StunServer)
53// TODO: Use a VirtualSocketServer here. We have to use a
54// PhysicalSocketServer right now since DNS is not part of SocketServer yet.
55class StunPortTest : public testing::Test,
56                     public sigslot::has_slots<> {
57 public:
58  StunPortTest()
59      : pss_(new rtc::PhysicalSocketServer),
60        ss_(new rtc::VirtualSocketServer(pss_.get())),
61        ss_scope_(ss_.get()),
62        network_("unittest", "unittest", rtc::IPAddress(INADDR_ANY), 32),
63        socket_factory_(rtc::Thread::Current()),
64        stun_server_1_(new cricket::TestStunServer(
65          rtc::Thread::Current(), kStunAddr1)),
66        stun_server_2_(new cricket::TestStunServer(
67          rtc::Thread::Current(), kStunAddr2)),
68        done_(false), error_(false), stun_keepalive_delay_(0) {
69  }
70
71  const cricket::Port* port() const { return stun_port_.get(); }
72  bool done() const { return done_; }
73  bool error() const { return error_; }
74
75  void CreateStunPort(const rtc::SocketAddress& server_addr) {
76    ServerAddresses stun_servers;
77    stun_servers.insert(server_addr);
78    CreateStunPort(stun_servers);
79  }
80
81  void CreateStunPort(const ServerAddresses& stun_servers) {
82    stun_port_.reset(cricket::StunPort::Create(
83        rtc::Thread::Current(), &socket_factory_, &network_,
84        kLocalAddr.ipaddr(), 0, 0, rtc::CreateRandomString(16),
85        rtc::CreateRandomString(22), stun_servers));
86    stun_port_->set_stun_keepalive_delay(stun_keepalive_delay_);
87    stun_port_->SignalPortComplete.connect(this,
88        &StunPortTest::OnPortComplete);
89    stun_port_->SignalPortError.connect(this,
90        &StunPortTest::OnPortError);
91  }
92
93  void CreateSharedStunPort(const rtc::SocketAddress& server_addr) {
94    socket_.reset(socket_factory_.CreateUdpSocket(
95        rtc::SocketAddress(kLocalAddr.ipaddr(), 0), 0, 0));
96    ASSERT_TRUE(socket_ != NULL);
97    socket_->SignalReadPacket.connect(this, &StunPortTest::OnReadPacket);
98    stun_port_.reset(cricket::UDPPort::Create(
99        rtc::Thread::Current(), &socket_factory_,
100        &network_, socket_.get(),
101        rtc::CreateRandomString(16), rtc::CreateRandomString(22)));
102    ASSERT_TRUE(stun_port_ != NULL);
103    ServerAddresses stun_servers;
104    stun_servers.insert(server_addr);
105    stun_port_->set_server_addresses(stun_servers);
106    stun_port_->SignalPortComplete.connect(this,
107        &StunPortTest::OnPortComplete);
108    stun_port_->SignalPortError.connect(this,
109        &StunPortTest::OnPortError);
110  }
111
112  void PrepareAddress() {
113    stun_port_->PrepareAddress();
114  }
115
116  void OnReadPacket(rtc::AsyncPacketSocket* socket, const char* data,
117                    size_t size, const rtc::SocketAddress& remote_addr,
118                    const rtc::PacketTime& packet_time) {
119    stun_port_->HandleIncomingPacket(
120        socket, data, size, remote_addr, rtc::PacketTime());
121  }
122
123  void SendData(const char* data, size_t len) {
124    stun_port_->HandleIncomingPacket(
125        socket_.get(), data, len, rtc::SocketAddress("22.22.22.22", 0),
126        rtc::PacketTime());
127  }
128
129 protected:
130  static void SetUpTestCase() {
131    rtc::InitializeSSL();
132    // Ensure the RNG is inited.
133    rtc::InitRandom(NULL, 0);
134
135  }
136  static void TearDownTestCase() {
137    rtc::CleanupSSL();
138  }
139
140  void OnPortComplete(cricket::Port* port) {
141    ASSERT_FALSE(done_);
142    done_ = true;
143    error_ = false;
144  }
145  void OnPortError(cricket::Port* port) {
146    done_ = true;
147    error_ = true;
148  }
149  void SetKeepaliveDelay(int delay) {
150    stun_keepalive_delay_ = delay;
151  }
152
153 private:
154  rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
155  rtc::scoped_ptr<rtc::VirtualSocketServer> ss_;
156  rtc::SocketServerScope ss_scope_;
157  rtc::Network network_;
158  rtc::BasicPacketSocketFactory socket_factory_;
159  rtc::scoped_ptr<cricket::UDPPort> stun_port_;
160  rtc::scoped_ptr<cricket::TestStunServer> stun_server_1_;
161  rtc::scoped_ptr<cricket::TestStunServer> stun_server_2_;
162  rtc::scoped_ptr<rtc::AsyncPacketSocket> socket_;
163  bool done_;
164  bool error_;
165  int stun_keepalive_delay_;
166};
167
168// Test that we can create a STUN port
169TEST_F(StunPortTest, TestBasic) {
170  CreateStunPort(kStunAddr1);
171  EXPECT_EQ("stun", port()->Type());
172  EXPECT_EQ(0U, port()->Candidates().size());
173}
174
175// Test that we can get an address from a STUN server.
176TEST_F(StunPortTest, TestPrepareAddress) {
177  CreateStunPort(kStunAddr1);
178  PrepareAddress();
179  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
180  ASSERT_EQ(1U, port()->Candidates().size());
181  EXPECT_TRUE(kLocalAddr.EqualIPs(port()->Candidates()[0].address()));
182
183  // TODO: Add IPv6 tests here, once either physicalsocketserver supports
184  // IPv6, or this test is changed to use VirtualSocketServer.
185}
186
187// Test that we fail properly if we can't get an address.
188TEST_F(StunPortTest, TestPrepareAddressFail) {
189  CreateStunPort(kBadAddr);
190  PrepareAddress();
191  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
192  EXPECT_TRUE(error());
193  EXPECT_EQ(0U, port()->Candidates().size());
194}
195
196// Test that we can get an address from a STUN server specified by a hostname.
197TEST_F(StunPortTest, TestPrepareAddressHostname) {
198  CreateStunPort(kStunHostnameAddr);
199  PrepareAddress();
200  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
201  ASSERT_EQ(1U, port()->Candidates().size());
202  EXPECT_TRUE(kLocalAddr.EqualIPs(port()->Candidates()[0].address()));
203  EXPECT_EQ(kStunCandidatePriority, port()->Candidates()[0].priority());
204}
205
206// Test that we handle hostname lookup failures properly.
207TEST_F(StunPortTest, TestPrepareAddressHostnameFail) {
208  CreateStunPort(kBadHostnameAddr);
209  PrepareAddress();
210  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
211  EXPECT_TRUE(error());
212  EXPECT_EQ(0U, port()->Candidates().size());
213}
214
215// This test verifies keepalive response messages don't result in
216// additional candidate generation.
217TEST_F(StunPortTest, TestKeepAliveResponse) {
218  SetKeepaliveDelay(500);  // 500ms of keepalive delay.
219  CreateStunPort(kStunHostnameAddr);
220  PrepareAddress();
221  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
222  ASSERT_EQ(1U, port()->Candidates().size());
223  EXPECT_TRUE(kLocalAddr.EqualIPs(port()->Candidates()[0].address()));
224  // Waiting for 1 seond, which will allow us to process
225  // response for keepalive binding request. 500 ms is the keepalive delay.
226  rtc::Thread::Current()->ProcessMessages(1000);
227  ASSERT_EQ(1U, port()->Candidates().size());
228}
229
230// Test that a local candidate can be generated using a shared socket.
231TEST_F(StunPortTest, TestSharedSocketPrepareAddress) {
232  CreateSharedStunPort(kStunAddr1);
233  PrepareAddress();
234  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
235  ASSERT_EQ(1U, port()->Candidates().size());
236  EXPECT_TRUE(kLocalAddr.EqualIPs(port()->Candidates()[0].address()));
237}
238
239// Test that we still a get a local candidate with invalid stun server hostname.
240// Also verifing that UDPPort can receive packets when stun address can't be
241// resolved.
242TEST_F(StunPortTest, TestSharedSocketPrepareAddressInvalidHostname) {
243  CreateSharedStunPort(kBadHostnameAddr);
244  PrepareAddress();
245  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
246  ASSERT_EQ(1U, port()->Candidates().size());
247  EXPECT_TRUE(kLocalAddr.EqualIPs(port()->Candidates()[0].address()));
248
249  // Send data to port after it's ready. This is to make sure, UDP port can
250  // handle data with unresolved stun server address.
251  std::string data = "some random data, sending to cricket::Port.";
252  SendData(data.c_str(), data.length());
253  // No crash is success.
254}
255
256// Test that candidates can be allocated for multiple STUN servers.
257TEST_F(StunPortTest, TestMultipleGoodStunServers) {
258  ServerAddresses stun_servers;
259  stun_servers.insert(kStunAddr1);
260  stun_servers.insert(kStunAddr2);
261  CreateStunPort(stun_servers);
262  EXPECT_EQ("stun", port()->Type());
263  PrepareAddress();
264  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
265  EXPECT_EQ(2U, port()->Candidates().size());
266}
267
268// Test that candidates can be allocated for multiple STUN servers, one of which
269// is not reachable.
270TEST_F(StunPortTest, TestMultipleStunServersWithBadServer) {
271  ServerAddresses stun_servers;
272  stun_servers.insert(kStunAddr1);
273  stun_servers.insert(kBadAddr);
274  CreateStunPort(stun_servers);
275  EXPECT_EQ("stun", port()->Type());
276  PrepareAddress();
277  EXPECT_TRUE_WAIT(done(), kTimeoutMs);
278  EXPECT_EQ(1U, port()->Candidates().size());
279}
280