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