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