portallocator_unittest.cc revision 98db68fdaa12c5bfca8b0004eba24d034f32de71
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/testrelayserver.h"
15#include "webrtc/p2p/base/teststunserver.h"
16#include "webrtc/p2p/base/testturnserver.h"
17#include "webrtc/p2p/client/basicportallocator.h"
18#include "webrtc/p2p/client/httpportallocator.h"
19#include "webrtc/base/fakenetwork.h"
20#include "webrtc/base/firewallsocketserver.h"
21#include "webrtc/base/gunit.h"
22#include "webrtc/base/helpers.h"
23#include "webrtc/base/ipaddress.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 kLoopbackAddr("127.0.0.1", 0);
40static const SocketAddress kPrivateAddr("192.168.1.11", 0);
41static const SocketAddress kPrivateAddr2("192.168.1.12", 0);
42static const SocketAddress kClientIPv6Addr(
43    "2401:fa00:4:1000:be30:5bff:fee5:c3", 0);
44static const SocketAddress kClientAddr2("22.22.22.22", 0);
45static const SocketAddress kNatUdpAddr("77.77.77.77", rtc::NAT_SERVER_UDP_PORT);
46static const SocketAddress kNatTcpAddr("77.77.77.77", rtc::NAT_SERVER_TCP_PORT);
47static const SocketAddress kRemoteClientAddr("22.22.22.22", 0);
48static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
49static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
50static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
51static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
52static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
53static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
54static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
55static const SocketAddress kTurnUdpIntAddr("99.99.99.4", 3478);
56static const SocketAddress kTurnTcpIntAddr("99.99.99.5", 3478);
57static const SocketAddress kTurnUdpExtAddr("99.99.99.6", 0);
58
59// Minimum and maximum port for port range tests.
60static const int kMinPort = 10000;
61static const int kMaxPort = 10099;
62
63// Based on ICE_UFRAG_LENGTH
64static const char kIceUfrag0[] = "TESTICEUFRAG0000";
65// Based on ICE_PWD_LENGTH
66static const char kIcePwd0[] = "TESTICEPWD00000000000000";
67
68static const char kContentName[] = "test content";
69
70static const int kDefaultAllocationTimeout = 1000;
71static const char kTurnUsername[] = "test";
72static const char kTurnPassword[] = "test";
73
74namespace cricket {
75
76// Helper for dumping candidates
77std::ostream& operator<<(std::ostream& os, const cricket::Candidate& c) {
78  os << c.ToString();
79  return os;
80}
81
82}  // namespace cricket
83
84class PortAllocatorTest : public testing::Test, public sigslot::has_slots<> {
85 public:
86  PortAllocatorTest()
87      : pss_(new rtc::PhysicalSocketServer),
88        vss_(new rtc::VirtualSocketServer(pss_.get())),
89        fss_(new rtc::FirewallSocketServer(vss_.get())),
90        ss_scope_(fss_.get()),
91        nat_factory_(vss_.get(), kNatUdpAddr, kNatTcpAddr),
92        nat_socket_factory_(new rtc::BasicPacketSocketFactory(&nat_factory_)),
93        stun_server_(cricket::TestStunServer::Create(Thread::Current(),
94                                                     kStunAddr)),
95        relay_server_(Thread::Current(), kRelayUdpIntAddr, kRelayUdpExtAddr,
96                      kRelayTcpIntAddr, kRelayTcpExtAddr,
97                      kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
98        turn_server_(Thread::Current(), kTurnUdpIntAddr, kTurnUdpExtAddr),
99        candidate_allocation_done_(false) {
100    cricket::ServerAddresses stun_servers;
101    stun_servers.insert(kStunAddr);
102    // Passing the addresses of GTURN servers will enable GTURN in
103    // Basicportallocator.
104    allocator_.reset(new cricket::BasicPortAllocator(
105        &network_manager_,
106        stun_servers,
107        kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr));
108    allocator_->set_step_delay(cricket::kMinimumStepDelay);
109  }
110
111  void AddInterface(const SocketAddress& addr) {
112    network_manager_.AddInterface(addr);
113  }
114  void AddInterface(const SocketAddress& addr, const std::string& if_name) {
115    network_manager_.AddInterface(addr, if_name);
116  }
117  void AddInterfaceAsDefaultRoute(const SocketAddress& addr) {
118    AddInterface(addr);
119    // When a binding comes from the any address, the |addr| will be used as the
120    // srflx address.
121    vss_->SetDefaultRoute(addr.ipaddr());
122  }
123  void RemoveInterface(const SocketAddress& addr) {
124    network_manager_.RemoveInterface(addr);
125  }
126  bool SetPortRange(int min_port, int max_port) {
127    return allocator_->SetPortRange(min_port, max_port);
128  }
129  // Endpoint is on the public network. No STUN or TURN.
130  void ResetWithNoServersOrNat() {
131    allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
132    allocator_->set_step_delay(cricket::kMinimumStepDelay);
133  }
134  // Endpoint is behind a NAT, with STUN specified.
135  void ResetWithStunServerAndNat(const rtc::SocketAddress& stun_server) {
136    ResetWithStunServer(stun_server, true);
137  }
138  // Endpoint is on the public network, with STUN specified.
139  void ResetWithStunServerNoNat(const rtc::SocketAddress& stun_server) {
140    ResetWithStunServer(stun_server, false);
141  }
142  // Endpoint is on the public network, with TURN specified.
143  void ResetWithTurnServersNoNat(const rtc::SocketAddress& udp_turn,
144                                 const rtc::SocketAddress& tcp_turn) {
145    ResetWithNoServersOrNat();
146    AddTurnServers(udp_turn, tcp_turn);
147  }
148
149  void AddTurnServers(const rtc::SocketAddress& udp_turn,
150                      const rtc::SocketAddress& tcp_turn) {
151    cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
152    cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
153    relay_server.credentials = credentials;
154
155    if (!udp_turn.IsNil()) {
156      relay_server.ports.push_back(cricket::ProtocolAddress(
157          kTurnUdpIntAddr, cricket::PROTO_UDP, false));
158    }
159    if (!tcp_turn.IsNil()) {
160      relay_server.ports.push_back(cricket::ProtocolAddress(
161          kTurnTcpIntAddr, cricket::PROTO_TCP, false));
162    }
163    allocator_->AddRelay(relay_server);
164  }
165
166  bool CreateSession(int component) {
167    session_.reset(CreateSession("session", component));
168    if (!session_)
169      return false;
170    return true;
171  }
172
173  bool CreateSession(int component, const std::string& content_name) {
174    session_.reset(CreateSession("session", content_name, component));
175    if (!session_)
176      return false;
177    return true;
178  }
179
180  cricket::PortAllocatorSession* CreateSession(
181      const std::string& sid, int component) {
182    return CreateSession(sid, kContentName, component);
183  }
184
185  cricket::PortAllocatorSession* CreateSession(
186      const std::string& sid, const std::string& content_name, int component) {
187    return CreateSession(sid, content_name, component, kIceUfrag0, kIcePwd0);
188  }
189
190  cricket::PortAllocatorSession* CreateSession(
191      const std::string& sid, const std::string& content_name, int component,
192      const std::string& ice_ufrag, const std::string& ice_pwd) {
193    cricket::PortAllocatorSession* session =
194        allocator_->CreateSession(
195            sid, content_name, component, ice_ufrag, ice_pwd);
196    session->SignalPortReady.connect(this,
197            &PortAllocatorTest::OnPortReady);
198    session->SignalCandidatesReady.connect(this,
199        &PortAllocatorTest::OnCandidatesReady);
200    session->SignalCandidatesAllocationDone.connect(this,
201        &PortAllocatorTest::OnCandidatesAllocationDone);
202    return session;
203  }
204
205  static bool CheckCandidate(const cricket::Candidate& c,
206                             int component, const std::string& type,
207                             const std::string& proto,
208                             const SocketAddress& addr) {
209    return (c.component() == component && c.type() == type &&
210        c.protocol() == proto && c.address().ipaddr() == addr.ipaddr() &&
211        ((addr.port() == 0 && (c.address().port() != 0)) ||
212        (c.address().port() == addr.port())));
213  }
214  static bool CheckPort(const rtc::SocketAddress& addr,
215                        int min_port, int max_port) {
216    return (addr.port() >= min_port && addr.port() <= max_port);
217  }
218
219  void OnCandidatesAllocationDone(cricket::PortAllocatorSession* session) {
220    // We should only get this callback once, except in the mux test where
221    // we have multiple port allocation sessions.
222    if (session == session_.get()) {
223      ASSERT_FALSE(candidate_allocation_done_);
224      candidate_allocation_done_ = true;
225    }
226  }
227
228  // Check if all ports allocated have send-buffer size |expected|. If
229  // |expected| == -1, check if GetOptions returns SOCKET_ERROR.
230  void CheckSendBufferSizesOfAllPorts(int expected) {
231    std::vector<cricket::PortInterface*>::iterator it;
232    for (it = ports_.begin(); it < ports_.end(); ++it) {
233      int send_buffer_size;
234      if (expected == -1) {
235        EXPECT_EQ(SOCKET_ERROR,
236                  (*it)->GetOption(rtc::Socket::OPT_SNDBUF,
237                                   &send_buffer_size));
238      } else {
239        EXPECT_EQ(0, (*it)->GetOption(rtc::Socket::OPT_SNDBUF,
240                                      &send_buffer_size));
241        ASSERT_EQ(expected, send_buffer_size);
242      }
243    }
244  }
245
246  // This function starts the port/address gathering and check the existence of
247  // candidates as specified. When |expect_stun_candidate| is true,
248  // |stun_candidate_addr| carries the expected reflective address, which is
249  // also the related address for TURN candidate if it is expected. Otherwise,
250  // it should be ignore.
251  void CheckDisableAdapterEnumeration(
252      uint32 total_ports,
253      const rtc::IPAddress& host_candidate_addr,
254      const rtc::IPAddress& stun_candidate_addr,
255      const rtc::IPAddress& relay_candidate_udp_transport_addr,
256      const rtc::IPAddress& relay_candidate_tcp_transport_addr) {
257    if (!session_) {
258      EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
259    }
260    session_->set_flags(session_->flags() |
261                        cricket::PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION |
262                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
263    allocator().set_allow_tcp_listen(false);
264    session_->StartGettingPorts();
265    EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
266
267    uint32 total_candidates = 0;
268    if (!host_candidate_addr.IsNil()) {
269      EXPECT_PRED5(CheckCandidate, candidates_[total_candidates],
270                   cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
271                   rtc::SocketAddress(host_candidate_addr, 0));
272      ++total_candidates;
273    }
274    if (!stun_candidate_addr.IsNil()) {
275      EXPECT_PRED5(CheckCandidate, candidates_[total_candidates],
276                   cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
277                   rtc::SocketAddress(stun_candidate_addr, 0));
278      EXPECT_EQ(rtc::EmptySocketAddressWithFamily(
279                    candidates_[total_candidates].address().family()),
280                candidates_[total_candidates].related_address());
281      ++total_candidates;
282    }
283    if (!relay_candidate_udp_transport_addr.IsNil()) {
284      EXPECT_PRED5(CheckCandidate, candidates_[total_candidates],
285                   cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
286                   rtc::SocketAddress(relay_candidate_udp_transport_addr, 0));
287      EXPECT_EQ(stun_candidate_addr,
288                candidates_[total_candidates].related_address().ipaddr());
289      ++total_candidates;
290    }
291    if (!relay_candidate_tcp_transport_addr.IsNil()) {
292      EXPECT_PRED5(CheckCandidate, candidates_[total_candidates],
293                   cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
294                   rtc::SocketAddress(relay_candidate_tcp_transport_addr, 0));
295      EXPECT_EQ(stun_candidate_addr,
296                candidates_[total_candidates].related_address().ipaddr());
297      ++total_candidates;
298    }
299
300    EXPECT_EQ(total_candidates, candidates_.size());
301    EXPECT_EQ(total_ports, ports_.size());
302  }
303
304 protected:
305  cricket::BasicPortAllocator& allocator() {
306    return *allocator_;
307  }
308
309  void OnPortReady(cricket::PortAllocatorSession* ses,
310                   cricket::PortInterface* port) {
311    LOG(LS_INFO) << "OnPortReady: " << port->ToString();
312    ports_.push_back(port);
313  }
314  void OnCandidatesReady(cricket::PortAllocatorSession* ses,
315                         const std::vector<cricket::Candidate>& candidates) {
316    for (size_t i = 0; i < candidates.size(); ++i) {
317      LOG(LS_INFO) << "OnCandidatesReady: " << candidates[i].ToString();
318      candidates_.push_back(candidates[i]);
319    }
320  }
321
322  bool HasRelayAddress(const cricket::ProtocolAddress& proto_addr) {
323    for (size_t i = 0; i < allocator_->relays().size(); ++i) {
324      cricket::RelayServerConfig server_config = allocator_->relays()[i];
325      cricket::PortList::const_iterator relay_port;
326      for (relay_port = server_config.ports.begin();
327          relay_port != server_config.ports.end(); ++relay_port) {
328        if (proto_addr.address == relay_port->address &&
329            proto_addr.proto == relay_port->proto)
330          return true;
331      }
332    }
333    return false;
334  }
335
336  void ResetWithStunServer(const rtc::SocketAddress& stun_server,
337                           bool with_nat) {
338    if (with_nat) {
339      nat_server_.reset(new rtc::NATServer(
340          rtc::NAT_OPEN_CONE, vss_.get(), kNatUdpAddr, kNatTcpAddr, vss_.get(),
341          rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0)));
342    } else {
343      nat_socket_factory_.reset(new rtc::BasicPacketSocketFactory());
344    }
345
346    ServerAddresses stun_servers;
347    if (!stun_server.IsNil()) {
348      stun_servers.insert(stun_server);
349    }
350    allocator_.reset(new cricket::BasicPortAllocator(
351        &network_manager_, nat_socket_factory_.get(), stun_servers));
352    allocator().set_step_delay(cricket::kMinimumStepDelay);
353  }
354
355  rtc::scoped_ptr<rtc::PhysicalSocketServer> pss_;
356  rtc::scoped_ptr<rtc::VirtualSocketServer> vss_;
357  rtc::scoped_ptr<rtc::FirewallSocketServer> fss_;
358  rtc::SocketServerScope ss_scope_;
359  rtc::scoped_ptr<rtc::NATServer> nat_server_;
360  rtc::NATSocketFactory nat_factory_;
361  rtc::scoped_ptr<rtc::BasicPacketSocketFactory> nat_socket_factory_;
362  rtc::scoped_ptr<cricket::TestStunServer> stun_server_;
363  cricket::TestRelayServer relay_server_;
364  cricket::TestTurnServer turn_server_;
365  rtc::FakeNetworkManager network_manager_;
366  rtc::scoped_ptr<cricket::BasicPortAllocator> allocator_;
367  rtc::scoped_ptr<cricket::PortAllocatorSession> session_;
368  std::vector<cricket::PortInterface*> ports_;
369  std::vector<cricket::Candidate> candidates_;
370  bool candidate_allocation_done_;
371};
372
373// Tests that we can init the port allocator and create a session.
374TEST_F(PortAllocatorTest, TestBasic) {
375  EXPECT_EQ(&network_manager_, allocator().network_manager());
376  EXPECT_EQ(kStunAddr, *allocator().stun_servers().begin());
377  ASSERT_EQ(1u, allocator().relays().size());
378  EXPECT_EQ(cricket::RELAY_GTURN, allocator().relays()[0].type);
379  // Empty relay credentials are used for GTURN.
380  EXPECT_TRUE(allocator().relays()[0].credentials.username.empty());
381  EXPECT_TRUE(allocator().relays()[0].credentials.password.empty());
382  EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
383      kRelayUdpIntAddr, cricket::PROTO_UDP)));
384  EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
385      kRelayTcpIntAddr, cricket::PROTO_TCP)));
386  EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
387      kRelaySslTcpIntAddr, cricket::PROTO_SSLTCP)));
388  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
389}
390
391// Tests that we allocator session not trying to allocate ports for every 250ms.
392TEST_F(PortAllocatorTest, TestNoNetworkInterface) {
393  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
394  session_->StartGettingPorts();
395  // Waiting for one second to make sure BasicPortAllocatorSession has not
396  // called OnAllocate multiple times. In old behavior it's called every 250ms.
397  // When there are no network interfaces, each execution of OnAllocate will
398  // result in SignalCandidatesAllocationDone signal.
399  rtc::Thread::Current()->ProcessMessages(1000);
400  EXPECT_TRUE(candidate_allocation_done_);
401  EXPECT_EQ(0U, candidates_.size());
402}
403
404// Test that we could use loopback interface as host candidate.
405TEST_F(PortAllocatorTest, TestLoopbackNetworkInterface) {
406  AddInterface(kLoopbackAddr);
407  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
408  session_->set_flags(cricket::PORTALLOCATOR_DISABLE_STUN |
409                      cricket::PORTALLOCATOR_DISABLE_RELAY |
410                      cricket::PORTALLOCATOR_DISABLE_TCP);
411  session_->StartGettingPorts();
412  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
413  EXPECT_EQ(1U, candidates_.size());
414}
415
416// Tests that we can get all the desired addresses successfully.
417TEST_F(PortAllocatorTest, TestGetAllPortsWithMinimumStepDelay) {
418  AddInterface(kClientAddr);
419  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
420  session_->StartGettingPorts();
421  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
422  EXPECT_EQ(4U, ports_.size());
423  EXPECT_PRED5(CheckCandidate, candidates_[0],
424      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
425  EXPECT_PRED5(CheckCandidate, candidates_[1],
426      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
427  EXPECT_PRED5(CheckCandidate, candidates_[2],
428      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
429  EXPECT_PRED5(CheckCandidate, candidates_[3],
430      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
431  EXPECT_PRED5(CheckCandidate, candidates_[4],
432      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
433  EXPECT_PRED5(CheckCandidate, candidates_[5],
434      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
435  EXPECT_PRED5(CheckCandidate, candidates_[6],
436      cricket::ICE_CANDIDATE_COMPONENT_RTP,
437      "relay", "ssltcp", kRelaySslTcpIntAddr);
438  EXPECT_TRUE(candidate_allocation_done_);
439}
440
441// Test that when the same network interface is brought down and up, the
442// port allocator session will restart a new allocation sequence if
443// it is not stopped.
444TEST_F(PortAllocatorTest, TestSameNetworkDownAndUpWhenSessionNotStopped) {
445  std::string if_name("test_net0");
446  AddInterface(kClientAddr, if_name);
447  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
448  session_->StartGettingPorts();
449  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
450  EXPECT_EQ(4U, ports_.size());
451  EXPECT_TRUE(candidate_allocation_done_);
452  candidate_allocation_done_ = false;
453  candidates_.clear();
454  ports_.clear();
455
456  RemoveInterface(kClientAddr);
457  ASSERT_EQ_WAIT(0U, candidates_.size(), kDefaultAllocationTimeout);
458  EXPECT_EQ(0U, ports_.size());
459  EXPECT_FALSE(candidate_allocation_done_);
460
461  // When the same interfaces are added again, new candidates/ports should be
462  // generated.
463  AddInterface(kClientAddr, if_name);
464  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
465  EXPECT_EQ(4U, ports_.size());
466  EXPECT_TRUE(candidate_allocation_done_);
467}
468
469// Test that when the same network interface is brought down and up, the
470// port allocator session will not restart a new allocation sequence if
471// it is stopped.
472TEST_F(PortAllocatorTest, TestSameNetworkDownAndUpWhenSessionStopped) {
473  std::string if_name("test_net0");
474  AddInterface(kClientAddr, if_name);
475  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
476  session_->StartGettingPorts();
477  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
478  EXPECT_EQ(4U, ports_.size());
479  EXPECT_TRUE(candidate_allocation_done_);
480  session_->StopGettingPorts();
481  candidates_.clear();
482  ports_.clear();
483
484  RemoveInterface(kClientAddr);
485  ASSERT_EQ_WAIT(0U, candidates_.size(), kDefaultAllocationTimeout);
486  EXPECT_EQ(0U, ports_.size());
487
488  // When the same interfaces are added again, new candidates/ports should not
489  // be generated because the session has stopped.
490  AddInterface(kClientAddr, if_name);
491  ASSERT_EQ_WAIT(0U, candidates_.size(), kDefaultAllocationTimeout);
492  EXPECT_EQ(0U, ports_.size());
493  EXPECT_TRUE(candidate_allocation_done_);
494}
495
496// Verify candidates with default step delay of 1sec.
497TEST_F(PortAllocatorTest, TestGetAllPortsWithOneSecondStepDelay) {
498  AddInterface(kClientAddr);
499  allocator_->set_step_delay(cricket::kDefaultStepDelay);
500  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
501  session_->StartGettingPorts();
502  ASSERT_EQ_WAIT(2U, candidates_.size(), 1000);
503  EXPECT_EQ(2U, ports_.size());
504  ASSERT_EQ_WAIT(4U, candidates_.size(), 2000);
505  EXPECT_EQ(3U, ports_.size());
506  EXPECT_PRED5(CheckCandidate, candidates_[2],
507      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
508  EXPECT_PRED5(CheckCandidate, candidates_[3],
509      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
510  ASSERT_EQ_WAIT(6U, candidates_.size(), 1500);
511  EXPECT_PRED5(CheckCandidate, candidates_[4],
512      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
513  EXPECT_PRED5(CheckCandidate, candidates_[5],
514      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
515  EXPECT_EQ(4U, ports_.size());
516  ASSERT_EQ_WAIT(7U, candidates_.size(), 2000);
517  EXPECT_PRED5(CheckCandidate, candidates_[6],
518      cricket::ICE_CANDIDATE_COMPONENT_RTP,
519               "relay", "ssltcp", kRelaySslTcpIntAddr);
520  EXPECT_EQ(4U, ports_.size());
521  EXPECT_TRUE(candidate_allocation_done_);
522  // If we Stop gathering now, we shouldn't get a second "done" callback.
523  session_->StopGettingPorts();
524}
525
526TEST_F(PortAllocatorTest, TestSetupVideoRtpPortsWithNormalSendBuffers) {
527  AddInterface(kClientAddr);
528  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP,
529                            cricket::CN_VIDEO));
530  session_->StartGettingPorts();
531  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
532  EXPECT_TRUE(candidate_allocation_done_);
533  // If we Stop gathering now, we shouldn't get a second "done" callback.
534  session_->StopGettingPorts();
535
536  // All ports should have unset send-buffer sizes.
537  CheckSendBufferSizesOfAllPorts(-1);
538}
539
540// Tests that we can get callback after StopGetAllPorts.
541TEST_F(PortAllocatorTest, TestStopGetAllPorts) {
542  AddInterface(kClientAddr);
543  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
544  session_->StartGettingPorts();
545  ASSERT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
546  EXPECT_EQ(2U, ports_.size());
547  session_->StopGettingPorts();
548  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
549}
550
551// Test that we restrict client ports appropriately when a port range is set.
552// We check the candidates for udp/stun/tcp ports, and the from address
553// for relay ports.
554TEST_F(PortAllocatorTest, TestGetAllPortsPortRange) {
555  AddInterface(kClientAddr);
556  // Check that an invalid port range fails.
557  EXPECT_FALSE(SetPortRange(kMaxPort, kMinPort));
558  // Check that a null port range succeeds.
559  EXPECT_TRUE(SetPortRange(0, 0));
560  // Check that a valid port range succeeds.
561  EXPECT_TRUE(SetPortRange(kMinPort, kMaxPort));
562  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
563  session_->StartGettingPorts();
564  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
565  EXPECT_EQ(4U, ports_.size());
566  // Check the port number for the UDP port object.
567  EXPECT_PRED3(CheckPort, candidates_[0].address(), kMinPort, kMaxPort);
568  // Check the port number for the STUN port object.
569  EXPECT_PRED3(CheckPort, candidates_[1].address(), kMinPort, kMaxPort);
570  // Check the port number used to connect to the relay server.
571  EXPECT_PRED3(CheckPort, relay_server_.GetConnection(0).source(),
572               kMinPort, kMaxPort);
573  // Check the port number for the TCP port object.
574  EXPECT_PRED3(CheckPort, candidates_[5].address(), kMinPort, kMaxPort);
575  EXPECT_TRUE(candidate_allocation_done_);
576}
577
578// Test that we don't crash or malfunction if we have no network adapters.
579TEST_F(PortAllocatorTest, TestGetAllPortsNoAdapters) {
580  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
581  session_->StartGettingPorts();
582  rtc::Thread::Current()->ProcessMessages(100);
583  // Without network adapter, we should not get any candidate.
584  EXPECT_EQ(0U, candidates_.size());
585  EXPECT_TRUE(candidate_allocation_done_);
586}
587
588// Test that we should only get STUN and TURN candidates when adapter
589// enumeration is disabled.
590TEST_F(PortAllocatorTest, TestDisableAdapterEnumerationBehindNat) {
591  AddInterface(kClientAddr);
592  // GTURN is not configured here.
593  ResetWithStunServerAndNat(kStunAddr);
594  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
595  // Expect to see 3 ports: STUN, TURN/UDP and TCP ports, and both STUN and
596  // TURN/UDP candidates.
597  CheckDisableAdapterEnumeration(3U, rtc::IPAddress(), kNatUdpAddr.ipaddr(),
598                                 kTurnUdpExtAddr.ipaddr(), rtc::IPAddress());
599}
600
601// Test that even with multiple interfaces, the result should still be one STUN
602// and one TURN candidate since we bind to any address (i.e. all 0s).
603TEST_F(PortAllocatorTest,
604       TestDisableAdapterEnumerationBehindNatMultipleInterfaces) {
605  AddInterface(kPrivateAddr);
606  AddInterface(kPrivateAddr2);
607  ResetWithStunServerAndNat(kStunAddr);
608  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
609  // Expect to see 3 ports: STUN, TURN/UDP and TCP ports, and both STUN and
610  // TURN/UDP candidates.
611  CheckDisableAdapterEnumeration(3U, rtc::IPAddress(), kNatUdpAddr.ipaddr(),
612                                 kTurnUdpExtAddr.ipaddr(), rtc::IPAddress());
613}
614
615// Test that we should get STUN, TURN/UDP and TURN/TCP candidates when a
616// TURN/TCP server is specified.
617TEST_F(PortAllocatorTest, TestDisableAdapterEnumerationBehindNatWithTcp) {
618  turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
619  AddInterface(kClientAddr);
620  // GTURN is not configured here.
621  ResetWithStunServerAndNat(kStunAddr);
622  AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr);
623  // Expect to see 4 ports - STUN, TURN/UDP, TURN/TCP and TCP port. STUN,
624  // TURN/UDP, and TURN/TCP candidates.
625  CheckDisableAdapterEnumeration(4U, rtc::IPAddress(), kNatUdpAddr.ipaddr(),
626                                 kTurnUdpExtAddr.ipaddr(),
627                                 kTurnUdpExtAddr.ipaddr());
628}
629
630// Test that we should only get STUN and TURN candidates when adapter
631// enumeration is disabled. Since the endpoint is not behind NAT, the srflx
632// address should be the public client interface.
633TEST_F(PortAllocatorTest, TestDisableAdapterEnumerationWithoutNat) {
634  AddInterfaceAsDefaultRoute(kClientAddr);
635  ResetWithStunServerNoNat(kStunAddr);
636  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
637  // Expect to see 3 ports: STUN, TURN/UDP and TCP ports, but only both STUN and
638  // TURN candidates. The STUN candidate should have kClientAddr as srflx
639  // address, and TURN candidate with kClientAddr as the related address.
640  CheckDisableAdapterEnumeration(3U, rtc::IPAddress(), kClientAddr.ipaddr(),
641                                 kTurnUdpExtAddr.ipaddr(), rtc::IPAddress());
642}
643
644// Test that when adapter enumeration is disabled, for endpoints without
645// STUN/TURN specified, no candidate is generated.
646TEST_F(PortAllocatorTest, TestDisableAdapterEnumerationWithoutNatOrServers) {
647  AddInterfaceAsDefaultRoute(kClientAddr);
648  ResetWithNoServersOrNat();
649  // Expect to see 2 ports: STUN and TCP ports, but no candidate.
650  CheckDisableAdapterEnumeration(2U, rtc::IPAddress(), rtc::IPAddress(),
651                                 rtc::IPAddress(), rtc::IPAddress());
652}
653
654// Test that when adapter enumeration is disabled, with
655// PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE specified, for endpoints not behind
656// a NAT, there are a localhost candidate in addition to a STUN candidate.
657TEST_F(PortAllocatorTest,
658       TestDisableAdapterEnumerationWithoutNatLocalhostCandidateRequested) {
659  AddInterfaceAsDefaultRoute(kClientAddr);
660  ResetWithStunServerNoNat(kStunAddr);
661  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
662  session_->set_flags(cricket::PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE);
663  // Expect to see 2 ports: STUN and TCP ports, localhost candidate and STUN
664  // candidate.
665  CheckDisableAdapterEnumeration(2U, rtc::GetLoopbackIP(AF_INET),
666                                 kClientAddr.ipaddr(), rtc::IPAddress(),
667                                 rtc::IPAddress());
668}
669
670// Test that we disable relay over UDP, and only TCP is used when connecting to
671// the relay server.
672TEST_F(PortAllocatorTest, TestDisableUdpTurn) {
673  turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
674  AddInterface(kClientAddr);
675  ResetWithStunServerAndNat(kStunAddr);
676  AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr);
677  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
678  session_->set_flags(cricket::PORTALLOCATOR_DISABLE_UDP_RELAY |
679                      cricket::PORTALLOCATOR_DISABLE_UDP |
680                      cricket::PORTALLOCATOR_DISABLE_STUN |
681                      cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
682
683  session_->StartGettingPorts();
684  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
685
686  // Expect to see 2 ports and 2 candidates - TURN/TCP and TCP ports, TCP and
687  // TURN/TCP candidates.
688  EXPECT_EQ(2U, ports_.size());
689  EXPECT_EQ(2U, candidates_.size());
690  EXPECT_PRED5(CheckCandidate, candidates_[0],
691               cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
692               kTurnUdpExtAddr);
693  // The TURN candidate should use TCP to contact the TURN server.
694  EXPECT_EQ(cricket::TCP_PROTOCOL_NAME, candidates_[0].relay_protocol());
695  EXPECT_PRED5(CheckCandidate, candidates_[1],
696               cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
697               kClientAddr);
698}
699
700// Disable for asan, see
701// https://code.google.com/p/webrtc/issues/detail?id=4743 for details.
702#if !defined(ADDRESS_SANITIZER)
703
704// Test that we can get OnCandidatesAllocationDone callback when all the ports
705// are disabled.
706TEST_F(PortAllocatorTest, TestDisableAllPorts) {
707  AddInterface(kClientAddr);
708  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
709  session_->set_flags(cricket::PORTALLOCATOR_DISABLE_UDP |
710                      cricket::PORTALLOCATOR_DISABLE_STUN |
711                      cricket::PORTALLOCATOR_DISABLE_RELAY |
712                      cricket::PORTALLOCATOR_DISABLE_TCP);
713  session_->StartGettingPorts();
714  rtc::Thread::Current()->ProcessMessages(100);
715  EXPECT_EQ(0U, candidates_.size());
716  EXPECT_TRUE(candidate_allocation_done_);
717}
718
719// Test that we don't crash or malfunction if we can't create UDP sockets.
720TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpSockets) {
721  AddInterface(kClientAddr);
722  fss_->set_udp_sockets_enabled(false);
723  EXPECT_TRUE(CreateSession(1));
724  session_->StartGettingPorts();
725  ASSERT_EQ_WAIT(5U, candidates_.size(), kDefaultAllocationTimeout);
726  EXPECT_EQ(2U, ports_.size());
727  EXPECT_PRED5(CheckCandidate, candidates_[0],
728      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
729  EXPECT_PRED5(CheckCandidate, candidates_[1],
730      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
731  EXPECT_PRED5(CheckCandidate, candidates_[2],
732      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
733  EXPECT_PRED5(CheckCandidate, candidates_[3],
734      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
735  EXPECT_PRED5(CheckCandidate, candidates_[4],
736      cricket::ICE_CANDIDATE_COMPONENT_RTP,
737      "relay", "ssltcp", kRelaySslTcpIntAddr);
738  EXPECT_TRUE(candidate_allocation_done_);
739}
740
741#endif // if !defined(ADDRESS_SANITIZER)
742
743// Test that we don't crash or malfunction if we can't create UDP sockets or
744// listen on TCP sockets. We still give out a local TCP address, since
745// apparently this is needed for the remote side to accept our connection.
746TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpSocketsNoTcpListen) {
747  AddInterface(kClientAddr);
748  fss_->set_udp_sockets_enabled(false);
749  fss_->set_tcp_listen_enabled(false);
750  EXPECT_TRUE(CreateSession(1));
751  session_->StartGettingPorts();
752  ASSERT_EQ_WAIT(5U, candidates_.size(), kDefaultAllocationTimeout);
753  EXPECT_EQ(2U, ports_.size());
754  EXPECT_PRED5(CheckCandidate, candidates_[0],
755      1, "relay", "udp", kRelayUdpIntAddr);
756  EXPECT_PRED5(CheckCandidate, candidates_[1],
757      1, "relay", "udp", kRelayUdpExtAddr);
758  EXPECT_PRED5(CheckCandidate, candidates_[2],
759      1, "relay", "tcp", kRelayTcpIntAddr);
760  EXPECT_PRED5(CheckCandidate, candidates_[3],
761      1, "local", "tcp", kClientAddr);
762  EXPECT_PRED5(CheckCandidate, candidates_[4],
763      1, "relay", "ssltcp", kRelaySslTcpIntAddr);
764  EXPECT_TRUE(candidate_allocation_done_);
765}
766
767// Test that we don't crash or malfunction if we can't create any sockets.
768// TODO: Find a way to exit early here.
769TEST_F(PortAllocatorTest, TestGetAllPortsNoSockets) {
770  AddInterface(kClientAddr);
771  fss_->set_tcp_sockets_enabled(false);
772  fss_->set_udp_sockets_enabled(false);
773  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
774  session_->StartGettingPorts();
775  WAIT(candidates_.size() > 0, 2000);
776  // TODO - Check candidate_allocation_done signal.
777  // In case of Relay, ports creation will succeed but sockets will fail.
778  // There is no error reporting from RelayEntry to handle this failure.
779}
780
781// Testing STUN timeout.
782TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpAllowed) {
783  fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr);
784  AddInterface(kClientAddr);
785  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
786  session_->StartGettingPorts();
787  EXPECT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
788  EXPECT_EQ(2U, ports_.size());
789  EXPECT_PRED5(CheckCandidate, candidates_[0],
790      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
791  EXPECT_PRED5(CheckCandidate, candidates_[1],
792      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
793  // RelayPort connection timeout is 3sec. TCP connection with RelayServer
794  // will be tried after 3 seconds.
795  EXPECT_EQ_WAIT(6U, candidates_.size(), 4000);
796  EXPECT_EQ(3U, ports_.size());
797  EXPECT_PRED5(CheckCandidate, candidates_[2],
798      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
799  EXPECT_PRED5(CheckCandidate, candidates_[3],
800      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
801  EXPECT_PRED5(CheckCandidate, candidates_[4],
802      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "ssltcp",
803      kRelaySslTcpIntAddr);
804  EXPECT_PRED5(CheckCandidate, candidates_[5],
805      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
806  // Stun Timeout is 9sec.
807  EXPECT_TRUE_WAIT(candidate_allocation_done_, 9000);
808}
809
810TEST_F(PortAllocatorTest, TestCandidatePriorityOfMultipleInterfaces) {
811  AddInterface(kClientAddr);
812  AddInterface(kClientAddr2);
813  // Allocating only host UDP ports. This is done purely for testing
814  // convenience.
815  allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_TCP |
816                        cricket::PORTALLOCATOR_DISABLE_STUN |
817                        cricket::PORTALLOCATOR_DISABLE_RELAY);
818  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
819  session_->StartGettingPorts();
820  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
821  ASSERT_EQ(2U, candidates_.size());
822  EXPECT_EQ(2U, ports_.size());
823  // Candidates priorities should be different.
824  EXPECT_NE(candidates_[0].priority(), candidates_[1].priority());
825}
826
827// Test to verify ICE restart process.
828TEST_F(PortAllocatorTest, TestGetAllPortsRestarts) {
829  AddInterface(kClientAddr);
830  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
831  session_->StartGettingPorts();
832  EXPECT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
833  EXPECT_EQ(4U, ports_.size());
834  EXPECT_TRUE(candidate_allocation_done_);
835  // TODO - Extend this to verify ICE restart.
836}
837
838// Test ICE candidate filter mechanism with options Relay/Host/Reflexive.
839// This test also verifies that when the allocator is only allowed to use
840// relay (i.e. IceTransportsType is relay), the raddr is an empty
841// address with the correct family. This is to prevent any local
842// reflective address leakage in the sdp line.
843TEST_F(PortAllocatorTest, TestCandidateFilterWithRelayOnly) {
844  AddInterface(kClientAddr);
845  // GTURN is not configured here.
846  ResetWithTurnServersNoNat(kTurnUdpIntAddr, rtc::SocketAddress());
847  allocator().set_candidate_filter(cricket::CF_RELAY);
848  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
849  session_->StartGettingPorts();
850  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
851  EXPECT_PRED5(CheckCandidate,
852               candidates_[0],
853               cricket::ICE_CANDIDATE_COMPONENT_RTP,
854               "relay",
855               "udp",
856               rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
857
858  EXPECT_EQ(1U, candidates_.size());
859  EXPECT_EQ(1U, ports_.size());  // Only Relay port will be in ready state.
860  for (size_t i = 0; i < candidates_.size(); ++i) {
861    EXPECT_EQ(std::string(cricket::RELAY_PORT_TYPE), candidates_[i].type());
862    EXPECT_EQ(
863        candidates_[0].related_address(),
864        rtc::EmptySocketAddressWithFamily(candidates_[0].address().family()));
865  }
866}
867
868TEST_F(PortAllocatorTest, TestCandidateFilterWithHostOnly) {
869  AddInterface(kClientAddr);
870  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
871  allocator().set_candidate_filter(cricket::CF_HOST);
872  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
873  session_->StartGettingPorts();
874  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
875  EXPECT_EQ(2U, candidates_.size()); // Host UDP/TCP candidates only.
876  EXPECT_EQ(2U, ports_.size()); // UDP/TCP ports only.
877  for (size_t i = 0; i < candidates_.size(); ++i) {
878    EXPECT_EQ(std::string(cricket::LOCAL_PORT_TYPE), candidates_[i].type());
879  }
880}
881
882// Host is behind the NAT.
883TEST_F(PortAllocatorTest, TestCandidateFilterWithReflexiveOnly) {
884  AddInterface(kPrivateAddr);
885  ResetWithStunServerAndNat(kStunAddr);
886
887  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
888  allocator().set_candidate_filter(cricket::CF_REFLEXIVE);
889  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
890  session_->StartGettingPorts();
891  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
892  // Host is behind NAT, no private address will be exposed. Hence only UDP
893  // port with STUN candidate will be sent outside.
894  EXPECT_EQ(1U, candidates_.size()); // Only STUN candidate.
895  EXPECT_EQ(1U, ports_.size());  // Only UDP port will be in ready state.
896  for (size_t i = 0; i < candidates_.size(); ++i) {
897    EXPECT_EQ(std::string(cricket::STUN_PORT_TYPE), candidates_[i].type());
898    EXPECT_EQ(
899        candidates_[0].related_address(),
900        rtc::EmptySocketAddressWithFamily(candidates_[0].address().family()));
901  }
902}
903
904// Host is not behind the NAT.
905TEST_F(PortAllocatorTest, TestCandidateFilterWithReflexiveOnlyAndNoNAT) {
906  AddInterface(kClientAddr);
907  allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
908  allocator().set_candidate_filter(cricket::CF_REFLEXIVE);
909  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
910  session_->StartGettingPorts();
911  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
912  // Host has a public address, both UDP and TCP candidates will be exposed.
913  EXPECT_EQ(2U, candidates_.size()); // Local UDP + TCP candidate.
914  EXPECT_EQ(2U, ports_.size());  //  UDP and TCP ports will be in ready state.
915  for (size_t i = 0; i < candidates_.size(); ++i) {
916    EXPECT_EQ(std::string(cricket::LOCAL_PORT_TYPE), candidates_[i].type());
917  }
918}
919
920// Test that we get the same ufrag and pwd for all candidates.
921TEST_F(PortAllocatorTest, TestEnableSharedUfrag) {
922  AddInterface(kClientAddr);
923  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
924  session_->StartGettingPorts();
925  ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
926  EXPECT_PRED5(CheckCandidate, candidates_[0],
927      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
928  EXPECT_PRED5(CheckCandidate, candidates_[1],
929      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
930  EXPECT_PRED5(CheckCandidate, candidates_[5],
931      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
932  EXPECT_EQ(4U, ports_.size());
933  EXPECT_EQ(kIceUfrag0, candidates_[0].username());
934  EXPECT_EQ(kIceUfrag0, candidates_[1].username());
935  EXPECT_EQ(kIceUfrag0, candidates_[2].username());
936  EXPECT_EQ(kIcePwd0, candidates_[0].password());
937  EXPECT_EQ(kIcePwd0, candidates_[1].password());
938  EXPECT_TRUE(candidate_allocation_done_);
939}
940
941// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
942// is allocated for udp and stun. Also verify there is only one candidate
943// (local) if stun candidate is same as local candidate, which will be the case
944// in a public network like the below test.
945TEST_F(PortAllocatorTest, TestSharedSocketWithoutNat) {
946  AddInterface(kClientAddr);
947  allocator_->set_flags(allocator().flags() |
948                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
949  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
950  session_->StartGettingPorts();
951  ASSERT_EQ_WAIT(6U, candidates_.size(), kDefaultAllocationTimeout);
952  EXPECT_EQ(3U, ports_.size());
953  EXPECT_PRED5(CheckCandidate, candidates_[0],
954      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
955  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
956}
957
958// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
959// is allocated for udp and stun. In this test we should expect both stun and
960// local candidates as client behind a nat.
961TEST_F(PortAllocatorTest, TestSharedSocketWithNat) {
962  AddInterface(kClientAddr);
963  ResetWithStunServerAndNat(kStunAddr);
964
965  allocator_->set_flags(allocator().flags() |
966                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
967  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
968  session_->StartGettingPorts();
969  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
970  ASSERT_EQ(2U, ports_.size());
971  EXPECT_PRED5(CheckCandidate, candidates_[0],
972      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
973  EXPECT_PRED5(CheckCandidate, candidates_[1],
974      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
975      rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0));
976  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
977  EXPECT_EQ(3U, candidates_.size());
978}
979
980// Test TURN port in shared socket mode with UDP and TCP TURN server addresses.
981TEST_F(PortAllocatorTest, TestSharedSocketWithoutNatUsingTurn) {
982  turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
983  AddInterface(kClientAddr);
984  allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
985
986  AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr);
987
988  allocator_->set_step_delay(cricket::kMinimumStepDelay);
989  allocator_->set_flags(allocator().flags() |
990                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
991                        cricket::PORTALLOCATOR_DISABLE_TCP);
992
993  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
994  session_->StartGettingPorts();
995
996  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
997  ASSERT_EQ(3U, ports_.size());
998  EXPECT_PRED5(CheckCandidate, candidates_[0],
999      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
1000  EXPECT_PRED5(CheckCandidate, candidates_[1],
1001      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1002      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1003  EXPECT_PRED5(CheckCandidate, candidates_[2],
1004      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1005      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1006  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
1007  EXPECT_EQ(3U, candidates_.size());
1008}
1009
1010// Testing DNS resolve for the TURN server, this will test AllocationSequence
1011// handling the unresolved address signal from TurnPort.
1012TEST_F(PortAllocatorTest, TestSharedSocketWithServerAddressResolve) {
1013  turn_server_.AddInternalSocket(rtc::SocketAddress("127.0.0.1", 3478),
1014                                 cricket::PROTO_UDP);
1015  AddInterface(kClientAddr);
1016  allocator_.reset(new cricket::BasicPortAllocator(&network_manager_));
1017  cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
1018  cricket::RelayCredentials credentials(kTurnUsername, kTurnPassword);
1019  relay_server.credentials = credentials;
1020  relay_server.ports.push_back(cricket::ProtocolAddress(
1021      rtc::SocketAddress("localhost", 3478),
1022      cricket::PROTO_UDP, false));
1023  allocator_->AddRelay(relay_server);
1024
1025  allocator_->set_step_delay(cricket::kMinimumStepDelay);
1026  allocator_->set_flags(allocator().flags() |
1027                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
1028                        cricket::PORTALLOCATOR_DISABLE_TCP);
1029
1030  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1031  session_->StartGettingPorts();
1032
1033  EXPECT_EQ_WAIT(2U, ports_.size(), kDefaultAllocationTimeout);
1034}
1035
1036// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
1037// is allocated for udp/stun/turn. In this test we should expect all local,
1038// stun and turn candidates.
1039TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurn) {
1040  AddInterface(kClientAddr);
1041  ResetWithStunServerAndNat(kStunAddr);
1042
1043  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
1044
1045  allocator_->set_flags(allocator().flags() |
1046                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
1047                        cricket::PORTALLOCATOR_DISABLE_TCP);
1048
1049  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1050  session_->StartGettingPorts();
1051
1052  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
1053  ASSERT_EQ(2U, ports_.size());
1054  EXPECT_PRED5(CheckCandidate, candidates_[0],
1055      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
1056  EXPECT_PRED5(CheckCandidate, candidates_[1],
1057      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
1058      rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0));
1059  EXPECT_PRED5(CheckCandidate, candidates_[2],
1060      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1061      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1062  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
1063  EXPECT_EQ(3U, candidates_.size());
1064  // Local port will be created first and then TURN port.
1065  EXPECT_EQ(2U, ports_[0]->Candidates().size());
1066  EXPECT_EQ(1U, ports_[1]->Candidates().size());
1067}
1068
1069// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled and the TURN
1070// server is also used as the STUN server, we should get 'local', 'stun', and
1071// 'relay' candidates.
1072TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurnAsStun) {
1073  AddInterface(kClientAddr);
1074  // Use an empty SocketAddress to add a NAT without STUN server.
1075  ResetWithStunServerAndNat(SocketAddress());
1076  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
1077
1078  // Must set the step delay to 0 to make sure the relay allocation phase is
1079  // started before the STUN candidates are obtained, so that the STUN binding
1080  // response is processed when both StunPort and TurnPort exist to reproduce
1081  // webrtc issue 3537.
1082  allocator_->set_step_delay(0);
1083  allocator_->set_flags(allocator().flags() |
1084                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
1085                        cricket::PORTALLOCATOR_DISABLE_TCP);
1086
1087  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1088  session_->StartGettingPorts();
1089
1090  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
1091  EXPECT_PRED5(CheckCandidate, candidates_[0],
1092      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
1093  EXPECT_PRED5(CheckCandidate, candidates_[1],
1094      cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
1095      rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0));
1096  EXPECT_PRED5(CheckCandidate, candidates_[2],
1097      cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1098      rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1099  EXPECT_EQ(candidates_[2].related_address(), candidates_[1].address());
1100
1101  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
1102  EXPECT_EQ(3U, candidates_.size());
1103  // Local port will be created first and then TURN port.
1104  EXPECT_EQ(2U, ports_[0]->Candidates().size());
1105  EXPECT_EQ(1U, ports_[1]->Candidates().size());
1106}
1107
1108// Test that when only a TCP TURN server is available, we do NOT use it as
1109// a UDP STUN server, as this could leak our IP address. Thus we should only
1110// expect two ports, a UDPPort and TurnPort.
1111TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurnTcpOnly) {
1112  turn_server_.AddInternalSocket(kTurnTcpIntAddr, cricket::PROTO_TCP);
1113  AddInterface(kClientAddr);
1114  ResetWithStunServerAndNat(rtc::SocketAddress());
1115  AddTurnServers(rtc::SocketAddress(), kTurnTcpIntAddr);
1116
1117  allocator_->set_flags(allocator().flags() |
1118                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
1119                        cricket::PORTALLOCATOR_DISABLE_TCP);
1120
1121  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1122  session_->StartGettingPorts();
1123
1124  ASSERT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
1125  ASSERT_EQ(2U, ports_.size());
1126  EXPECT_PRED5(CheckCandidate, candidates_[0],
1127               cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
1128               kClientAddr);
1129  EXPECT_PRED5(CheckCandidate, candidates_[1],
1130               cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1131               rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1132  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
1133  EXPECT_EQ(2U, candidates_.size());
1134  EXPECT_EQ(1U, ports_[0]->Candidates().size());
1135  EXPECT_EQ(1U, ports_[1]->Candidates().size());
1136}
1137
1138// Test that even when PORTALLOCATOR_ENABLE_SHARED_SOCKET is NOT enabled, the
1139// TURN server is used as the STUN server and we get 'local', 'stun', and
1140// 'relay' candidates.
1141// TODO(deadbeef): Remove this test when support for non-shared socket mode
1142// is removed.
1143TEST_F(PortAllocatorTest, TestNonSharedSocketWithNatUsingTurnAsStun) {
1144  AddInterface(kClientAddr);
1145  // Use an empty SocketAddress to add a NAT without STUN server.
1146  ResetWithStunServerAndNat(SocketAddress());
1147  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
1148
1149  allocator_->set_flags(allocator().flags() |
1150                        cricket::PORTALLOCATOR_DISABLE_TCP);
1151
1152  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1153  session_->StartGettingPorts();
1154
1155  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
1156  ASSERT_EQ(3U, ports_.size());
1157  EXPECT_PRED5(CheckCandidate, candidates_[0],
1158               cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
1159               kClientAddr);
1160  EXPECT_PRED5(CheckCandidate, candidates_[1],
1161               cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
1162               rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0));
1163  EXPECT_PRED5(CheckCandidate, candidates_[2],
1164               cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1165               rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1166  // Not using shared socket, so the STUN request's server reflexive address
1167  // should be different than the TURN request's server reflexive address.
1168  EXPECT_NE(candidates_[2].related_address(), candidates_[1].address());
1169
1170  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
1171  EXPECT_EQ(3U, candidates_.size());
1172  EXPECT_EQ(1U, ports_[0]->Candidates().size());
1173  EXPECT_EQ(1U, ports_[1]->Candidates().size());
1174  EXPECT_EQ(1U, ports_[2]->Candidates().size());
1175}
1176
1177// Test that even when both a STUN and TURN server are configured, the TURN
1178// server is used as a STUN server and we get a 'stun' candidate.
1179TEST_F(PortAllocatorTest, TestSharedSocketWithNatUsingTurnAndStun) {
1180  AddInterface(kClientAddr);
1181  // Configure with STUN server but destroy it, so we can ensure that it's
1182  // the TURN server actually being used as a STUN server.
1183  ResetWithStunServerAndNat(kStunAddr);
1184  stun_server_.reset();
1185  AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress());
1186
1187  allocator_->set_flags(allocator().flags() |
1188                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
1189                        cricket::PORTALLOCATOR_DISABLE_TCP);
1190
1191  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1192  session_->StartGettingPorts();
1193
1194  ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
1195  EXPECT_PRED5(CheckCandidate, candidates_[0],
1196               cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
1197               kClientAddr);
1198  EXPECT_PRED5(CheckCandidate, candidates_[1],
1199               cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
1200               rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0));
1201  EXPECT_PRED5(CheckCandidate, candidates_[2],
1202               cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp",
1203               rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0));
1204  EXPECT_EQ(candidates_[2].related_address(), candidates_[1].address());
1205
1206  // Don't bother waiting for STUN timeout, since we already verified
1207  // that we got a STUN candidate from the TURN server.
1208}
1209
1210// This test verifies when PORTALLOCATOR_ENABLE_SHARED_SOCKET flag is enabled
1211// and fail to generate STUN candidate, local UDP candidate is generated
1212// properly.
1213TEST_F(PortAllocatorTest, TestSharedSocketNoUdpAllowed) {
1214  allocator().set_flags(allocator().flags() |
1215                        cricket::PORTALLOCATOR_DISABLE_RELAY |
1216                        cricket::PORTALLOCATOR_DISABLE_TCP |
1217                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
1218  fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr);
1219  AddInterface(kClientAddr);
1220  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1221  session_->StartGettingPorts();
1222  ASSERT_EQ_WAIT(1U, ports_.size(), kDefaultAllocationTimeout);
1223  EXPECT_EQ(1U, candidates_.size());
1224  EXPECT_PRED5(CheckCandidate, candidates_[0],
1225      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
1226  // STUN timeout is 9sec. We need to wait to get candidate done signal.
1227  EXPECT_TRUE_WAIT(candidate_allocation_done_, 10000);
1228  EXPECT_EQ(1U, candidates_.size());
1229}
1230
1231// Test that when the NetworkManager doesn't have permission to enumerate
1232// adapters, the PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION is specified
1233// automatically.
1234TEST_F(PortAllocatorTest, TestNetworkPermissionBlocked) {
1235  AddInterface(kClientAddr);
1236  network_manager_.set_enumeration_permission(
1237      rtc::NetworkManager::ENUMERATION_BLOCKED);
1238  allocator().set_flags(allocator().flags() |
1239                        cricket::PORTALLOCATOR_DISABLE_RELAY |
1240                        cricket::PORTALLOCATOR_DISABLE_TCP |
1241                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
1242  EXPECT_EQ(0U, allocator_->flags() &
1243                    cricket::PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
1244  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1245  EXPECT_EQ(0U, session_->flags() &
1246                    cricket::PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
1247  session_->StartGettingPorts();
1248  EXPECT_EQ_WAIT(1U, ports_.size(), kDefaultAllocationTimeout);
1249  EXPECT_EQ(0U, candidates_.size());
1250  EXPECT_TRUE((session_->flags() &
1251               cricket::PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) != 0);
1252}
1253
1254// This test verifies allocator can use IPv6 addresses along with IPv4.
1255TEST_F(PortAllocatorTest, TestEnableIPv6Addresses) {
1256  allocator().set_flags(allocator().flags() |
1257                        cricket::PORTALLOCATOR_DISABLE_RELAY |
1258                        cricket::PORTALLOCATOR_ENABLE_IPV6 |
1259                        cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
1260  AddInterface(kClientIPv6Addr);
1261  AddInterface(kClientAddr);
1262  allocator_->set_step_delay(cricket::kMinimumStepDelay);
1263  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1264  session_->StartGettingPorts();
1265  ASSERT_EQ_WAIT(4U, ports_.size(), kDefaultAllocationTimeout);
1266  EXPECT_EQ(4U, candidates_.size());
1267  EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
1268  EXPECT_PRED5(CheckCandidate, candidates_[0],
1269      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
1270      kClientIPv6Addr);
1271  EXPECT_PRED5(CheckCandidate, candidates_[1],
1272      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
1273      kClientAddr);
1274  EXPECT_PRED5(CheckCandidate, candidates_[2],
1275      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
1276      kClientIPv6Addr);
1277  EXPECT_PRED5(CheckCandidate, candidates_[3],
1278      cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
1279      kClientAddr);
1280  EXPECT_EQ(4U, candidates_.size());
1281}
1282
1283TEST_F(PortAllocatorTest, TestStopGettingPorts) {
1284  AddInterface(kClientAddr);
1285  allocator_->set_step_delay(cricket::kDefaultStepDelay);
1286  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1287  session_->StartGettingPorts();
1288  ASSERT_EQ_WAIT(2U, candidates_.size(), 1000);
1289  EXPECT_EQ(2U, ports_.size());
1290  session_->StopGettingPorts();
1291  EXPECT_TRUE_WAIT(candidate_allocation_done_, 1000);
1292
1293  // After stopping getting ports, adding a new interface will not start
1294  // getting ports again.
1295  candidates_.clear();
1296  ports_.clear();
1297  candidate_allocation_done_ = false;
1298  network_manager_.AddInterface(kClientAddr2);
1299  rtc::Thread::Current()->ProcessMessages(1000);
1300  EXPECT_EQ(0U, candidates_.size());
1301  EXPECT_EQ(0U, ports_.size());
1302}
1303
1304TEST_F(PortAllocatorTest, TestClearGettingPorts) {
1305  AddInterface(kClientAddr);
1306  allocator_->set_step_delay(cricket::kDefaultStepDelay);
1307  EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
1308  session_->StartGettingPorts();
1309  ASSERT_EQ_WAIT(2U, candidates_.size(), 1000);
1310  EXPECT_EQ(2U, ports_.size());
1311  session_->ClearGettingPorts();
1312  WAIT(candidate_allocation_done_, 1000);
1313  EXPECT_FALSE(candidate_allocation_done_);
1314
1315  // After clearing getting ports, adding a new interface will start getting
1316  // ports again.
1317  candidates_.clear();
1318  ports_.clear();
1319  candidate_allocation_done_ = false;
1320  network_manager_.AddInterface(kClientAddr2);
1321  ASSERT_EQ_WAIT(2U, candidates_.size(), 1000);
1322  EXPECT_EQ(2U, ports_.size());
1323}
1324