Upstream version 5.34.104.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/base/fakenetwork.h"
29 #include "talk/base/firewallsocketserver.h"
30 #include "talk/base/gunit.h"
31 #include "talk/base/helpers.h"
32 #include "talk/base/logging.h"
33 #include "talk/base/natserver.h"
34 #include "talk/base/natsocketfactory.h"
35 #include "talk/base/network.h"
36 #include "talk/base/physicalsocketserver.h"
37 #include "talk/base/socketaddress.h"
38 #include "talk/base/ssladapter.h"
39 #include "talk/base/thread.h"
40 #include "talk/base/virtualsocketserver.h"
41 #include "talk/p2p/base/basicpacketsocketfactory.h"
42 #include "talk/p2p/base/constants.h"
43 #include "talk/p2p/base/p2ptransportchannel.h"
44 #include "talk/p2p/base/portallocatorsessionproxy.h"
45 #include "talk/p2p/base/testrelayserver.h"
46 #include "talk/p2p/base/teststunserver.h"
47 #include "talk/p2p/client/basicportallocator.h"
48 #include "talk/p2p/client/httpportallocator.h"
49
50 using talk_base::SocketAddress;
51 using talk_base::Thread;
52
53 static const SocketAddress kClientAddr("11.11.11.11", 0);
54 static const SocketAddress kClientIPv6Addr(
55     "2401:fa00:4:1000:be30:5bff:fee5:c3", 0);
56 static const SocketAddress kClientAddr2("22.22.22.22", 0);
57 static const SocketAddress kNatAddr("77.77.77.77", talk_base::NAT_SERVER_PORT);
58 static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
59 static const SocketAddress kRelayUdpIntAddr("99.99.99.2", 5000);
60 static const SocketAddress kRelayUdpExtAddr("99.99.99.3", 5001);
61 static const SocketAddress kRelayTcpIntAddr("99.99.99.2", 5002);
62 static const SocketAddress kRelayTcpExtAddr("99.99.99.3", 5003);
63 static const SocketAddress kRelaySslTcpIntAddr("99.99.99.2", 5004);
64 static const SocketAddress kRelaySslTcpExtAddr("99.99.99.3", 5005);
65
66 // Minimum and maximum port for port range tests.
67 static const int kMinPort = 10000;
68 static const int kMaxPort = 10099;
69
70 // Based on ICE_UFRAG_LENGTH
71 static const char kIceUfrag0[] = "TESTICEUFRAG0000";
72 // Based on ICE_PWD_LENGTH
73 static const char kIcePwd0[] = "TESTICEPWD00000000000000";
74
75 static const char kContentName[] = "test content";
76
77 static const int kDefaultAllocationTimeout = 1000;
78
79 namespace cricket {
80
81 // Helper for dumping candidates
82 std::ostream& operator<<(std::ostream& os, const cricket::Candidate& c) {
83   os << c.ToString();
84   return os;
85 }
86
87 }  // namespace cricket
88
89 class PortAllocatorTest : public testing::Test, public sigslot::has_slots<> {
90  public:
91   static void SetUpTestCase() {
92     talk_base::InitializeSSL();
93   }
94
95   static void TearDownTestCase() {
96     talk_base::CleanupSSL();
97   }
98
99   PortAllocatorTest()
100       : pss_(new talk_base::PhysicalSocketServer),
101         vss_(new talk_base::VirtualSocketServer(pss_.get())),
102         fss_(new talk_base::FirewallSocketServer(vss_.get())),
103         ss_scope_(fss_.get()),
104         nat_factory_(vss_.get(), kNatAddr),
105         nat_socket_factory_(&nat_factory_),
106         stun_server_(Thread::Current(), kStunAddr),
107         relay_server_(Thread::Current(), kRelayUdpIntAddr, kRelayUdpExtAddr,
108                       kRelayTcpIntAddr, kRelayTcpExtAddr,
109                       kRelaySslTcpIntAddr, kRelaySslTcpExtAddr),
110         allocator_(new cricket::BasicPortAllocator(
111             &network_manager_, kStunAddr,
112             kRelayUdpIntAddr, kRelayTcpIntAddr, kRelaySslTcpIntAddr)),
113         candidate_allocation_done_(false) {
114     allocator_->set_step_delay(cricket::kMinimumStepDelay);
115   }
116
117   void AddInterface(const SocketAddress& addr) {
118     network_manager_.AddInterface(addr);
119   }
120   bool SetPortRange(int min_port, int max_port) {
121     return allocator_->SetPortRange(min_port, max_port);
122   }
123   talk_base::NATServer* CreateNatServer(const SocketAddress& addr,
124                                         talk_base::NATType type) {
125     return new talk_base::NATServer(type, vss_.get(), addr, vss_.get(), addr);
126   }
127
128   bool CreateSession(int component) {
129     session_.reset(CreateSession("session", component));
130     if (!session_)
131       return false;
132     return true;
133   }
134
135   bool CreateSession(int component, const std::string& content_name) {
136     session_.reset(CreateSession("session", content_name, component));
137     if (!session_)
138       return false;
139     return true;
140   }
141
142   cricket::PortAllocatorSession* CreateSession(
143       const std::string& sid, int component) {
144     return CreateSession(sid, kContentName, component);
145   }
146
147   cricket::PortAllocatorSession* CreateSession(
148       const std::string& sid, const std::string& content_name, int component) {
149     return CreateSession(sid, content_name, component, kIceUfrag0, kIcePwd0);
150   }
151
152   cricket::PortAllocatorSession* CreateSession(
153       const std::string& sid, const std::string& content_name, int component,
154       const std::string& ice_ufrag, const std::string& ice_pwd) {
155     cricket::PortAllocatorSession* session =
156         allocator_->CreateSession(
157             sid, content_name, component, ice_ufrag, ice_pwd);
158     session->SignalPortReady.connect(this,
159             &PortAllocatorTest::OnPortReady);
160     session->SignalCandidatesReady.connect(this,
161         &PortAllocatorTest::OnCandidatesReady);
162     session->SignalCandidatesAllocationDone.connect(this,
163         &PortAllocatorTest::OnCandidatesAllocationDone);
164     return session;
165   }
166
167   static bool CheckCandidate(const cricket::Candidate& c,
168                              int component, const std::string& type,
169                              const std::string& proto,
170                              const SocketAddress& addr) {
171     return (c.component() == component && c.type() == type &&
172         c.protocol() == proto && c.address().ipaddr() == addr.ipaddr() &&
173         ((addr.port() == 0 && (c.address().port() != 0)) ||
174         (c.address().port() == addr.port())));
175   }
176   static bool CheckPort(const talk_base::SocketAddress& addr,
177                         int min_port, int max_port) {
178     return (addr.port() >= min_port && addr.port() <= max_port);
179   }
180
181   void OnCandidatesAllocationDone(cricket::PortAllocatorSession* session) {
182     // We should only get this callback once, except in the mux test where
183     // we have multiple port allocation sessions.
184     if (session == session_.get()) {
185       ASSERT_FALSE(candidate_allocation_done_);
186       candidate_allocation_done_ = true;
187     }
188   }
189
190   // Check if all ports allocated have send-buffer size |expected|. If
191   // |expected| == -1, check if GetOptions returns SOCKET_ERROR.
192   void CheckSendBufferSizesOfAllPorts(int expected) {
193     std::vector<cricket::PortInterface*>::iterator it;
194     for (it = ports_.begin(); it < ports_.end(); ++it) {
195       int send_buffer_size;
196       if (expected == -1) {
197         EXPECT_EQ(SOCKET_ERROR,
198                   (*it)->GetOption(talk_base::Socket::OPT_SNDBUF,
199                                    &send_buffer_size));
200       } else {
201         EXPECT_EQ(0, (*it)->GetOption(talk_base::Socket::OPT_SNDBUF,
202                                       &send_buffer_size));
203         ASSERT_EQ(expected, send_buffer_size);
204       }
205     }
206   }
207
208  protected:
209   cricket::BasicPortAllocator& allocator() {
210     return *allocator_;
211   }
212
213   void OnPortReady(cricket::PortAllocatorSession* ses,
214                    cricket::PortInterface* port) {
215     LOG(LS_INFO) << "OnPortReady: " << port->ToString();
216     ports_.push_back(port);
217   }
218   void OnCandidatesReady(cricket::PortAllocatorSession* ses,
219                          const std::vector<cricket::Candidate>& candidates) {
220     for (size_t i = 0; i < candidates.size(); ++i) {
221       LOG(LS_INFO) << "OnCandidatesReady: " << candidates[i].ToString();
222       candidates_.push_back(candidates[i]);
223     }
224   }
225
226   bool HasRelayAddress(const cricket::ProtocolAddress& proto_addr) {
227     for (size_t i = 0; i < allocator_->relays().size(); ++i) {
228       cricket::RelayServerConfig server_config = allocator_->relays()[i];
229       cricket::PortList::const_iterator relay_port;
230       for (relay_port = server_config.ports.begin();
231           relay_port != server_config.ports.end(); ++relay_port) {
232         if (proto_addr.address == relay_port->address &&
233             proto_addr.proto == relay_port->proto)
234           return true;
235       }
236     }
237     return false;
238   }
239
240   talk_base::scoped_ptr<talk_base::PhysicalSocketServer> pss_;
241   talk_base::scoped_ptr<talk_base::VirtualSocketServer> vss_;
242   talk_base::scoped_ptr<talk_base::FirewallSocketServer> fss_;
243   talk_base::SocketServerScope ss_scope_;
244   talk_base::NATSocketFactory nat_factory_;
245   talk_base::BasicPacketSocketFactory nat_socket_factory_;
246   cricket::TestStunServer stun_server_;
247   cricket::TestRelayServer relay_server_;
248   talk_base::FakeNetworkManager network_manager_;
249   talk_base::scoped_ptr<cricket::BasicPortAllocator> allocator_;
250   talk_base::scoped_ptr<cricket::PortAllocatorSession> session_;
251   std::vector<cricket::PortInterface*> ports_;
252   std::vector<cricket::Candidate> candidates_;
253   bool candidate_allocation_done_;
254 };
255
256 // Tests that we can init the port allocator and create a session.
257 TEST_F(PortAllocatorTest, TestBasic) {
258   EXPECT_EQ(&network_manager_, allocator().network_manager());
259   EXPECT_EQ(kStunAddr, allocator().stun_address());
260   ASSERT_EQ(1u, allocator().relays().size());
261   EXPECT_EQ(cricket::RELAY_GTURN, allocator().relays()[0].type);
262   // Empty relay credentials are used for GTURN.
263   EXPECT_TRUE(allocator().relays()[0].credentials.username.empty());
264   EXPECT_TRUE(allocator().relays()[0].credentials.password.empty());
265   EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
266       kRelayUdpIntAddr, cricket::PROTO_UDP)));
267   EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
268       kRelayTcpIntAddr, cricket::PROTO_TCP)));
269   EXPECT_TRUE(HasRelayAddress(cricket::ProtocolAddress(
270       kRelaySslTcpIntAddr, cricket::PROTO_SSLTCP)));
271   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
272 }
273
274 // Tests that we can get all the desired addresses successfully.
275 TEST_F(PortAllocatorTest, TestGetAllPortsWithMinimumStepDelay) {
276   AddInterface(kClientAddr);
277   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
278   session_->StartGettingPorts();
279   ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
280   EXPECT_EQ(4U, ports_.size());
281   EXPECT_PRED5(CheckCandidate, candidates_[0],
282       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
283   EXPECT_PRED5(CheckCandidate, candidates_[1],
284       cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
285   EXPECT_PRED5(CheckCandidate, candidates_[2],
286       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
287   EXPECT_PRED5(CheckCandidate, candidates_[3],
288       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
289   EXPECT_PRED5(CheckCandidate, candidates_[4],
290       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
291   EXPECT_PRED5(CheckCandidate, candidates_[5],
292       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
293   EXPECT_PRED5(CheckCandidate, candidates_[6],
294       cricket::ICE_CANDIDATE_COMPONENT_RTP,
295       "relay", "ssltcp", kRelaySslTcpIntAddr);
296   EXPECT_TRUE(candidate_allocation_done_);
297 }
298
299 // Verify candidates with default step delay of 1sec.
300 TEST_F(PortAllocatorTest, TestGetAllPortsWithOneSecondStepDelay) {
301   AddInterface(kClientAddr);
302   allocator_->set_step_delay(cricket::kDefaultStepDelay);
303   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
304   session_->StartGettingPorts();
305   ASSERT_EQ_WAIT(2U, candidates_.size(), 1000);
306   EXPECT_EQ(2U, ports_.size());
307   ASSERT_EQ_WAIT(4U, candidates_.size(), 2000);
308   EXPECT_EQ(3U, ports_.size());
309   EXPECT_PRED5(CheckCandidate, candidates_[2],
310       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
311   EXPECT_PRED5(CheckCandidate, candidates_[3],
312       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
313   ASSERT_EQ_WAIT(6U, candidates_.size(), 1500);
314   EXPECT_PRED5(CheckCandidate, candidates_[4],
315       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
316   EXPECT_PRED5(CheckCandidate, candidates_[5],
317       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
318   EXPECT_EQ(4U, ports_.size());
319   ASSERT_EQ_WAIT(7U, candidates_.size(), 2000);
320   EXPECT_PRED5(CheckCandidate, candidates_[6],
321       cricket::ICE_CANDIDATE_COMPONENT_RTP,
322                "relay", "ssltcp", kRelaySslTcpIntAddr);
323   EXPECT_EQ(4U, ports_.size());
324   EXPECT_TRUE(candidate_allocation_done_);
325   // If we Stop gathering now, we shouldn't get a second "done" callback.
326   session_->StopGettingPorts();
327 }
328
329 TEST_F(PortAllocatorTest, TestSetupVideoRtpPortsWithNormalSendBuffers) {
330   AddInterface(kClientAddr);
331   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP,
332                             cricket::CN_VIDEO));
333   session_->StartGettingPorts();
334   ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
335   EXPECT_TRUE(candidate_allocation_done_);
336   // If we Stop gathering now, we shouldn't get a second "done" callback.
337   session_->StopGettingPorts();
338
339   // All ports should have unset send-buffer sizes.
340   CheckSendBufferSizesOfAllPorts(-1);
341 }
342
343 // Tests that we can get callback after StopGetAllPorts.
344 TEST_F(PortAllocatorTest, TestStopGetAllPorts) {
345   AddInterface(kClientAddr);
346   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
347   session_->StartGettingPorts();
348   ASSERT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
349   EXPECT_EQ(2U, ports_.size());
350   session_->StopGettingPorts();
351   EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
352 }
353
354 // Test that we restrict client ports appropriately when a port range is set.
355 // We check the candidates for udp/stun/tcp ports, and the from address
356 // for relay ports.
357 TEST_F(PortAllocatorTest, TestGetAllPortsPortRange) {
358   AddInterface(kClientAddr);
359   // Check that an invalid port range fails.
360   EXPECT_FALSE(SetPortRange(kMaxPort, kMinPort));
361   // Check that a null port range succeeds.
362   EXPECT_TRUE(SetPortRange(0, 0));
363   // Check that a valid port range succeeds.
364   EXPECT_TRUE(SetPortRange(kMinPort, kMaxPort));
365   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
366   session_->StartGettingPorts();
367   ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
368   EXPECT_EQ(4U, ports_.size());
369   // Check the port number for the UDP port object.
370   EXPECT_PRED3(CheckPort, candidates_[0].address(), kMinPort, kMaxPort);
371   // Check the port number for the STUN port object.
372   EXPECT_PRED3(CheckPort, candidates_[1].address(), kMinPort, kMaxPort);
373   // Check the port number used to connect to the relay server.
374   EXPECT_PRED3(CheckPort, relay_server_.GetConnection(0).source(),
375                kMinPort, kMaxPort);
376   // Check the port number for the TCP port object.
377   EXPECT_PRED3(CheckPort, candidates_[5].address(), kMinPort, kMaxPort);
378   EXPECT_TRUE(candidate_allocation_done_);
379 }
380
381 // Test that we don't crash or malfunction if we have no network adapters.
382 TEST_F(PortAllocatorTest, TestGetAllPortsNoAdapters) {
383   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
384   session_->StartGettingPorts();
385   talk_base::Thread::Current()->ProcessMessages(100);
386   // Without network adapter, we should not get any candidate.
387   EXPECT_EQ(0U, candidates_.size());
388   EXPECT_TRUE(candidate_allocation_done_);
389 }
390
391 // Test that we can get OnCandidatesAllocationDone callback when all the ports
392 // are disabled.
393 TEST_F(PortAllocatorTest, TestDisableAllPorts) {
394   AddInterface(kClientAddr);
395   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
396   session_->set_flags(cricket::PORTALLOCATOR_DISABLE_UDP |
397                       cricket::PORTALLOCATOR_DISABLE_STUN |
398                       cricket::PORTALLOCATOR_DISABLE_RELAY |
399                       cricket::PORTALLOCATOR_DISABLE_TCP);
400   session_->StartGettingPorts();
401   talk_base::Thread::Current()->ProcessMessages(100);
402   EXPECT_EQ(0U, candidates_.size());
403   EXPECT_TRUE(candidate_allocation_done_);
404 }
405
406 // Test that we don't crash or malfunction if we can't create UDP sockets.
407 TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpSockets) {
408   AddInterface(kClientAddr);
409   fss_->set_udp_sockets_enabled(false);
410   EXPECT_TRUE(CreateSession(1));
411   session_->StartGettingPorts();
412   ASSERT_EQ_WAIT(5U, candidates_.size(), kDefaultAllocationTimeout);
413   EXPECT_EQ(2U, ports_.size());
414   EXPECT_PRED5(CheckCandidate, candidates_[0],
415       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
416   EXPECT_PRED5(CheckCandidate, candidates_[1],
417       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
418   EXPECT_PRED5(CheckCandidate, candidates_[2],
419       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
420   EXPECT_PRED5(CheckCandidate, candidates_[3],
421       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
422   EXPECT_PRED5(CheckCandidate, candidates_[4],
423       cricket::ICE_CANDIDATE_COMPONENT_RTP,
424       "relay", "ssltcp", kRelaySslTcpIntAddr);
425   EXPECT_TRUE(candidate_allocation_done_);
426 }
427
428 // Test that we don't crash or malfunction if we can't create UDP sockets or
429 // listen on TCP sockets. We still give out a local TCP address, since
430 // apparently this is needed for the remote side to accept our connection.
431 TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpSocketsNoTcpListen) {
432   AddInterface(kClientAddr);
433   fss_->set_udp_sockets_enabled(false);
434   fss_->set_tcp_listen_enabled(false);
435   EXPECT_TRUE(CreateSession(1));
436   session_->StartGettingPorts();
437   ASSERT_EQ_WAIT(5U, candidates_.size(), kDefaultAllocationTimeout);
438   EXPECT_EQ(2U, ports_.size());
439   EXPECT_PRED5(CheckCandidate, candidates_[0],
440       1, "relay", "udp", kRelayUdpIntAddr);
441   EXPECT_PRED5(CheckCandidate, candidates_[1],
442       1, "relay", "udp", kRelayUdpExtAddr);
443   EXPECT_PRED5(CheckCandidate, candidates_[2],
444       1, "relay", "tcp", kRelayTcpIntAddr);
445   EXPECT_PRED5(CheckCandidate, candidates_[3],
446       1, "local", "tcp", kClientAddr);
447   EXPECT_PRED5(CheckCandidate, candidates_[4],
448       1, "relay", "ssltcp", kRelaySslTcpIntAddr);
449   EXPECT_TRUE(candidate_allocation_done_);
450 }
451
452 // Test that we don't crash or malfunction if we can't create any sockets.
453 // TODO: Find a way to exit early here.
454 TEST_F(PortAllocatorTest, TestGetAllPortsNoSockets) {
455   AddInterface(kClientAddr);
456   fss_->set_tcp_sockets_enabled(false);
457   fss_->set_udp_sockets_enabled(false);
458   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
459   session_->StartGettingPorts();
460   WAIT(candidates_.size() > 0, 2000);
461   // TODO - Check candidate_allocation_done signal.
462   // In case of Relay, ports creation will succeed but sockets will fail.
463   // There is no error reporting from RelayEntry to handle this failure.
464 }
465
466 // Testing STUN timeout.
467 TEST_F(PortAllocatorTest, TestGetAllPortsNoUdpAllowed) {
468   fss_->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY, kClientAddr);
469   AddInterface(kClientAddr);
470   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
471   session_->StartGettingPorts();
472   EXPECT_EQ_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout);
473   EXPECT_EQ(2U, ports_.size());
474   EXPECT_PRED5(CheckCandidate, candidates_[0],
475       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
476   EXPECT_PRED5(CheckCandidate, candidates_[1],
477       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
478   // RelayPort connection timeout is 3sec. TCP connection with RelayServer
479   // will be tried after 3 seconds.
480   EXPECT_EQ_WAIT(6U, candidates_.size(), 4000);
481   EXPECT_EQ(3U, ports_.size());
482   EXPECT_PRED5(CheckCandidate, candidates_[2],
483       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpIntAddr);
484   EXPECT_PRED5(CheckCandidate, candidates_[3],
485       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "tcp", kRelayTcpIntAddr);
486   EXPECT_PRED5(CheckCandidate, candidates_[4],
487       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "ssltcp",
488       kRelaySslTcpIntAddr);
489   EXPECT_PRED5(CheckCandidate, candidates_[5],
490       cricket::ICE_CANDIDATE_COMPONENT_RTP, "relay", "udp", kRelayUdpExtAddr);
491   // Stun Timeout is 9sec.
492   EXPECT_TRUE_WAIT(candidate_allocation_done_, 9000);
493 }
494
495 TEST_F(PortAllocatorTest, TestCandidatePriorityOfMultipleInterfaces) {
496   AddInterface(kClientAddr);
497   AddInterface(kClientAddr2);
498   // Allocating only host UDP ports. This is done purely for testing
499   // convenience.
500   allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_TCP |
501                         cricket::PORTALLOCATOR_DISABLE_STUN |
502                         cricket::PORTALLOCATOR_DISABLE_RELAY);
503   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
504   session_->StartGettingPorts();
505   EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
506   ASSERT_EQ(2U, candidates_.size());
507   EXPECT_EQ(2U, ports_.size());
508   // Candidates priorities should be different.
509   EXPECT_NE(candidates_[0].priority(), candidates_[1].priority());
510 }
511
512 // Test to verify ICE restart process.
513 TEST_F(PortAllocatorTest, TestGetAllPortsRestarts) {
514   AddInterface(kClientAddr);
515   EXPECT_TRUE(CreateSession(1));
516   session_->StartGettingPorts();
517   EXPECT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
518   EXPECT_EQ(4U, ports_.size());
519   EXPECT_TRUE(candidate_allocation_done_);
520   // TODO - Extend this to verify ICE restart.
521 }
522
523 TEST_F(PortAllocatorTest, TestBasicMuxFeatures) {
524   AddInterface(kClientAddr);
525   allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE);
526   // Session ID - session1.
527   talk_base::scoped_ptr<cricket::PortAllocatorSession> session1(
528       CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTP));
529   talk_base::scoped_ptr<cricket::PortAllocatorSession> session2(
530       CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTCP));
531   session1->StartGettingPorts();
532   session2->StartGettingPorts();
533   // Each session should receive two proxy ports of local and stun.
534   ASSERT_EQ_WAIT(14U, candidates_.size(), kDefaultAllocationTimeout);
535   EXPECT_EQ(8U, ports_.size());
536
537   talk_base::scoped_ptr<cricket::PortAllocatorSession> session3(
538       CreateSession("session1", cricket::ICE_CANDIDATE_COMPONENT_RTP));
539   session3->StartGettingPorts();
540   // Already allocated candidates and ports will be sent to the newly
541   // allocated proxy session.
542   ASSERT_EQ_WAIT(21U, candidates_.size(), kDefaultAllocationTimeout);
543   EXPECT_EQ(12U, ports_.size());
544 }
545
546 // This test verifies by changing ice_ufrag and/or ice_pwd
547 // will result in different set of candidates when BUNDLE is enabled.
548 // If BUNDLE is disabled, CreateSession will always allocate new
549 // set of candidates.
550 TEST_F(PortAllocatorTest, TestBundleIceRestart) {
551   AddInterface(kClientAddr);
552   allocator().set_flags(cricket::PORTALLOCATOR_ENABLE_BUNDLE);
553   // Session ID - session1.
554   talk_base::scoped_ptr<cricket::PortAllocatorSession> session1(
555       CreateSession("session1", kContentName,
556                     cricket::ICE_CANDIDATE_COMPONENT_RTP,
557                     kIceUfrag0, kIcePwd0));
558   session1->StartGettingPorts();
559   ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
560   EXPECT_EQ(4U, ports_.size());
561
562   // Allocate a different session with sid |session1| and different ice_ufrag.
563   talk_base::scoped_ptr<cricket::PortAllocatorSession> session2(
564       CreateSession("session1", kContentName,
565                     cricket::ICE_CANDIDATE_COMPONENT_RTP,
566                     "TestIceUfrag", kIcePwd0));
567   session2->StartGettingPorts();
568   ASSERT_EQ_WAIT(14U, candidates_.size(), kDefaultAllocationTimeout);
569   EXPECT_EQ(8U, ports_.size());
570   // Verifying the candidate address different from previously allocated
571   // address.
572   // Skipping verification of component id and candidate type.
573   EXPECT_NE(candidates_[0].address(), candidates_[7].address());
574   EXPECT_NE(candidates_[1].address(), candidates_[8].address());
575
576   // Allocating a different session with sid |session1| and
577   // different ice_pwd.
578   talk_base::scoped_ptr<cricket::PortAllocatorSession> session3(
579       CreateSession("session1", kContentName,
580                     cricket::ICE_CANDIDATE_COMPONENT_RTP,
581                     kIceUfrag0, "TestIcePwd"));
582   session3->StartGettingPorts();
583   ASSERT_EQ_WAIT(21U, candidates_.size(), kDefaultAllocationTimeout);
584   EXPECT_EQ(12U, ports_.size());
585   // Verifying the candidate address different from previously
586   // allocated address.
587   EXPECT_NE(candidates_[7].address(), candidates_[14].address());
588   EXPECT_NE(candidates_[8].address(), candidates_[15].address());
589
590   // Allocating a session with by changing both ice_ufrag and ice_pwd.
591   talk_base::scoped_ptr<cricket::PortAllocatorSession> session4(
592       CreateSession("session1", kContentName,
593                     cricket::ICE_CANDIDATE_COMPONENT_RTP,
594                     "TestIceUfrag", "TestIcePwd"));
595   session4->StartGettingPorts();
596   ASSERT_EQ_WAIT(28U, candidates_.size(), kDefaultAllocationTimeout);
597   EXPECT_EQ(16U, ports_.size());
598   // Verifying the candidate address different from previously
599   // allocated address.
600   EXPECT_NE(candidates_[14].address(), candidates_[21].address());
601   EXPECT_NE(candidates_[15].address(), candidates_[22].address());
602 }
603
604 // Test that when the PORTALLOCATOR_ENABLE_SHARED_UFRAG is enabled we got same
605 // ufrag and pwd for the collected candidates.
606 TEST_F(PortAllocatorTest, TestEnableSharedUfrag) {
607   allocator().set_flags(allocator().flags() |
608                         cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
609   AddInterface(kClientAddr);
610   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
611   session_->StartGettingPorts();
612   ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
613   EXPECT_PRED5(CheckCandidate, candidates_[0],
614       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
615   EXPECT_PRED5(CheckCandidate, candidates_[1],
616       cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
617   EXPECT_PRED5(CheckCandidate, candidates_[5],
618       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp", kClientAddr);
619   EXPECT_EQ(4U, ports_.size());
620   EXPECT_EQ(kIceUfrag0, candidates_[0].username());
621   EXPECT_EQ(kIceUfrag0, candidates_[1].username());
622   EXPECT_EQ(kIceUfrag0, candidates_[2].username());
623   EXPECT_EQ(kIcePwd0, candidates_[0].password());
624   EXPECT_EQ(kIcePwd0, candidates_[1].password());
625   EXPECT_TRUE(candidate_allocation_done_);
626 }
627
628 // Test that when the PORTALLOCATOR_ENABLE_SHARED_UFRAG isn't enabled we got
629 // different ufrag and pwd for the collected candidates.
630 TEST_F(PortAllocatorTest, TestDisableSharedUfrag) {
631   allocator().set_flags(allocator().flags() &
632                         ~cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
633   AddInterface(kClientAddr);
634   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
635   session_->StartGettingPorts();
636   ASSERT_EQ_WAIT(7U, candidates_.size(), kDefaultAllocationTimeout);
637   EXPECT_PRED5(CheckCandidate, candidates_[0],
638       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
639   EXPECT_PRED5(CheckCandidate, candidates_[1],
640       cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp", kClientAddr);
641   EXPECT_EQ(4U, ports_.size());
642   // Port should generate random ufrag and pwd.
643   EXPECT_NE(kIceUfrag0, candidates_[0].username());
644   EXPECT_NE(kIceUfrag0, candidates_[1].username());
645   EXPECT_NE(candidates_[0].username(), candidates_[1].username());
646   EXPECT_NE(kIcePwd0, candidates_[0].password());
647   EXPECT_NE(kIcePwd0, candidates_[1].password());
648   EXPECT_NE(candidates_[0].password(), candidates_[1].password());
649   EXPECT_TRUE(candidate_allocation_done_);
650 }
651
652 // Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
653 // is allocated for udp and stun. Also verify there is only one candidate
654 // (local) if stun candidate is same as local candidate, which will be the case
655 // in a public network like the below test.
656 TEST_F(PortAllocatorTest, TestEnableSharedSocketWithoutNat) {
657   AddInterface(kClientAddr);
658   allocator_->set_flags(allocator().flags() |
659                         cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
660                         cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
661   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
662   session_->StartGettingPorts();
663   ASSERT_EQ_WAIT(6U, candidates_.size(), kDefaultAllocationTimeout);
664   EXPECT_EQ(3U, ports_.size());
665   EXPECT_PRED5(CheckCandidate, candidates_[0],
666       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
667   EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
668 }
669
670 // Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port
671 // is allocated for udp and stun. In this test we should expect both stun and
672 // local candidates as client behind a nat.
673 TEST_F(PortAllocatorTest, TestEnableSharedSocketWithNat) {
674   AddInterface(kClientAddr);
675   talk_base::scoped_ptr<talk_base::NATServer> nat_server(
676       CreateNatServer(kNatAddr, talk_base::NAT_OPEN_CONE));
677   allocator_.reset(new cricket::BasicPortAllocator(
678       &network_manager_, &nat_socket_factory_, kStunAddr));
679   allocator_->set_step_delay(cricket::kMinimumStepDelay);
680   allocator_->set_flags(allocator().flags() |
681                         cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
682                         cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
683   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
684   session_->StartGettingPorts();
685   ASSERT_EQ_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout);
686   ASSERT_EQ(2U, ports_.size());
687   EXPECT_PRED5(CheckCandidate, candidates_[0],
688       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
689   EXPECT_PRED5(CheckCandidate, candidates_[1],
690       cricket::ICE_CANDIDATE_COMPONENT_RTP, "stun", "udp",
691       talk_base::SocketAddress(kNatAddr.ipaddr(), 0));
692   EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
693   EXPECT_EQ(3U, candidates_.size());
694 }
695
696 // This test verifies when PORTALLOCATOR_ENABLE_SHARED_SOCKET flag is enabled
697 // and fail to generate STUN candidate, local UDP candidate is generated
698 // properly.
699 TEST_F(PortAllocatorTest, TestEnableSharedSocketNoUdpAllowed) {
700   allocator().set_flags(allocator().flags() |
701                         cricket::PORTALLOCATOR_DISABLE_RELAY |
702                         cricket::PORTALLOCATOR_DISABLE_TCP |
703                         cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
704                         cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
705   fss_->AddRule(false, talk_base::FP_UDP, talk_base::FD_ANY, kClientAddr);
706   AddInterface(kClientAddr);
707   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
708   session_->StartGettingPorts();
709   ASSERT_EQ_WAIT(1U, ports_.size(), kDefaultAllocationTimeout);
710   EXPECT_EQ(1U, candidates_.size());
711   EXPECT_PRED5(CheckCandidate, candidates_[0],
712       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp", kClientAddr);
713   // STUN timeout is 9sec. We need to wait to get candidate done signal.
714   EXPECT_TRUE_WAIT(candidate_allocation_done_, 10000);
715   EXPECT_EQ(1U, candidates_.size());
716 }
717
718 // This test verifies allocator can use IPv6 addresses along with IPv4.
719 TEST_F(PortAllocatorTest, TestEnableIPv6Addresses) {
720   allocator().set_flags(allocator().flags() |
721                         cricket::PORTALLOCATOR_DISABLE_RELAY |
722                         cricket::PORTALLOCATOR_ENABLE_IPV6 |
723                         cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG |
724                         cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET);
725   AddInterface(kClientIPv6Addr);
726   AddInterface(kClientAddr);
727   allocator_->set_step_delay(cricket::kMinimumStepDelay);
728   EXPECT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP));
729   session_->StartGettingPorts();
730   ASSERT_EQ_WAIT(4U, ports_.size(), kDefaultAllocationTimeout);
731   EXPECT_EQ(4U, candidates_.size());
732   EXPECT_TRUE_WAIT(candidate_allocation_done_, kDefaultAllocationTimeout);
733   EXPECT_PRED5(CheckCandidate, candidates_[0],
734       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
735       kClientIPv6Addr);
736   EXPECT_PRED5(CheckCandidate, candidates_[1],
737       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "udp",
738       kClientAddr);
739   EXPECT_PRED5(CheckCandidate, candidates_[2],
740       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
741       kClientIPv6Addr);
742   EXPECT_PRED5(CheckCandidate, candidates_[3],
743       cricket::ICE_CANDIDATE_COMPONENT_RTP, "local", "tcp",
744       kClientAddr);
745   EXPECT_EQ(4U, candidates_.size());
746 }
747
748 // Test that the httpportallocator correctly maintains its lists of stun and
749 // relay servers, by never allowing an empty list.
750 TEST(HttpPortAllocatorTest, TestHttpPortAllocatorHostLists) {
751   talk_base::FakeNetworkManager network_manager;
752   cricket::HttpPortAllocator alloc(&network_manager, "unit test agent");
753   EXPECT_EQ(1U, alloc.relay_hosts().size());
754   EXPECT_EQ(1U, alloc.stun_hosts().size());
755
756   std::vector<std::string> relay_servers;
757   std::vector<talk_base::SocketAddress> stun_servers;
758
759   alloc.SetRelayHosts(relay_servers);
760   alloc.SetStunHosts(stun_servers);
761   EXPECT_EQ(1U, alloc.relay_hosts().size());
762   EXPECT_EQ(1U, alloc.stun_hosts().size());
763
764   relay_servers.push_back("1.unittest.corp.google.com");
765   relay_servers.push_back("2.unittest.corp.google.com");
766   stun_servers.push_back(
767       talk_base::SocketAddress("1.unittest.corp.google.com", 0));
768   stun_servers.push_back(
769       talk_base::SocketAddress("2.unittest.corp.google.com", 0));
770   alloc.SetRelayHosts(relay_servers);
771   alloc.SetStunHosts(stun_servers);
772   EXPECT_EQ(2U, alloc.relay_hosts().size());
773   EXPECT_EQ(2U, alloc.stun_hosts().size());
774 }
775
776 // Test that the HttpPortAllocator uses correct URL to create sessions.
777 TEST(HttpPortAllocatorTest, TestSessionRequestUrl) {
778   talk_base::FakeNetworkManager network_manager;
779   cricket::HttpPortAllocator alloc(&network_manager, "unit test agent");
780
781   // Disable PORTALLOCATOR_ENABLE_SHARED_UFRAG.
782   alloc.set_flags(alloc.flags() & ~cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
783   talk_base::scoped_ptr<cricket::HttpPortAllocatorSessionBase> session(
784       static_cast<cricket::HttpPortAllocatorSession*>(
785           alloc.CreateSessionInternal(
786               "test content", 0, kIceUfrag0, kIcePwd0)));
787   std::string url = session->GetSessionRequestUrl();
788   LOG(LS_INFO) << "url: " << url;
789   EXPECT_EQ(std::string(cricket::HttpPortAllocator::kCreateSessionURL), url);
790
791   // Enable PORTALLOCATOR_ENABLE_SHARED_UFRAG.
792   alloc.set_flags(alloc.flags() | cricket::PORTALLOCATOR_ENABLE_SHARED_UFRAG);
793   session.reset(static_cast<cricket::HttpPortAllocatorSession*>(
794       alloc.CreateSessionInternal("test content", 0, kIceUfrag0, kIcePwd0)));
795   url = session->GetSessionRequestUrl();
796   LOG(LS_INFO) << "url: " << url;
797   std::vector<std::string> parts;
798   talk_base::split(url, '?', &parts);
799   ASSERT_EQ(2U, parts.size());
800
801   std::vector<std::string> args_parts;
802   talk_base::split(parts[1], '&', &args_parts);
803
804   std::map<std::string, std::string> args;
805   for (std::vector<std::string>::iterator it = args_parts.begin();
806        it != args_parts.end(); ++it) {
807     std::vector<std::string> parts;
808     talk_base::split(*it, '=', &parts);
809     ASSERT_EQ(2U, parts.size());
810     args[talk_base::s_url_decode(parts[0])] = talk_base::s_url_decode(parts[1]);
811   }
812
813   EXPECT_EQ(kIceUfrag0, args["username"]);
814   EXPECT_EQ(kIcePwd0, args["password"]);
815 }