portallocator_unittest.cc revision d1ba6d9cbfc44618d2c553ff7851948c730ae37b
1/*
2 *  Copyright 2009 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 "webrtc/p2p/base/basicpacketsocketfactory.h"
12#include "webrtc/p2p/base/constants.h"
13#include "webrtc/p2p/base/p2ptransportchannel.h"
14#include "webrtc/p2p/base/portallocatorsessionproxy.h"
15#include "webrtc/p2p/base/testrelayserver.h"
16#include "webrtc/p2p/base/teststunserver.h"
17#include "webrtc/p2p/base/testturnserver.h"
18#include "webrtc/p2p/client/basicportallocator.h"
19#include "webrtc/p2p/client/httpportallocator.h"
20#include "webrtc/base/fakenetwork.h"
21#include "webrtc/base/firewallsocketserver.h"
22#include "webrtc/base/gunit.h"
23#include "webrtc/base/helpers.h"
24#include "webrtc/base/logging.h"
25#include "webrtc/base/natserver.h"
26#include "webrtc/base/natsocketfactory.h"
27#include "webrtc/base/network.h"
28#include "webrtc/base/physicalsocketserver.h"
29#include "webrtc/base/socketaddress.h"
30#include "webrtc/base/ssladapter.h"
31#include "webrtc/base/thread.h"
32#include "webrtc/base/virtualsocketserver.h"
33
34using cricket::ServerAddresses;
35using rtc::SocketAddress;
36using rtc::Thread;
37
38static const SocketAddress kClientAddr("11.11.11.11", 0);
39static const SocketAddress kPrivateAddr("192.168.1.11", 0);
40static const SocketAddress kClientIPv6Addr(
41    "2401:fa00:4:1000:be30:5bff:fee5:c3", 0);
42static const SocketAddress kClientAddr2("22.22.22.22", 0);
43static const SocketAddress kNatAddr("77.77.77.77", rtc::NAT_SERVER_PORT);
44static const SocketAddress kRemoteClientAddr("22.22.22.22", 0);
45static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
46static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
47static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
48static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
49static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
50static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
51static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
52static const SocketAddress kTurnUdpIntAddr("99.99.99.4", 3478);
53static const SocketAddress kTurnTcpIntAddr("99.99.99.5", 3478);
54static const SocketAddress kTurnUdpExtAddr("99.99.99.6", 0);
55
56// Minimum and maximum port for port range tests.
57static const int kMinPort = 10000;
58static const int kMaxPort = 10099;
59
60// Based on ICE_UFRAG_LENGTH
61static const char kIceUfrag0[] = "TESTICEUFRAG0000";
62// Based on ICE_PWD_LENGTH
63static const char kIcePwd0[] = "TESTICEPWD00000000000000";
64
65static const char kContentName[] = "test content";
66
67static const int kDefaultAllocationTimeout = 1000;
68static const char kTurnUsername[] = "test";
69static const char kTurnPassword[] = "test";
70
71namespace cricket {
72
73// Helper for dumping candidates
74std::ostream& operator<<(std::ostream& os, const cricket::Candidate& c) {
75  os << c.ToString();
76  return os;
77}
78
79}  // namespace cricket
80
81class PortAllocatorTest : public testing::Test, public sigslot::has_slots<> {
82 public:
83  PortAllocatorTest()
84      : pss_(new rtc::PhysicalSocketServer),
85        vss_(new rtc::VirtualSocketServer(pss_.get())),
86        fss_(new rtc::FirewallSocketServer(vss_.get())),
87        ss_scope_(fss_.get()),
88        nat_factory_(vss_.get(), kNatAddr),
89        nat_socket_factory_(&nat_factory_),
90        stun_server_(cricket::TestStunServer::Create(Thread::Current(),
91                                                     kStunAddr)),
92        relay_server_(Thread::Current(), kRelayUdpIntAddr, kRelayUdpExtAddr,
93                      kRelayTcpIntAddr, kRelayTcpExtAddr,
94                      kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
95        turn_server_(Thread::Current(), kTurnUdpIntAddr, kTurnUdpExtAddr),
96        candidate_allocation_done_(false) {
97    cricket::ServerAddresses stun_servers;
98    stun_servers.insert(kStunAddr);
99    allocator_.reset(new cricket::BasicPortAllocator(
100        &network_manager_,
101        stun_servers,
102        kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr));
103    allocator_->set_step_delay(cricket::kMinimumStepDelay);
104  }
105
106  void AddInterface(const SocketAddress& addr) {
107    network_manager_.AddInterface(addr);
108  }
109  bool SetPortRange(int min_port, int max_port) {
110    return allocator_->SetPortRange(min_port, max_port);
111  }
112  void ResetWithNatServer(const rtc::SocketAddress& stun_server) {
113    nat_server_.reset(new rtc::NATServer(
114        rtc::NAT_OPEN_CONE, vss_.get(), kNatAddr, vss_.get(), kNatAddr));
115
116    ServerAddresses stun_servers;
117    stun_servers.insert(stun_server);
118    allocator_.reset(new cricket::BasicPortAllocator(
119        &network_manager_, &nat_socket_factory_, stun_servers));
120    allocator().set_step_delay(cricket::kMinimumStepDelay);
121  }
122
123  void AddTurnServers(const rtc::SocketAddress& udp_turn,
124                      const rtc::SocketAddress& tcp_turn) {
125    cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
126    cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
127    relay_server.credentials = credentials;
128
129    if (!udp_turn.IsNil()) {
130      relay_server.ports.push_back(cricket::ProtocolAddress(
131          kTurnUdpIntAddr, cricket::PROTO_UDP, false));
132    }
133    if (!tcp_turn.IsNil()) {
134      relay_server.ports.push_back(cricket::ProtocolAddress(
135          kTurnTcpIntAddr, cricket::PROTO_TCP, false));
136    }
137    allocator_->AddRelay(relay_server);
138  }
139
140  bool CreateSession(int component) {
141    session_.reset(CreateSession("session", component));
142    if (!session_)
143      return false;
144    return true;
145  }
146
147  bool CreateSession(int component, const std::string& content_name) {
148    session_.reset(CreateSession("session", content_name, component));
149    if (!session_)
150      return false;
151    return true;
152  }
153
154  cricket::PortAllocatorSession* CreateSession(
155      const std::string& sid, int component) {
156    return CreateSession(sid, kContentName, component);
157  }
158
159  cricket::PortAllocatorSession* CreateSession(
160      const std::string& sid, const std::string& content_name, int component) {
161    return CreateSession(sid, content_name, component, kIceUfrag0, kIcePwd0);
162  }
163
164  cricket::PortAllocatorSession* CreateSession(
165      const std::string& sid, const std::string& content_name, int component,
166      const std::string& ice_ufrag, const std::string& ice_pwd) {
167    cricket::PortAllocatorSession* session =
168        allocator_->CreateSession(
169            sid, content_name, component, ice_ufrag, ice_pwd);
170    session->SignalPortReady.connect(this,
171            &PortAllocatorTest::OnPortReady);
172    session->SignalCandidatesReady.connect(this,
173        &PortAllocatorTest::OnCandidatesReady);
174    session->SignalCandidatesAllocationDone.connect(this,
175        &PortAllocatorTest::OnCandidatesAllocationDone);
176    return session;
177  }
178
179  static bool CheckCandidate(const cricket::Candidate& c,
180                             int component, const std::string& type,
181                             const std::string& proto,
182                             const SocketAddress& addr) {
183    return (c.component() == component && c.type() == type &&
184        c.protocol() == proto && c.address().ipaddr() == addr.ipaddr() &&
185        ((addr.port() == 0 && (c.address().port() != 0)) ||
186        (c.address().port() == addr.port())));
187  }
188  static bool CheckPort(const rtc::SocketAddress& addr,
189                        int min_port, int max_port) {
190    return (addr.port() >= min_port && addr.port() <= max_port);
191  }
192
193  void OnCandidatesAllocationDone(cricket::PortAllocatorSession* session) {
194    // We should only get this callback once, except in the mux test where
195    // we have multiple port allocation sessions.
196    if (session == session_.get()) {
197      ASSERT_FALSE(candidate_allocation_done_);
198      candidate_allocation_done_ = true;
199    }
200  }
201
202  // Check if all ports allocated have send-buffer size |expected|. If
203  // |expected| == -1, check if GetOptions returns SOCKET_ERROR.
204  void CheckSendBufferSizesOfAllPorts(int expected) {
205    std::vector<cricket::PortInterface*>::iterator it;
206    for (it = ports_.begin(); it < ports_.end(); ++it) {
207      int send_buffer_size;
208      if (expected == -1) {
209        EXPECT_EQ(SOCKET_ERROR,
210                  (*it)->GetOption(rtc::Socket::OPT_SNDBUF,
211                                   &send_buffer_size));
212      } else {
213        EXPECT_EQ(0, (*it)->GetOption(rtc::Socket::OPT_SNDBUF,
214                                      &send_buffer_size));
215        ASSERT_EQ(expected, send_buffer_size);
216      }
217    }
218  }
219
220 protected:
221  cricket::BasicPortAllocator& allocator() {
222    return *allocator_;
223  }
224
225  void OnPortReady(cricket::PortAllocatorSession* ses,
226                   cricket::PortInterface* port) {
227    LOG(LS_INFO) << "OnPortReady: " << port->ToString();
228    ports_.push_back(port);
229  }
230  void OnCandidatesReady(cricket::PortAllocatorSession* ses,
231                         const std::vector<cricket::Candidate>& candidates) {
232    for (size_t i = 0; i < candidates.size(); ++i) {
233      LOG(LS_INFO) << "OnCandidatesReady: " << candidates[i].ToString();
234      candidates_.push_back(candidates[i]);
235    }
236  }
237
238  bool HasRelayAddress(const cricket::ProtocolAddress& proto_addr) {
239    for (size_t i = 0; i < allocator_->relays().size(); ++i) {
240      cricket::RelayServerConfig server_config = allocator_->relays()[i];
241      cricket::PortList::const_iterator relay_port;
242      for (relay_port = server_config.ports.begin();
243          relay_port != server_config.ports.end(); ++relay_port) {
244        if (proto_addr.address == relay_port->address &&
245            proto_addr.proto == relay_port->proto)
246          return true;
247      }
248    }
249    return false;
250  }
251
252  rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
253  rtc::scoped_ptr<rtc::VirtualSocketServer> vss_;
254  rtc::scoped_ptr<rtc::FirewallSocketServer> fss_;
255  rtc::SocketServerScope ss_scope_;
256  rtc::scoped_ptr<rtc::NATServer> nat_server_;
257  rtc::NATSocketFactory nat_factory_;
258  rtc::BasicPacketSocketFactory nat_socket_factory_;
259  rtc::scoped_ptr<cricket::TestStunServer> stun_server_;
260  cricket::TestRelayServer relay_server_;
261  cricket::TestTurnServer turn_server_;
262  rtc::FakeNetworkManager network_manager_;
263  rtc::scoped_ptr<cricket::BasicPortAllocator> allocator_;
264  rtc::scoped_ptr<cricket::PortAllocatorSession> session_;
265  std::vector<cricket::PortInterface*> ports_;
266  std::vector<cricket::Candidate> candidates_;
267  bool candidate_allocation_done_;
268};
269
270// Tests that we can init the port allocator and create a session.
271TEST_F(PortAllocatorTest, TestBasic) {
272  EXPECT_EQ(&network_manager_, allocator().network_manager());
273  EXPECT_EQ(kStunAddr, *allocator().stun_servers().begin());
274  ASSERT_EQ(1u, allocator().relays().size());
275  EXPECT_EQ(cricket::RELAY_GTURN, allocator().relays()[0].type);
276  // Empty relay credentials are used for GTURN.
277  EXPECT_TRUE(allocator().relays()[0].credentials.username.empty());
278  EXPECT_TRUE(allocator().relays()[0].credentials.password.empty());
279  EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
280      kRelayUdpIntAddr, cricket::PROTO_UDP)));
281  EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
282      kRelayTcpIntAddr, cricket::PROTO_TCP)));
283  EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
284      kRelaySslTcpIntAddr, cricket::PROTO_SSLTCP)));
285  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
286}
287
288// Tests that we allocator session not trying to allocate ports for every 250ms.
289TEST_F(PortAllocatorTest, TestNoNetworkInterface) {
290  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
291  session_->StartGettingPorts();
292  // Waiting for one second to make sure BasicPortAllocatorSession has not
293  // called OnAllocate multiple times. In old behavior it's called every 250ms.
294  // When there are no network interfaces, each execution of OnAllocate will
295  // result in SignalCandidatesAllocationDone signal.
296  rtc::Thread::Current()->ProcessMessages(1000);
297  EXPECT_TRUE(candidate_allocation_done_);
298  EXPECT_EQ(0U, candidates_.size());
299}
300
301// Tests that we can get all the desired addresses successfully.
302TEST_F(PortAllocatorTest, TestGetAllPortsWithMinimumStepDelay) {
303  AddInterface(kClientAddr);
304  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
305  session_->StartGettingPorts();
306  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
307  EXPECT_EQ(4U, ports_.size());
308  EXPECT_PRED5(CheckCandidate, candidates_[0],
309      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
310  EXPECT_PRED5(CheckCandidate, candidates_[1],
311      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
312  EXPECT_PRED5(CheckCandidate, candidates_[2],
313      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
314  EXPECT_PRED5(CheckCandidate, candidates_[3],
315      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
316  EXPECT_PRED5(CheckCandidate, candidates_[4],
317      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
318  EXPECT_PRED5(CheckCandidate, candidates_[5],
319      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
320  EXPECT_PRED5(CheckCandidate, candidates_[6],
321      cricket::ICE_CANDIDATE_COMPONENT_RTP,
322      "relay", "ssltcp", kRelaySslTcpIntAddr);
323  EXPECT_TRUE(candidate_allocation_done_);
324}
325
326// Verify candidates with default step delay of 1sec.
327TEST_F(PortAllocatorTest, TestGetAllPortsWithOneSecondStepDelay) {
328  AddInterface(kClientAddr);
329  allocator_->set_step_delay(cricket::kDefaultStepDelay);
330  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
331  session_->StartGettingPorts();
332  ASSERT_EQ_WAIT(2U, candidates_.size(), 1000);
333  EXPECT_EQ(2U, ports_.size());
334  ASSERT_EQ_WAIT(4U, candidates_.size(), 2000);
335  EXPECT_EQ(3U, ports_.size());
336  EXPECT_PRED5(CheckCandidate, candidates_[2],
337      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
338  EXPECT_PRED5(CheckCandidate, candidates_[3],
339      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
340  ASSERT_EQ_WAIT(6U, candidates_.size(), 1500);
341  EXPECT_PRED5(CheckCandidate, candidates_[4],
342      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
343  EXPECT_PRED5(CheckCandidate, candidates_[5],
344      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
345  EXPECT_EQ(4U, ports_.size());
346  ASSERT_EQ_WAIT(7U, candidates_.size(), 2000);
347  EXPECT_PRED5(CheckCandidate, candidates_[6],
348      cricket::ICE_CANDIDATE_COMPONENT_RTP,
349               "relay", "ssltcp", kRelaySslTcpIntAddr);
350  EXPECT_EQ(4U, ports_.size());
351  EXPECT_TRUE(candidate_allocation_done_);
352  // If we Stop gathering now, we shouldn't get a second "done" callback.
353  session_->StopGettingPorts();
354}
355
356TEST_F(PortAllocatorTest, TestSetupVideoRtpPortsWithNormalSendBuffers) {
357  AddInterface(kClientAddr);
358  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP,
359                            cricket::CN_VIDEO));
360  session_->StartGettingPorts();
361  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
362  EXPECT_TRUE(candidate_allocation_done_);
363  // If we Stop gathering now, we shouldn't get a second "done" callback.
364  session_->StopGettingPorts();
365
366  // All ports should have unset send-buffer sizes.
367  CheckSendBufferSizesOfAllPorts(-1);
368}
369
370// Tests that we can get callback after StopGetAllPorts.
371TEST_F(PortAllocatorTest, TestStopGetAllPorts) {
372  AddInterface(kClientAddr);
373  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
374  session_->StartGettingPorts();
375  ASSERT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
376  EXPECT_EQ(2U, ports_.size());
377  session_->StopGettingPorts();
378  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
379}
380
381// Test that we restrict client ports appropriately when a port range is set.
382// We check the candidates for udp/stun/tcp ports, and the from address
383// for relay ports.
384TEST_F(PortAllocatorTest, TestGetAllPortsPortRange) {
385  AddInterface(kClientAddr);
386  // Check that an invalid port range fails.
387  EXPECT_FALSE(SetPortRange(kMaxPort, kMinPort));
388  // Check that a null port range succeeds.
389  EXPECT_TRUE(SetPortRange(0, 0));
390  // Check that a valid port range succeeds.
391  EXPECT_TRUE(SetPortRange(kMinPort, kMaxPort));
392  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
393  session_->StartGettingPorts();
394  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
395  EXPECT_EQ(4U, ports_.size());
396  // Check the port number for the UDP port object.
397  EXPECT_PRED3(CheckPort, candidates_[0].address(), kMinPort, kMaxPort);
398  // Check the port number for the STUN port object.
399  EXPECT_PRED3(CheckPort, candidates_[1].address(), kMinPort, kMaxPort);
400  // Check the port number used to connect to the relay server.
401  EXPECT_PRED3(CheckPort, relay_server_.GetConnection(0).source(),
402               kMinPort, kMaxPort);
403  // Check the port number for the TCP port object.
404  EXPECT_PRED3(CheckPort, candidates_[5].address(), kMinPort, kMaxPort);
405  EXPECT_TRUE(candidate_allocation_done_);
406}
407
408// Test that we don't crash or malfunction if we have no network adapters.
409TEST_F(PortAllocatorTest, TestGetAllPortsNoAdapters) {
410  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
411  session_->StartGettingPorts();
412  rtc::Thread::Current()->ProcessMessages(100);
413  // Without network adapter, we should not get any candidate.
414  EXPECT_EQ(0U, candidates_.size());
415  EXPECT_TRUE(candidate_allocation_done_);
416}
417
418// Test that we can get OnCandidatesAllocationDone callback when all the ports
419// are disabled.
420TEST_F(PortAllocatorTest, TestDisableAllPorts) {
421  AddInterface(kClientAddr);
422  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
423  session_->set_flags(cricket::PORTALLOCATOR_DISABLE_UDP |
424                      cricket::PORTALLOCATOR_DISABLE_STUN |
425                      cricket::PORTALLOCATOR_DISABLE_RELAY |
426                      cricket::PORTALLOCATOR_DISABLE_TCP);
427  session_->StartGettingPorts();
428  rtc::Thread::Current()->ProcessMessages(100);
429  EXPECT_EQ(0U, candidates_.size());
430  EXPECT_TRUE(candidate_allocation_done_);
431}
432
433// Test that we don't crash or malfunction if we can't create UDP sockets.
434TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpSockets) {
435  AddInterface(kClientAddr);
436  fss_->set_udp_sockets_enabled(false);
437  EXPECT_TRUE(CreateSession(1));
438  session_->StartGettingPorts();
439  ASSERT_EQ_WAIT(5U, candidates_.size(), kDefaultAllocationTimeout);
440  EXPECT_EQ(2U, ports_.size());
441  EXPECT_PRED5(CheckCandidate, candidates_[0],
442      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
443  EXPECT_PRED5(CheckCandidate, candidates_[1],
444      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
445  EXPECT_PRED5(CheckCandidate, candidates_[2],
446      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
447  EXPECT_PRED5(CheckCandidate, candidates_[3],
448      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
449  EXPECT_PRED5(CheckCandidate, candidates_[4],
450      cricket::ICE_CANDIDATE_COMPONENT_RTP,
451      "relay", "ssltcp", kRelaySslTcpIntAddr);
452  EXPECT_TRUE(candidate_allocation_done_);
453}
454
455// Test that we don't crash or malfunction if we can't create UDP sockets or
456// listen on TCP sockets. We still give out a local TCP address, since
457// apparently this is needed for the remote side to accept our connection.
458TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpSocketsNoTcpListen) {
459  AddInterface(kClientAddr);
460  fss_->set_udp_sockets_enabled(false);
461  fss_->set_tcp_listen_enabled(false);
462  EXPECT_TRUE(CreateSession(1));
463  session_->StartGettingPorts();
464  ASSERT_EQ_WAIT(5U, candidates_.size(), kDefaultAllocationTimeout);
465  EXPECT_EQ(2U, ports_.size());
466  EXPECT_PRED5(CheckCandidate, candidates_[0],
467      1, "relay", "udp", kRelayUdpIntAddr);
468  EXPECT_PRED5(CheckCandidate, candidates_[1],
469      1, "relay", "udp", kRelayUdpExtAddr);
470  EXPECT_PRED5(CheckCandidate, candidates_[2],
471      1, "relay", "tcp", kRelayTcpIntAddr);
472  EXPECT_PRED5(CheckCandidate, candidates_[3],
473      1, "local", "tcp", kClientAddr);
474  EXPECT_PRED5(CheckCandidate, candidates_[4],
475      1, "relay", "ssltcp", kRelaySslTcpIntAddr);
476  EXPECT_TRUE(candidate_allocation_done_);
477}
478
479// Test that we don't crash or malfunction if we can't create any sockets.
480// TODO: Find a way to exit early here.
481TEST_F(PortAllocatorTest, TestGetAllPortsNoSockets) {
482  AddInterface(kClientAddr);
483  fss_->set_tcp_sockets_enabled(false);
484  fss_->set_udp_sockets_enabled(false);
485  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
486  session_->StartGettingPorts();
487  WAIT(candidates_.size() > 0, 2000);
488  // TODO - Check candidate_allocation_done signal.
489  // In case of Relay, ports creation will succeed but sockets will fail.
490  // There is no error reporting from RelayEntry to handle this failure.
491}
492
493// Testing STUN timeout.
494TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpAllowed) {
495  fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr);
496  AddInterface(kClientAddr);
497  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
498  session_->StartGettingPorts();
499  EXPECT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
500  EXPECT_EQ(2U, ports_.size());
501  EXPECT_PRED5(CheckCandidate, candidates_[0],
502      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
503  EXPECT_PRED5(CheckCandidate, candidates_[1],
504      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
505  // RelayPort connection timeout is 3sec. TCP connection with RelayServer
506  // will be tried after 3 seconds.
507  EXPECT_EQ_WAIT(6U, candidates_.size(), 4000);
508  EXPECT_EQ(3U, ports_.size());
509  EXPECT_PRED5(CheckCandidate, candidates_[2],
510      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
511  EXPECT_PRED5(CheckCandidate, candidates_[3],
512      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
513  EXPECT_PRED5(CheckCandidate, candidates_[4],
514      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "ssltcp",
515      kRelaySslTcpIntAddr);
516  EXPECT_PRED5(CheckCandidate, candidates_[5],
517      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
518  // Stun Timeout is 9sec.
519  EXPECT_TRUE_WAIT(candidate_allocation_done_, 9000);
520}
521
522TEST_F(PortAllocatorTest, TestCandidatePriorityOfMultipleInterfaces) {
523  AddInterface(kClientAddr);
524  AddInterface(kClientAddr2);
525  // Allocating only host UDP ports. This is done purely for testing
526  // convenience.
527  allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_TCP |
528                        cricket::PORTALLOCATOR_DISABLE_STUN |
529                        cricket::PORTALLOCATOR_DISABLE_RELAY);
530  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
531  session_->StartGettingPorts();
532  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
533  ASSERT_EQ(2U, candidates_.size());
534  EXPECT_EQ(2U, ports_.size());
535  // Candidates priorities should be different.
536  EXPECT_NE(candidates_[0].priority(), candidates_[1].priority());
537}
538
539// Test to verify ICE restart process.
540TEST_F(PortAllocatorTest, TestGetAllPortsRestarts) {
541  AddInterface(kClientAddr);
542  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
543  session_->StartGettingPorts();
544  EXPECT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
545  EXPECT_EQ(4U, ports_.size());
546  EXPECT_TRUE(candidate_allocation_done_);
547  // TODO - Extend this to verify ICE restart.
548}
549
550// Test ICE candidate filter mechanism with options Relay/Host/Reflexive.
551TEST_F(PortAllocatorTest, TestCandidateFilterWithRelayOnly) {
552  AddInterface(kClientAddr);
553  allocator().set_candidate_filter(cricket::CF_RELAY);
554  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
555  session_->StartGettingPorts();
556  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
557  // Using GTURN, we will have 4 candidates.
558  EXPECT_EQ(4U, candidates_.size());
559  EXPECT_EQ(1U, ports_.size());  // Only Relay port will be in ready state.
560  for (size_t i = 0; i < candidates_.size(); ++i) {
561    EXPECT_EQ(std::string(cricket::RELAY_PORT_TYPE), candidates_[i].type());
562  }
563}
564
565TEST_F(PortAllocatorTest, TestCandidateFilterWithHostOnly) {
566  AddInterface(kClientAddr);
567  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
568                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
569  allocator().set_candidate_filter(cricket::CF_HOST);
570  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
571  session_->StartGettingPorts();
572  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
573  EXPECT_EQ(2U, candidates_.size()); // Host UDP/TCP candidates only.
574  EXPECT_EQ(2U, ports_.size()); // UDP/TCP ports only.
575  for (size_t i = 0; i < candidates_.size(); ++i) {
576    EXPECT_EQ(std::string(cricket::LOCAL_PORT_TYPE), candidates_[i].type());
577  }
578}
579
580// Host is behind the NAT.
581TEST_F(PortAllocatorTest, TestCandidateFilterWithReflexiveOnly) {
582  AddInterface(kPrivateAddr);
583  ResetWithNatServer(kStunAddr);
584
585  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
586                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
587  allocator().set_candidate_filter(cricket::CF_REFLEXIVE);
588  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
589  session_->StartGettingPorts();
590  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
591  // Host is behind NAT, no private address will be exposed. Hence only UDP
592  // port with STUN candidate will be sent outside.
593  EXPECT_EQ(1U, candidates_.size()); // Only STUN candidate.
594  EXPECT_EQ(1U, ports_.size());  // Only UDP port will be in ready state.
595  for (size_t i = 0; i < candidates_.size(); ++i) {
596    EXPECT_EQ(std::string(cricket::STUN_PORT_TYPE), candidates_[i].type());
597  }
598}
599
600// Host is not behind the NAT.
601TEST_F(PortAllocatorTest, TestCandidateFilterWithReflexiveOnlyAndNoNAT) {
602  AddInterface(kClientAddr);
603  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
604                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
605  allocator().set_candidate_filter(cricket::CF_REFLEXIVE);
606  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
607  session_->StartGettingPorts();
608  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
609  // Host has a public address, both UDP and TCP candidates will be exposed.
610  EXPECT_EQ(2U, candidates_.size()); // Local UDP + TCP candidate.
611  EXPECT_EQ(2U, ports_.size());  //  UDP and TCP ports will be in ready state.
612  for (size_t i = 0; i < candidates_.size(); ++i) {
613    EXPECT_EQ(std::string(cricket::LOCAL_PORT_TYPE), candidates_[i].type());
614  }
615}
616
617TEST_F(PortAllocatorTest, TestBasicMuxFeatures) {
618  AddInterface(kClientAddr);
619  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE);
620  // Session ID - session1.
621  rtc::scoped_ptr<cricket::PortAllocatorSession> session1(
622      CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTP));
623  rtc::scoped_ptr<cricket::PortAllocatorSession> session2(
624      CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTCP));
625  session1->StartGettingPorts();
626  session2->StartGettingPorts();
627  // Each session should receive two proxy ports of local and stun.
628  ASSERT_EQ_WAIT(14U, candidates_.size(), kDefaultAllocationTimeout);
629  EXPECT_EQ(8U, ports_.size());
630
631  rtc::scoped_ptr<cricket::PortAllocatorSession> session3(
632      CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTP));
633  session3->StartGettingPorts();
634  // Already allocated candidates and ports will be sent to the newly
635  // allocated proxy session.
636  ASSERT_EQ_WAIT(21U, candidates_.size(), kDefaultAllocationTimeout);
637  EXPECT_EQ(12U, ports_.size());
638}
639
640// This test verifies by changing ice_ufrag and/or ice_pwd
641// will result in different set of candidates when BUNDLE is enabled.
642// If BUNDLE is disabled, CreateSession will always allocate new
643// set of candidates.
644TEST_F(PortAllocatorTest, TestBundleIceRestart) {
645  AddInterface(kClientAddr);
646  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE);
647  // Session ID - session1.
648  rtc::scoped_ptr<cricket::PortAllocatorSession> session1(
649      CreateSession("session1", kContentName,
650                    cricket::ICE_CANDIDATE_COMPONENT_RTP,
651                    kIceUfrag0, kIcePwd0));
652  session1->StartGettingPorts();
653  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
654  EXPECT_EQ(4U, ports_.size());
655
656  // Allocate a different session with sid |session1| and different ice_ufrag.
657  rtc::scoped_ptr<cricket::PortAllocatorSession> session2(
658      CreateSession("session1", kContentName,
659                    cricket::ICE_CANDIDATE_COMPONENT_RTP,
660                    "TestIceUfrag", kIcePwd0));
661  session2->StartGettingPorts();
662  ASSERT_EQ_WAIT(14U, candidates_.size(), kDefaultAllocationTimeout);
663  EXPECT_EQ(8U, ports_.size());
664  // Verifying the candidate address different from previously allocated
665  // address.
666  // Skipping verification of component id and candidate type.
667  EXPECT_NE(candidates_[0].address(), candidates_[7].address());
668  EXPECT_NE(candidates_[1].address(), candidates_[8].address());
669
670  // Allocating a different session with sid |session1| and
671  // different ice_pwd.
672  rtc::scoped_ptr<cricket::PortAllocatorSession> session3(
673      CreateSession("session1", kContentName,
674                    cricket::ICE_CANDIDATE_COMPONENT_RTP,
675                    kIceUfrag0, "TestIcePwd"));
676  session3->StartGettingPorts();
677  ASSERT_EQ_WAIT(21U, candidates_.size(), kDefaultAllocationTimeout);
678  EXPECT_EQ(12U, ports_.size());
679  // Verifying the candidate address different from previously
680  // allocated address.
681  EXPECT_NE(candidates_[7].address(), candidates_[14].address());
682  EXPECT_NE(candidates_[8].address(), candidates_[15].address());
683
684  // Allocating a session with by changing both ice_ufrag and ice_pwd.
685  rtc::scoped_ptr<cricket::PortAllocatorSession> session4(
686      CreateSession("session1", kContentName,
687                    cricket::ICE_CANDIDATE_COMPONENT_RTP,
688                    "TestIceUfrag", "TestIcePwd"));
689  session4->StartGettingPorts();
690  ASSERT_EQ_WAIT(28U, candidates_.size(), kDefaultAllocationTimeout);
691  EXPECT_EQ(16U, ports_.size());
692  // Verifying the candidate address different from previously
693  // allocated address.
694  EXPECT_NE(candidates_[14].address(), candidates_[21].address());
695  EXPECT_NE(candidates_[15].address(), candidates_[22].address());
696}
697
698// Test that when the PORTALLOCATOR_ENABLE_SHARED_UFRAG is enabled we got same
699// ufrag and pwd for the collected candidates.
700TEST_F(PortAllocatorTest, TestEnableSharedUfrag) {
701  allocator().set_flags(allocator().flags() |
702                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
703  AddInterface(kClientAddr);
704  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
705  session_->StartGettingPorts();
706  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
707  EXPECT_PRED5(CheckCandidate, candidates_[0],
708      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
709  EXPECT_PRED5(CheckCandidate, candidates_[1],
710      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
711  EXPECT_PRED5(CheckCandidate, candidates_[5],
712      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
713  EXPECT_EQ(4U, ports_.size());
714  EXPECT_EQ(kIceUfrag0, candidates_[0].username());
715  EXPECT_EQ(kIceUfrag0, candidates_[1].username());
716  EXPECT_EQ(kIceUfrag0, candidates_[2].username());
717  EXPECT_EQ(kIcePwd0, candidates_[0].password());
718  EXPECT_EQ(kIcePwd0, candidates_[1].password());
719  EXPECT_TRUE(candidate_allocation_done_);
720}
721
722// Test that when the PORTALLOCATOR_ENABLE_SHARED_UFRAG isn't enabled we got
723// different ufrag and pwd for the collected candidates.
724TEST_F(PortAllocatorTest, TestDisableSharedUfrag) {
725  allocator().set_flags(allocator().flags() &
726                        ~cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
727  AddInterface(kClientAddr);
728  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
729  session_->StartGettingPorts();
730  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
731  EXPECT_PRED5(CheckCandidate, candidates_[0],
732      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
733  EXPECT_PRED5(CheckCandidate, candidates_[1],
734      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
735  EXPECT_EQ(4U, ports_.size());
736  // Port should generate random ufrag and pwd.
737  EXPECT_NE(kIceUfrag0, candidates_[0].username());
738  EXPECT_NE(kIceUfrag0, candidates_[1].username());
739  EXPECT_NE(candidates_[0].username(), candidates_[1].username());
740  EXPECT_NE(kIcePwd0, candidates_[0].password());
741  EXPECT_NE(kIcePwd0, candidates_[1].password());
742  EXPECT_NE(candidates_[0].password(), candidates_[1].password());
743  EXPECT_TRUE(candidate_allocation_done_);
744}
745
746// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
747// is allocated for udp and stun. Also verify there is only one candidate
748// (local) if stun candidate is same as local candidate, which will be the case
749// in a public network like the below test.
750TEST_F(PortAllocatorTest, TestSharedSocketWithoutNat) {
751  AddInterface(kClientAddr);
752  allocator_->set_flags(allocator().flags() |
753                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
754                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
755  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
756  session_->StartGettingPorts();
757  ASSERT_EQ_WAIT(6U, candidates_.size(), kDefaultAllocationTimeout);
758  EXPECT_EQ(3U, ports_.size());
759  EXPECT_PRED5(CheckCandidate, candidates_[0],
760      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
761  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
762}
763
764// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
765// is allocated for udp and stun. In this test we should expect both stun and
766// local candidates as client behind a nat.
767TEST_F(PortAllocatorTest, TestSharedSocketWithNat) {
768  AddInterface(kClientAddr);
769  ResetWithNatServer(kStunAddr);
770
771  allocator_->set_flags(allocator().flags() |
772                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
773                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
774  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
775  session_->StartGettingPorts();
776  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
777  ASSERT_EQ(2U, ports_.size());
778  EXPECT_PRED5(CheckCandidate, candidates_[0],
779      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
780  EXPECT_PRED5(CheckCandidate, candidates_[1],
781      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
782      rtc::SocketAddress(kNatAddr.ipaddr(), 0));
783  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
784  EXPECT_EQ(3U, candidates_.size());
785}
786
787// Test TURN port in shared socket mode with UDP and TCP TURN server adderesses.
788TEST_F(PortAllocatorTest, TestSharedSocketWithoutNatUsingTurn) {
789  turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
790  AddInterface(kClientAddr);
791  allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
792
793  AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr);
794
795  allocator_->set_step_delay(cricket::kMinimumStepDelay);
796  allocator_->set_flags(allocator().flags() |
797                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
798                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
799                        cricket::PORTALLOCATOR_DISABLE_TCP);
800
801  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
802  session_->StartGettingPorts();
803
804  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
805  ASSERT_EQ(3U, ports_.size());
806  EXPECT_PRED5(CheckCandidate, candidates_[0],
807      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
808  EXPECT_PRED5(CheckCandidate, candidates_[1],
809      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
810      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
811  EXPECT_PRED5(CheckCandidate, candidates_[2],
812      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
813      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
814  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
815  EXPECT_EQ(3U, candidates_.size());
816}
817
818// Testing DNS resolve for the TURN server, this will test AllocationSequence
819// handling the unresolved address signal from TurnPort.
820TEST_F(PortAllocatorTest, TestSharedSocketWithServerAddressResolve) {
821  turn_server_.AddInternalSocket(rtc::SocketAddress("127.0.0.1", 3478),
822                                 cricket::PROTO_UDP);
823  AddInterface(kClientAddr);
824  allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
825  cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
826  cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
827  relay_server.credentials = credentials;
828  relay_server.ports.push_back(cricket::ProtocolAddress(
829      rtc::SocketAddress("localhost", 3478),
830      cricket::PROTO_UDP, false));
831  allocator_->AddRelay(relay_server);
832
833  allocator_->set_step_delay(cricket::kMinimumStepDelay);
834  allocator_->set_flags(allocator().flags() |
835                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
836                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
837                        cricket::PORTALLOCATOR_DISABLE_TCP);
838
839  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
840  session_->StartGettingPorts();
841
842  EXPECT_EQ_WAIT(2U, ports_.size(), kDefaultAllocationTimeout);
843}
844
845// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
846// is allocated for udp/stun/turn. In this test we should expect all local,
847// stun and turn candidates.
848TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurn) {
849  AddInterface(kClientAddr);
850  ResetWithNatServer(kStunAddr);
851
852  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
853
854  allocator_->set_flags(allocator().flags() |
855                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
856                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
857                        cricket::PORTALLOCATOR_DISABLE_TCP);
858
859  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
860  session_->StartGettingPorts();
861
862  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
863  ASSERT_EQ(2U, ports_.size());
864  EXPECT_PRED5(CheckCandidate, candidates_[0],
865      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
866  EXPECT_PRED5(CheckCandidate, candidates_[1],
867      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
868      rtc::SocketAddress(kNatAddr.ipaddr(), 0));
869  EXPECT_PRED5(CheckCandidate, candidates_[2],
870      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
871      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
872  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
873  EXPECT_EQ(3U, candidates_.size());
874  // Local port will be created first and then TURN port.
875  EXPECT_EQ(2U, ports_[0]->Candidates().size());
876  EXPECT_EQ(1U, ports_[1]->Candidates().size());
877}
878
879// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled and the TURN
880// server is also used as the STUN server, we should get 'local', 'stun', and
881// 'relay' candidates.
882TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurnAsStun) {
883  AddInterface(kClientAddr);
884  ResetWithNatServer(kTurnUdpIntAddr);
885  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
886
887  // Must set the step delay to 0 to make sure the relay allocation phase is
888  // started before the STUN candidates are obtained, so that the STUN binding
889  // response is processed when both StunPort and TurnPort exist to reproduce
890  // webrtc issue 3537.
891  allocator_->set_step_delay(0);
892  allocator_->set_flags(allocator().flags() |
893                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
894                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
895                        cricket::PORTALLOCATOR_DISABLE_TCP);
896
897  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
898  session_->StartGettingPorts();
899
900  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
901  EXPECT_PRED5(CheckCandidate, candidates_[0],
902      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
903  EXPECT_PRED5(CheckCandidate, candidates_[1],
904      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
905      rtc::SocketAddress(kNatAddr.ipaddr(), 0));
906  EXPECT_PRED5(CheckCandidate, candidates_[2],
907      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
908      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
909  EXPECT_EQ(candidates_[2].related_address(), candidates_[1].address());
910
911  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
912  EXPECT_EQ(3U, candidates_.size());
913  // Local port will be created first and then TURN port.
914  EXPECT_EQ(2U, ports_[0]->Candidates().size());
915  EXPECT_EQ(1U, ports_[1]->Candidates().size());
916}
917
918// This test verifies when PORTALLOCATOR_ENABLE_SHARED_SOCKET flag is enabled
919// and fail to generate STUN candidate, local UDP candidate is generated
920// properly.
921TEST_F(PortAllocatorTest, TestSharedSocketNoUdpAllowed) {
922  allocator().set_flags(allocator().flags() |
923                        cricket::PORTALLOCATOR_DISABLE_RELAY |
924                        cricket::PORTALLOCATOR_DISABLE_TCP |
925                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
926                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
927  fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr);
928  AddInterface(kClientAddr);
929  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
930  session_->StartGettingPorts();
931  ASSERT_EQ_WAIT(1U, ports_.size(), kDefaultAllocationTimeout);
932  EXPECT_EQ(1U, candidates_.size());
933  EXPECT_PRED5(CheckCandidate, candidates_[0],
934      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
935  // STUN timeout is 9sec. We need to wait to get candidate done signal.
936  EXPECT_TRUE_WAIT(candidate_allocation_done_, 10000);
937  EXPECT_EQ(1U, candidates_.size());
938}
939
940// This test verifies allocator can use IPv6 addresses along with IPv4.
941TEST_F(PortAllocatorTest, TestEnableIPv6Addresses) {
942  allocator().set_flags(allocator().flags() |
943                        cricket::PORTALLOCATOR_DISABLE_RELAY |
944                        cricket::PORTALLOCATOR_ENABLE_IPV6 |
945                        cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
946                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
947  AddInterface(kClientIPv6Addr);
948  AddInterface(kClientAddr);
949  allocator_->set_step_delay(cricket::kMinimumStepDelay);
950  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
951  session_->StartGettingPorts();
952  ASSERT_EQ_WAIT(4U, ports_.size(), kDefaultAllocationTimeout);
953  EXPECT_EQ(4U, candidates_.size());
954  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
955  EXPECT_PRED5(CheckCandidate, candidates_[0],
956      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
957      kClientIPv6Addr);
958  EXPECT_PRED5(CheckCandidate, candidates_[1],
959      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
960      kClientAddr);
961  EXPECT_PRED5(CheckCandidate, candidates_[2],
962      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
963      kClientIPv6Addr);
964  EXPECT_PRED5(CheckCandidate, candidates_[3],
965      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
966      kClientAddr);
967  EXPECT_EQ(4U, candidates_.size());
968}
969
970// Test that the httpportallocator correctly maintains its lists of stun and
971// relay servers, by never allowing an empty list.
972TEST(HttpPortAllocatorTest, TestHttpPortAllocatorHostLists) {
973  rtc::FakeNetworkManager network_manager;
974  cricket::HttpPortAllocator alloc(&network_manager, "unit test agent");
975  EXPECT_EQ(1U, alloc.relay_hosts().size());
976  EXPECT_EQ(1U, alloc.stun_hosts().size());
977
978  std::vector<std::string> relay_servers;
979  std::vector<rtc::SocketAddress> stun_servers;
980
981  alloc.SetRelayHosts(relay_servers);
982  alloc.SetStunHosts(stun_servers);
983  EXPECT_EQ(1U, alloc.relay_hosts().size());
984  EXPECT_EQ(1U, alloc.stun_hosts().size());
985
986  relay_servers.push_back("1.unittest.corp.google.com");
987  relay_servers.push_back("2.unittest.corp.google.com");
988  stun_servers.push_back(
989      rtc::SocketAddress("1.unittest.corp.google.com", 0));
990  stun_servers.push_back(
991      rtc::SocketAddress("2.unittest.corp.google.com", 0));
992
993  alloc.SetRelayHosts(relay_servers);
994  alloc.SetStunHosts(stun_servers);
995  EXPECT_EQ(2U, alloc.relay_hosts().size());
996  EXPECT_EQ(2U, alloc.stun_hosts().size());
997}
998
999// Test that the HttpPortAllocator uses correct URL to create sessions.
1000TEST(HttpPortAllocatorTest, TestSessionRequestUrl) {
1001  rtc::FakeNetworkManager network_manager;
1002  cricket::HttpPortAllocator alloc(&network_manager, "unit test agent");
1003
1004  // Disable PORTALLOCATOR_ENABLE_SHARED_UFRAG.
1005  alloc.set_flags(alloc.flags() & ~cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
1006  rtc::scoped_ptr<cricket::HttpPortAllocatorSessionBase> session(
1007      static_cast<cricket::HttpPortAllocatorSession*>(
1008          alloc.CreateSessionInternal(
1009              "test content", 0, kIceUfrag0, kIcePwd0)));
1010  std::string url = session->GetSessionRequestUrl();
1011  LOG(LS_INFO) << "url: " << url;
1012  EXPECT_EQ(std::string(cricket::HttpPortAllocator::kCreateSessionURL), url);
1013
1014  // Enable PORTALLOCATOR_ENABLE_SHARED_UFRAG.
1015  alloc.set_flags(alloc.flags() | cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
1016  session.reset(static_cast<cricket::HttpPortAllocatorSession*>(
1017      alloc.CreateSessionInternal("test content", 0, kIceUfrag0, kIcePwd0)));
1018  url = session->GetSessionRequestUrl();
1019  LOG(LS_INFO) << "url: " << url;
1020  std::vector<std::string> parts;
1021  rtc::split(url, '?', &parts);
1022  ASSERT_EQ(2U, parts.size());
1023
1024  std::vector<std::string> args_parts;
1025  rtc::split(parts[1], '&', &args_parts);
1026
1027  std::map<std::string, std::string> args;
1028  for (std::vector<std::string>::iterator it = args_parts.begin();
1029       it != args_parts.end(); ++it) {
1030    std::vector<std::string> parts;
1031    rtc::split(*it, '=', &parts);
1032    ASSERT_EQ(2U, parts.size());
1033    args[rtc::s_url_decode(parts[0])] = rtc::s_url_decode(parts[1]);
1034  }
1035
1036  EXPECT_EQ(kIceUfrag0, args["username"]);
1037  EXPECT_EQ(kIcePwd0, args["password"]);
1038}
1039