diff options
Diffstat (limited to 'third_party/libwebrtc/p2p/client')
6 files changed, 5249 insertions, 0 deletions
diff --git a/third_party/libwebrtc/p2p/client/basic_port_allocator.cc b/third_party/libwebrtc/p2p/client/basic_port_allocator.cc new file mode 100644 index 0000000000..e36f266f15 --- /dev/null +++ b/third_party/libwebrtc/p2p/client/basic_port_allocator.cc @@ -0,0 +1,1860 @@ +/* + * Copyright 2004 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "p2p/client/basic_port_allocator.h" + +#include <algorithm> +#include <functional> +#include <memory> +#include <set> +#include <string> +#include <utility> +#include <vector> + +#include "absl/algorithm/container.h" +#include "absl/memory/memory.h" +#include "absl/strings/string_view.h" +#include "api/task_queue/pending_task_safety_flag.h" +#include "api/transport/field_trial_based_config.h" +#include "api/units/time_delta.h" +#include "p2p/base/basic_packet_socket_factory.h" +#include "p2p/base/port.h" +#include "p2p/base/stun_port.h" +#include "p2p/base/tcp_port.h" +#include "p2p/base/turn_port.h" +#include "p2p/base/udp_port.h" +#include "rtc_base/checks.h" +#include "rtc_base/experiments/field_trial_parser.h" +#include "rtc_base/helpers.h" +#include "rtc_base/logging.h" +#include "rtc_base/network_constants.h" +#include "rtc_base/strings/string_builder.h" +#include "rtc_base/trace_event.h" +#include "system_wrappers/include/metrics.h" + +namespace cricket { +namespace { +using ::rtc::CreateRandomId; +using ::webrtc::SafeTask; +using ::webrtc::TimeDelta; + +const int PHASE_UDP = 0; +const int PHASE_RELAY = 1; +const int PHASE_TCP = 2; + +const int kNumPhases = 3; + +// Gets protocol priority: UDP > TCP > SSLTCP == TLS. +int GetProtocolPriority(cricket::ProtocolType protocol) { + switch (protocol) { + case cricket::PROTO_UDP: + return 2; + case cricket::PROTO_TCP: + return 1; + case cricket::PROTO_SSLTCP: + case cricket::PROTO_TLS: + return 0; + default: + RTC_DCHECK_NOTREACHED(); + return 0; + } +} +// Gets address family priority: IPv6 > IPv4 > Unspecified. +int GetAddressFamilyPriority(int ip_family) { + switch (ip_family) { + case AF_INET6: + return 2; + case AF_INET: + return 1; + default: + RTC_DCHECK_NOTREACHED(); + return 0; + } +} + +// Returns positive if a is better, negative if b is better, and 0 otherwise. +int ComparePort(const cricket::Port* a, const cricket::Port* b) { + int a_protocol = GetProtocolPriority(a->GetProtocol()); + int b_protocol = GetProtocolPriority(b->GetProtocol()); + int cmp_protocol = a_protocol - b_protocol; + if (cmp_protocol != 0) { + return cmp_protocol; + } + + int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family()); + int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family()); + return a_family - b_family; +} + +struct NetworkFilter { + using Predicate = std::function<bool(const rtc::Network*)>; + NetworkFilter(Predicate pred, absl::string_view description) + : predRemain( + [pred](const rtc::Network* network) { return !pred(network); }), + description(description) {} + Predicate predRemain; + const std::string description; +}; + +void FilterNetworks(std::vector<const rtc::Network*>* networks, + NetworkFilter filter) { + auto start_to_remove = + std::partition(networks->begin(), networks->end(), filter.predRemain); + if (start_to_remove == networks->end()) { + return; + } + RTC_LOG(LS_INFO) << "Filtered out " << filter.description << " networks:"; + for (auto it = start_to_remove; it != networks->end(); ++it) { + RTC_LOG(LS_INFO) << (*it)->ToString(); + } + networks->erase(start_to_remove, networks->end()); +} + +bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) { + // When binding to any address, before sending packets out, the getsockname + // returns all 0s, but after sending packets, it'll be the NIC used to + // send. All 0s is not a valid ICE candidate address and should be filtered + // out. + if (c.address().IsAnyIP()) { + return false; + } + + if (c.type() == RELAY_PORT_TYPE) { + return ((filter & CF_RELAY) != 0); + } else if (c.type() == STUN_PORT_TYPE) { + return ((filter & CF_REFLEXIVE) != 0); + } else if (c.type() == LOCAL_PORT_TYPE) { + if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) { + // We allow host candidates if the filter allows server-reflexive + // candidates and the candidate is a public IP. Because we don't generate + // server-reflexive candidates if they have the same IP as the host + // candidate (i.e. when the host candidate is a public IP), filtering to + // only server-reflexive candidates won't work right when the host + // candidates have public IPs. + return true; + } + + return ((filter & CF_HOST) != 0); + } + return false; +} + +std::string NetworksToString(const std::vector<const rtc::Network*>& networks) { + rtc::StringBuilder ost; + for (auto n : networks) { + ost << n->name() << " "; + } + return ost.Release(); +} + +bool IsDiversifyIpv6InterfacesEnabled( + const webrtc::FieldTrialsView* field_trials) { + // webrtc:14334: Improve IPv6 network resolution and candidate creation + if (field_trials && + field_trials->IsEnabled("WebRTC-IPv6NetworkResolutionFixes")) { + webrtc::FieldTrialParameter<bool> diversify_ipv6_interfaces( + "DiversifyIpv6Interfaces", false); + webrtc::ParseFieldTrial( + {&diversify_ipv6_interfaces}, + field_trials->Lookup("WebRTC-IPv6NetworkResolutionFixes")); + return diversify_ipv6_interfaces; + } + return false; +} + +} // namespace + +const uint32_t DISABLE_ALL_PHASES = + PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY; + +// BasicPortAllocator +BasicPortAllocator::BasicPortAllocator( + rtc::NetworkManager* network_manager, + rtc::PacketSocketFactory* socket_factory, + webrtc::TurnCustomizer* customizer, + RelayPortFactoryInterface* relay_port_factory, + const webrtc::FieldTrialsView* field_trials) + : field_trials_(field_trials), + network_manager_(network_manager), + socket_factory_(socket_factory) { + Init(relay_port_factory); + RTC_DCHECK(relay_port_factory_ != nullptr); + RTC_DCHECK(network_manager_ != nullptr); + RTC_CHECK(socket_factory_ != nullptr); + SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0, + webrtc::NO_PRUNE, customizer); +} + +BasicPortAllocator::BasicPortAllocator( + rtc::NetworkManager* network_manager, + std::unique_ptr<rtc::PacketSocketFactory> owned_socket_factory, + const webrtc::FieldTrialsView* field_trials) + : field_trials_(field_trials), + network_manager_(network_manager), + socket_factory_(std::move(owned_socket_factory)) { + Init(nullptr); + RTC_DCHECK(relay_port_factory_ != nullptr); + RTC_DCHECK(network_manager_ != nullptr); + RTC_CHECK(socket_factory_ != nullptr); +} + +BasicPortAllocator::BasicPortAllocator( + rtc::NetworkManager* network_manager, + std::unique_ptr<rtc::PacketSocketFactory> owned_socket_factory, + const ServerAddresses& stun_servers, + const webrtc::FieldTrialsView* field_trials) + : field_trials_(field_trials), + network_manager_(network_manager), + socket_factory_(std::move(owned_socket_factory)) { + Init(nullptr); + RTC_DCHECK(relay_port_factory_ != nullptr); + RTC_DCHECK(network_manager_ != nullptr); + RTC_CHECK(socket_factory_ != nullptr); + SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, + webrtc::NO_PRUNE, nullptr); +} + +BasicPortAllocator::BasicPortAllocator( + rtc::NetworkManager* network_manager, + rtc::PacketSocketFactory* socket_factory, + const ServerAddresses& stun_servers, + const webrtc::FieldTrialsView* field_trials) + : field_trials_(field_trials), + network_manager_(network_manager), + socket_factory_(socket_factory) { + Init(nullptr); + RTC_DCHECK(relay_port_factory_ != nullptr); + RTC_DCHECK(network_manager_ != nullptr); + RTC_CHECK(socket_factory_ != nullptr); + SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, + webrtc::NO_PRUNE, nullptr); +} + +void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session, + IceRegatheringReason reason) { + // If the session has not been taken by an active channel, do not report the + // metric. + for (auto& allocator_session : pooled_sessions()) { + if (allocator_session.get() == session) { + return; + } + } + + RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason", + static_cast<int>(reason), + static_cast<int>(IceRegatheringReason::MAX_VALUE)); +} + +BasicPortAllocator::~BasicPortAllocator() { + CheckRunOnValidThreadIfInitialized(); + // Our created port allocator sessions depend on us, so destroy our remaining + // pooled sessions before anything else. + DiscardCandidatePool(); +} + +void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) { + // TODO(phoglund): implement support for other types than loopback. + // See https://code.google.com/p/webrtc/issues/detail?id=4288. + // Then remove set_network_ignore_list from NetworkManager. + CheckRunOnValidThreadIfInitialized(); + network_ignore_mask_ = network_ignore_mask; +} + +int BasicPortAllocator::GetNetworkIgnoreMask() const { + CheckRunOnValidThreadIfInitialized(); + int mask = network_ignore_mask_; + switch (vpn_preference_) { + case webrtc::VpnPreference::kOnlyUseVpn: + mask |= ~static_cast<int>(rtc::ADAPTER_TYPE_VPN); + break; + case webrtc::VpnPreference::kNeverUseVpn: + mask |= static_cast<int>(rtc::ADAPTER_TYPE_VPN); + break; + default: + break; + } + return mask; +} + +PortAllocatorSession* BasicPortAllocator::CreateSessionInternal( + absl::string_view content_name, + int component, + absl::string_view ice_ufrag, + absl::string_view ice_pwd) { + CheckRunOnValidThreadAndInitialized(); + PortAllocatorSession* session = new BasicPortAllocatorSession( + this, std::string(content_name), component, std::string(ice_ufrag), + std::string(ice_pwd)); + session->SignalIceRegathering.connect(this, + &BasicPortAllocator::OnIceRegathering); + return session; +} + +void BasicPortAllocator::AddTurnServerForTesting( + const RelayServerConfig& turn_server) { + CheckRunOnValidThreadAndInitialized(); + std::vector<RelayServerConfig> new_turn_servers = turn_servers(); + new_turn_servers.push_back(turn_server); + SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(), + turn_port_prune_policy(), turn_customizer()); +} + +void BasicPortAllocator::Init(RelayPortFactoryInterface* relay_port_factory) { + if (relay_port_factory != nullptr) { + relay_port_factory_ = relay_port_factory; + } else { + default_relay_port_factory_.reset(new TurnPortFactory()); + relay_port_factory_ = default_relay_port_factory_.get(); + } +} + +// BasicPortAllocatorSession +BasicPortAllocatorSession::BasicPortAllocatorSession( + BasicPortAllocator* allocator, + absl::string_view content_name, + int component, + absl::string_view ice_ufrag, + absl::string_view ice_pwd) + : PortAllocatorSession(content_name, + component, + ice_ufrag, + ice_pwd, + allocator->flags()), + allocator_(allocator), + network_thread_(rtc::Thread::Current()), + socket_factory_(allocator->socket_factory()), + allocation_started_(false), + network_manager_started_(false), + allocation_sequences_created_(false), + turn_port_prune_policy_(allocator->turn_port_prune_policy()) { + TRACE_EVENT0("webrtc", + "BasicPortAllocatorSession::BasicPortAllocatorSession"); + allocator_->network_manager()->SignalNetworksChanged.connect( + this, &BasicPortAllocatorSession::OnNetworksChanged); + allocator_->network_manager()->StartUpdating(); +} + +BasicPortAllocatorSession::~BasicPortAllocatorSession() { + TRACE_EVENT0("webrtc", + "BasicPortAllocatorSession::~BasicPortAllocatorSession"); + RTC_DCHECK_RUN_ON(network_thread_); + allocator_->network_manager()->StopUpdating(); + + for (uint32_t i = 0; i < sequences_.size(); ++i) { + // AllocationSequence should clear it's map entry for turn ports before + // ports are destroyed. + sequences_[i]->Clear(); + } + + std::vector<PortData>::iterator it; + for (it = ports_.begin(); it != ports_.end(); it++) + delete it->port(); + + configs_.clear(); + + for (uint32_t i = 0; i < sequences_.size(); ++i) + delete sequences_[i]; +} + +BasicPortAllocator* BasicPortAllocatorSession::allocator() { + RTC_DCHECK_RUN_ON(network_thread_); + return allocator_; +} + +void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) { + RTC_DCHECK_RUN_ON(network_thread_); + if (filter == candidate_filter_) { + return; + } + uint32_t prev_filter = candidate_filter_; + candidate_filter_ = filter; + for (PortData& port_data : ports_) { + if (port_data.error() || port_data.pruned()) { + continue; + } + PortData::State cur_state = port_data.state(); + bool found_signalable_candidate = false; + bool found_pairable_candidate = false; + cricket::Port* port = port_data.port(); + for (const auto& c : port->Candidates()) { + if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) && + IsAllowedByCandidateFilter(c, filter)) { + // This candidate was not signaled because of not matching the previous + // filter (see OnCandidateReady below). Let the Port to fire the signal + // again. + // + // Note that + // 1) we would need the Port to enter the state of in-progress of + // gathering to have candidates signaled; + // + // 2) firing the signal would also let the session set the port ready + // if needed, so that we could form candidate pairs with candidates + // from this port; + // + // * See again OnCandidateReady below for 1) and 2). + // + // 3) we only try to resurface candidates if we have not stopped + // getting ports, which is always true for the continual gathering. + if (!found_signalable_candidate) { + found_signalable_candidate = true; + port_data.set_state(PortData::STATE_INPROGRESS); + } + port->SignalCandidateReady(port, c); + } + + if (CandidatePairable(c, port)) { + found_pairable_candidate = true; + } + } + // Restore the previous state. + port_data.set_state(cur_state); + // Setting a filter may cause a ready port to become non-ready + // if it no longer has any pairable candidates. + // + // Note that we only set for the negative case here, since a port would be + // set to have pairable candidates when it signals a ready candidate, which + // requires the port is still in the progress of gathering/surfacing + // candidates, and would be done in the firing of the signal above. + if (!found_pairable_candidate) { + port_data.set_has_pairable_candidate(false); + } + } +} + +void BasicPortAllocatorSession::StartGettingPorts() { + RTC_DCHECK_RUN_ON(network_thread_); + state_ = SessionState::GATHERING; + + network_thread_->PostTask( + SafeTask(network_safety_.flag(), [this] { GetPortConfigurations(); })); + + RTC_LOG(LS_INFO) << "Start getting ports with turn_port_prune_policy " + << turn_port_prune_policy_; +} + +void BasicPortAllocatorSession::StopGettingPorts() { + RTC_DCHECK_RUN_ON(network_thread_); + ClearGettingPorts(); + // Note: this must be called after ClearGettingPorts because both may set the + // session state and we should set the state to STOPPED. + state_ = SessionState::STOPPED; +} + +void BasicPortAllocatorSession::ClearGettingPorts() { + RTC_DCHECK_RUN_ON(network_thread_); + ++allocation_epoch_; + for (uint32_t i = 0; i < sequences_.size(); ++i) { + sequences_[i]->Stop(); + } + network_thread_->PostTask( + SafeTask(network_safety_.flag(), [this] { OnConfigStop(); })); + state_ = SessionState::CLEARED; +} + +bool BasicPortAllocatorSession::IsGettingPorts() { + RTC_DCHECK_RUN_ON(network_thread_); + return state_ == SessionState::GATHERING; +} + +bool BasicPortAllocatorSession::IsCleared() const { + RTC_DCHECK_RUN_ON(network_thread_); + return state_ == SessionState::CLEARED; +} + +bool BasicPortAllocatorSession::IsStopped() const { + RTC_DCHECK_RUN_ON(network_thread_); + return state_ == SessionState::STOPPED; +} + +std::vector<const rtc::Network*> +BasicPortAllocatorSession::GetFailedNetworks() { + RTC_DCHECK_RUN_ON(network_thread_); + + std::vector<const rtc::Network*> networks = GetNetworks(); + // A network interface may have both IPv4 and IPv6 networks. Only if + // neither of the networks has any connections, the network interface + // is considered failed and need to be regathered on. + std::set<std::string> networks_with_connection; + for (const PortData& data : ports_) { + Port* port = data.port(); + if (!port->connections().empty()) { + networks_with_connection.insert(port->Network()->name()); + } + } + + networks.erase( + std::remove_if(networks.begin(), networks.end(), + [networks_with_connection](const rtc::Network* network) { + // If a network does not have any connection, it is + // considered failed. + return networks_with_connection.find(network->name()) != + networks_with_connection.end(); + }), + networks.end()); + return networks; +} + +void BasicPortAllocatorSession::RegatherOnFailedNetworks() { + RTC_DCHECK_RUN_ON(network_thread_); + + // Find the list of networks that have no connection. + std::vector<const rtc::Network*> failed_networks = GetFailedNetworks(); + if (failed_networks.empty()) { + return; + } + + RTC_LOG(LS_INFO) << "Regather candidates on failed networks"; + + // Mark a sequence as "network failed" if its network is in the list of failed + // networks, so that it won't be considered as equivalent when the session + // regathers ports and candidates. + for (AllocationSequence* sequence : sequences_) { + if (!sequence->network_failed() && + absl::c_linear_search(failed_networks, sequence->network())) { + sequence->set_network_failed(); + } + } + + bool disable_equivalent_phases = true; + Regather(failed_networks, disable_equivalent_phases, + IceRegatheringReason::NETWORK_FAILURE); +} + +void BasicPortAllocatorSession::Regather( + const std::vector<const rtc::Network*>& networks, + bool disable_equivalent_phases, + IceRegatheringReason reason) { + RTC_DCHECK_RUN_ON(network_thread_); + // Remove ports from being used locally and send signaling to remove + // the candidates on the remote side. + std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks); + if (!ports_to_prune.empty()) { + RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports"; + PrunePortsAndRemoveCandidates(ports_to_prune); + } + + if (allocation_started_ && network_manager_started_ && !IsStopped()) { + SignalIceRegathering(this, reason); + + DoAllocate(disable_equivalent_phases); + } +} + +void BasicPortAllocatorSession::GetCandidateStatsFromReadyPorts( + CandidateStatsList* candidate_stats_list) const { + auto ports = ReadyPorts(); + for (auto* port : ports) { + auto candidates = port->Candidates(); + for (const auto& candidate : candidates) { + absl::optional<StunStats> stun_stats; + port->GetStunStats(&stun_stats); + CandidateStats candidate_stats(allocator_->SanitizeCandidate(candidate), + std::move(stun_stats)); + candidate_stats_list->push_back(std::move(candidate_stats)); + } + } +} + +void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts( + const absl::optional<int>& stun_keepalive_interval) { + RTC_DCHECK_RUN_ON(network_thread_); + auto ports = ReadyPorts(); + for (PortInterface* port : ports) { + // The port type and protocol can be used to identify different subclasses + // of Port in the current implementation. Note that a TCPPort has the type + // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP. + if (port->Type() == STUN_PORT_TYPE || + (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) { + static_cast<UDPPort*>(port)->set_stun_keepalive_delay( + stun_keepalive_interval); + } + } +} + +std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const { + RTC_DCHECK_RUN_ON(network_thread_); + std::vector<PortInterface*> ret; + for (const PortData& data : ports_) { + if (data.ready()) { + ret.push_back(data.port()); + } + } + return ret; +} + +std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const { + RTC_DCHECK_RUN_ON(network_thread_); + std::vector<Candidate> candidates; + for (const PortData& data : ports_) { + if (!data.ready()) { + continue; + } + GetCandidatesFromPort(data, &candidates); + } + return candidates; +} + +void BasicPortAllocatorSession::GetCandidatesFromPort( + const PortData& data, + std::vector<Candidate>* candidates) const { + RTC_DCHECK_RUN_ON(network_thread_); + RTC_CHECK(candidates != nullptr); + for (const Candidate& candidate : data.port()->Candidates()) { + if (!CheckCandidateFilter(candidate)) { + continue; + } + candidates->push_back(allocator_->SanitizeCandidate(candidate)); + } +} + +bool BasicPortAllocator::MdnsObfuscationEnabled() const { + return network_manager()->GetMdnsResponder() != nullptr; +} + +bool BasicPortAllocatorSession::CandidatesAllocationDone() const { + RTC_DCHECK_RUN_ON(network_thread_); + // Done only if all required AllocationSequence objects + // are created. + if (!allocation_sequences_created_) { + return false; + } + + // Check that all port allocation sequences are complete (not running). + if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) { + return sequence->state() == AllocationSequence::kRunning; + })) { + return false; + } + + // If all allocated ports are no longer gathering, session must have got all + // expected candidates. Session will trigger candidates allocation complete + // signal. + return absl::c_none_of( + ports_, [](const PortData& port) { return port.inprogress(); }); +} + +void BasicPortAllocatorSession::UpdateIceParametersInternal() { + RTC_DCHECK_RUN_ON(network_thread_); + for (PortData& port : ports_) { + port.port()->set_content_name(content_name()); + port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd()); + } +} + +void BasicPortAllocatorSession::GetPortConfigurations() { + RTC_DCHECK_RUN_ON(network_thread_); + + auto config = std::make_unique<PortConfiguration>( + allocator_->stun_servers(), username(), password(), + allocator()->field_trials()); + + for (const RelayServerConfig& turn_server : allocator_->turn_servers()) { + config->AddRelay(turn_server); + } + ConfigReady(std::move(config)); +} + +void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) { + RTC_DCHECK_RUN_ON(network_thread_); + ConfigReady(absl::WrapUnique(config)); +} + +void BasicPortAllocatorSession::ConfigReady( + std::unique_ptr<PortConfiguration> config) { + RTC_DCHECK_RUN_ON(network_thread_); + network_thread_->PostTask(SafeTask( + network_safety_.flag(), [this, config = std::move(config)]() mutable { + OnConfigReady(std::move(config)); + })); +} + +// Adds a configuration to the list. +void BasicPortAllocatorSession::OnConfigReady( + std::unique_ptr<PortConfiguration> config) { + RTC_DCHECK_RUN_ON(network_thread_); + if (config) + configs_.push_back(std::move(config)); + + AllocatePorts(); +} + +void BasicPortAllocatorSession::OnConfigStop() { + RTC_DCHECK_RUN_ON(network_thread_); + + // If any of the allocated ports have not completed the candidates allocation, + // mark those as error. Since session doesn't need any new candidates + // at this stage of the allocation, it's safe to discard any new candidates. + bool send_signal = false; + for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end(); + ++it) { + if (it->inprogress()) { + // Updating port state to error, which didn't finish allocating candidates + // yet. + it->set_state(PortData::STATE_ERROR); + send_signal = true; + } + } + + // Did we stop any running sequences? + for (std::vector<AllocationSequence*>::iterator it = sequences_.begin(); + it != sequences_.end() && !send_signal; ++it) { + if ((*it)->state() == AllocationSequence::kStopped) { + send_signal = true; + } + } + + // If we stopped anything that was running, send a done signal now. + if (send_signal) { + MaybeSignalCandidatesAllocationDone(); + } +} + +void BasicPortAllocatorSession::AllocatePorts() { + RTC_DCHECK_RUN_ON(network_thread_); + network_thread_->PostTask(SafeTask( + network_safety_.flag(), [this, allocation_epoch = allocation_epoch_] { + OnAllocate(allocation_epoch); + })); +} + +void BasicPortAllocatorSession::OnAllocate(int allocation_epoch) { + RTC_DCHECK_RUN_ON(network_thread_); + if (allocation_epoch != allocation_epoch_) + return; + + if (network_manager_started_ && !IsStopped()) { + bool disable_equivalent_phases = true; + DoAllocate(disable_equivalent_phases); + } + + allocation_started_ = true; +} + +std::vector<const rtc::Network*> BasicPortAllocatorSession::GetNetworks() { + RTC_DCHECK_RUN_ON(network_thread_); + std::vector<const rtc::Network*> networks; + rtc::NetworkManager* network_manager = allocator_->network_manager(); + RTC_DCHECK(network_manager != nullptr); + // If the network permission state is BLOCKED, we just act as if the flag has + // been passed in. + if (network_manager->enumeration_permission() == + rtc::NetworkManager::ENUMERATION_BLOCKED) { + set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION); + } + // If the adapter enumeration is disabled, we'll just bind to any address + // instead of specific NIC. This is to ensure the same routing for http + // traffic by OS is also used here to avoid any local or public IP leakage + // during stun process. + if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) { + networks = network_manager->GetAnyAddressNetworks(); + } else { + networks = network_manager->GetNetworks(); + // If network enumeration fails, use the ANY address as a fallback, so we + // can at least try gathering candidates using the default route chosen by + // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is + // set, we'll use ANY address candidates either way. + if (networks.empty() || + (flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS)) { + std::vector<const rtc::Network*> any_address_networks = + network_manager->GetAnyAddressNetworks(); + networks.insert(networks.end(), any_address_networks.begin(), + any_address_networks.end()); + } + } + // Filter out link-local networks if needed. + if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) { + NetworkFilter link_local_filter( + [](const rtc::Network* network) { + return IPIsLinkLocal(network->prefix()); + }, + "link-local"); + FilterNetworks(&networks, link_local_filter); + } + // Do some more filtering, depending on the network ignore mask and "disable + // costly networks" flag. + NetworkFilter ignored_filter( + [this](const rtc::Network* network) { + return allocator_->GetNetworkIgnoreMask() & network->type(); + }, + "ignored"); + FilterNetworks(&networks, ignored_filter); + if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) { + uint16_t lowest_cost = rtc::kNetworkCostMax; + for (const rtc::Network* network : networks) { + // Don't determine the lowest cost from a link-local network. + // On iOS, a device connected to the computer will get a link-local + // network for communicating with the computer, however this network can't + // be used to connect to a peer outside the network. + if (rtc::IPIsLinkLocal(network->GetBestIP())) { + continue; + } + lowest_cost = std::min<uint16_t>( + lowest_cost, network->GetCost(*allocator()->field_trials())); + } + NetworkFilter costly_filter( + [lowest_cost, this](const rtc::Network* network) { + return network->GetCost(*allocator()->field_trials()) > + lowest_cost + rtc::kNetworkCostLow; + }, + "costly"); + FilterNetworks(&networks, costly_filter); + } + + // Lastly, if we have a limit for the number of IPv6 network interfaces (by + // default, it's 5), remove networks to ensure that limit is satisfied. + // + // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6 + // networks, we could try to choose a set that's "most likely to work". It's + // hard to define what that means though; it's not just "lowest cost". + // Alternatively, we could just focus on making our ICE pinging logic smarter + // such that this filtering isn't necessary in the first place. + const webrtc::FieldTrialsView* field_trials = allocator_->field_trials(); + if (IsDiversifyIpv6InterfacesEnabled(field_trials)) { + std::vector<const rtc::Network*> ipv6_networks; + for (auto it = networks.begin(); it != networks.end();) { + if ((*it)->prefix().family() == AF_INET6) { + ipv6_networks.push_back(*it); + it = networks.erase(it); + continue; + } + ++it; + } + ipv6_networks = + SelectIPv6Networks(ipv6_networks, allocator_->max_ipv6_networks()); + networks.insert(networks.end(), ipv6_networks.begin(), ipv6_networks.end()); + } else { + int ipv6_networks = 0; + for (auto it = networks.begin(); it != networks.end();) { + if ((*it)->prefix().family() == AF_INET6) { + if (ipv6_networks >= allocator_->max_ipv6_networks()) { + it = networks.erase(it); + continue; + } else { + ++ipv6_networks; + } + } + ++it; + } + } + return networks; +} + +std::vector<const rtc::Network*> BasicPortAllocatorSession::SelectIPv6Networks( + std::vector<const rtc::Network*>& all_ipv6_networks, + int max_ipv6_networks) { + if (static_cast<int>(all_ipv6_networks.size()) <= max_ipv6_networks) { + return all_ipv6_networks; + } + // Adapter types are placed in priority order. Cellular type is an alias of + // cellular, 2G..5G types. + std::vector<rtc::AdapterType> adapter_types = { + rtc::ADAPTER_TYPE_ETHERNET, rtc::ADAPTER_TYPE_LOOPBACK, + rtc::ADAPTER_TYPE_WIFI, rtc::ADAPTER_TYPE_CELLULAR, + rtc::ADAPTER_TYPE_VPN, rtc::ADAPTER_TYPE_UNKNOWN, + rtc::ADAPTER_TYPE_ANY}; + int adapter_types_cnt = adapter_types.size(); + std::vector<const rtc::Network*> selected_networks; + int adapter_types_pos = 0; + + while (static_cast<int>(selected_networks.size()) < max_ipv6_networks && + adapter_types_pos < adapter_types_cnt * max_ipv6_networks) { + int network_pos = 0; + while (network_pos < static_cast<int>(all_ipv6_networks.size())) { + if (adapter_types[adapter_types_pos % adapter_types_cnt] == + all_ipv6_networks[network_pos]->type() || + (adapter_types[adapter_types_pos % adapter_types_cnt] == + rtc::ADAPTER_TYPE_CELLULAR && + all_ipv6_networks[network_pos]->IsCellular())) { + selected_networks.push_back(all_ipv6_networks[network_pos]); + all_ipv6_networks.erase(all_ipv6_networks.begin() + network_pos); + break; + } + network_pos++; + } + adapter_types_pos++; + } + + return selected_networks; +} + +// For each network, see if we have a sequence that covers it already. If not, +// create a new sequence to create the appropriate ports. +void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) { + RTC_DCHECK_RUN_ON(network_thread_); + bool done_signal_needed = false; + std::vector<const rtc::Network*> networks = GetNetworks(); + if (networks.empty()) { + RTC_LOG(LS_WARNING) + << "Machine has no networks; no ports will be allocated"; + done_signal_needed = true; + } else { + RTC_LOG(LS_INFO) << "Allocate ports on " << NetworksToString(networks); + PortConfiguration* config = + configs_.empty() ? nullptr : configs_.back().get(); + for (uint32_t i = 0; i < networks.size(); ++i) { + uint32_t sequence_flags = flags(); + if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) { + // If all the ports are disabled we should just fire the allocation + // done event and return. + done_signal_needed = true; + break; + } + + if (!config || config->relays.empty()) { + // No relay ports specified in this config. + sequence_flags |= PORTALLOCATOR_DISABLE_RELAY; + } + + if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) && + networks[i]->GetBestIP().family() == AF_INET6) { + // Skip IPv6 networks unless the flag's been set. + continue; + } + + if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) && + networks[i]->GetBestIP().family() == AF_INET6 && + networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) { + // Skip IPv6 Wi-Fi networks unless the flag's been set. + continue; + } + + if (disable_equivalent) { + // Disable phases that would only create ports equivalent to + // ones that we have already made. + DisableEquivalentPhases(networks[i], config, &sequence_flags); + + if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) { + // New AllocationSequence would have nothing to do, so don't make it. + continue; + } + } + + AllocationSequence* sequence = + new AllocationSequence(this, networks[i], config, sequence_flags, + [this, safety_flag = network_safety_.flag()] { + if (safety_flag->alive()) + OnPortAllocationComplete(); + }); + sequence->Init(); + sequence->Start(); + sequences_.push_back(sequence); + done_signal_needed = true; + } + } + if (done_signal_needed) { + network_thread_->PostTask(SafeTask(network_safety_.flag(), [this] { + OnAllocationSequenceObjectsCreated(); + })); + } +} + +void BasicPortAllocatorSession::OnNetworksChanged() { + RTC_DCHECK_RUN_ON(network_thread_); + std::vector<const rtc::Network*> networks = GetNetworks(); + std::vector<const rtc::Network*> failed_networks; + for (AllocationSequence* sequence : sequences_) { + // Mark the sequence as "network failed" if its network is not in + // `networks`. + if (!sequence->network_failed() && + !absl::c_linear_search(networks, sequence->network())) { + sequence->OnNetworkFailed(); + failed_networks.push_back(sequence->network()); + } + } + std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks); + if (!ports_to_prune.empty()) { + RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() + << " ports because their networks were gone"; + PrunePortsAndRemoveCandidates(ports_to_prune); + } + + if (allocation_started_ && !IsStopped()) { + if (network_manager_started_) { + // If the network manager has started, it must be regathering. + SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE); + } + bool disable_equivalent_phases = true; + DoAllocate(disable_equivalent_phases); + } + + if (!network_manager_started_) { + RTC_LOG(LS_INFO) << "Network manager has started"; + network_manager_started_ = true; + } +} + +void BasicPortAllocatorSession::DisableEquivalentPhases( + const rtc::Network* network, + PortConfiguration* config, + uint32_t* flags) { + RTC_DCHECK_RUN_ON(network_thread_); + for (uint32_t i = 0; i < sequences_.size() && + (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES; + ++i) { + sequences_[i]->DisableEquivalentPhases(network, config, flags); + } +} + +void BasicPortAllocatorSession::AddAllocatedPort(Port* port, + AllocationSequence* seq) { + RTC_DCHECK_RUN_ON(network_thread_); + if (!port) + return; + + RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name(); + port->set_content_name(content_name()); + port->set_component(component()); + port->set_generation(generation()); + if (allocator_->proxy().type != rtc::PROXY_NONE) + port->set_proxy(allocator_->user_agent(), allocator_->proxy()); + port->set_send_retransmit_count_attribute( + (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0); + + PortData data(port, seq); + ports_.push_back(data); + + port->SignalCandidateReady.connect( + this, &BasicPortAllocatorSession::OnCandidateReady); + port->SignalCandidateError.connect( + this, &BasicPortAllocatorSession::OnCandidateError); + port->SignalPortComplete.connect(this, + &BasicPortAllocatorSession::OnPortComplete); + port->SubscribePortDestroyed( + [this](PortInterface* port) { OnPortDestroyed(port); }); + + port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError); + RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator"; + + port->PrepareAddress(); +} + +void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() { + RTC_DCHECK_RUN_ON(network_thread_); + allocation_sequences_created_ = true; + // Send candidate allocation complete signal if we have no sequences. + MaybeSignalCandidatesAllocationDone(); +} + +void BasicPortAllocatorSession::OnCandidateReady(Port* port, + const Candidate& c) { + RTC_DCHECK_RUN_ON(network_thread_); + PortData* data = FindPort(port); + RTC_DCHECK(data != NULL); + RTC_LOG(LS_INFO) << port->ToString() + << ": Gathered candidate: " << c.ToSensitiveString(); + // Discarding any candidate signal if port allocation status is + // already done with gathering. + if (!data->inprogress()) { + RTC_LOG(LS_WARNING) + << "Discarding candidate because port is already done gathering."; + return; + } + + // Mark that the port has a pairable candidate, either because we have a + // usable candidate from the port, or simply because the port is bound to the + // any address and therefore has no host candidate. This will trigger the port + // to start creating candidate pairs (connections) and issue connectivity + // checks. If port has already been marked as having a pairable candidate, + // do nothing here. + // Note: We should check whether any candidates may become ready after this + // because there we will check whether the candidate is generated by the ready + // ports, which may include this port. + bool pruned = false; + if (CandidatePairable(c, port) && !data->has_pairable_candidate()) { + data->set_has_pairable_candidate(true); + + if (port->Type() == RELAY_PORT_TYPE) { + if (turn_port_prune_policy_ == webrtc::KEEP_FIRST_READY) { + pruned = PruneNewlyPairableTurnPort(data); + } else if (turn_port_prune_policy_ == webrtc::PRUNE_BASED_ON_PRIORITY) { + pruned = PruneTurnPorts(port); + } + } + + // If the current port is not pruned yet, SignalPortReady. + if (!data->pruned()) { + RTC_LOG(LS_INFO) << port->ToString() << ": Port ready."; + SignalPortReady(this, port); + port->KeepAliveUntilPruned(); + } + } + + if (data->ready() && CheckCandidateFilter(c)) { + std::vector<Candidate> candidates; + candidates.push_back(allocator_->SanitizeCandidate(c)); + SignalCandidatesReady(this, candidates); + } else { + RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter."; + } + + // If we have pruned any port, maybe need to signal port allocation done. + if (pruned) { + MaybeSignalCandidatesAllocationDone(); + } +} + +void BasicPortAllocatorSession::OnCandidateError( + Port* port, + const IceCandidateErrorEvent& event) { + RTC_DCHECK_RUN_ON(network_thread_); + RTC_DCHECK(FindPort(port)); + if (event.address.empty()) { + candidate_error_events_.push_back(event); + } else { + SignalCandidateError(this, event); + } +} + +Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork( + absl::string_view network_name) const { + RTC_DCHECK_RUN_ON(network_thread_); + Port* best_turn_port = nullptr; + for (const PortData& data : ports_) { + if (data.port()->Network()->name() == network_name && + data.port()->Type() == RELAY_PORT_TYPE && data.ready() && + (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) { + best_turn_port = data.port(); + } + } + return best_turn_port; +} + +bool BasicPortAllocatorSession::PruneNewlyPairableTurnPort( + PortData* newly_pairable_port_data) { + RTC_DCHECK_RUN_ON(network_thread_); + RTC_DCHECK(newly_pairable_port_data->port()->Type() == RELAY_PORT_TYPE); + // If an existing turn port is ready on the same network, prune the newly + // pairable port. + const std::string& network_name = + newly_pairable_port_data->port()->Network()->name(); + + for (PortData& data : ports_) { + if (data.port()->Network()->name() == network_name && + data.port()->Type() == RELAY_PORT_TYPE && data.ready() && + &data != newly_pairable_port_data) { + RTC_LOG(LS_INFO) << "Port pruned: " + << newly_pairable_port_data->port()->ToString(); + newly_pairable_port_data->Prune(); + return true; + } + } + return false; +} + +bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) { + RTC_DCHECK_RUN_ON(network_thread_); + // Note: We determine the same network based only on their network names. So + // if an IPv4 address and an IPv6 address have the same network name, they + // are considered the same network here. + const std::string& network_name = newly_pairable_turn_port->Network()->name(); + Port* best_turn_port = GetBestTurnPortForNetwork(network_name); + // `port` is already in the list of ports, so the best port cannot be nullptr. + RTC_CHECK(best_turn_port != nullptr); + + bool pruned = false; + std::vector<PortData*> ports_to_prune; + for (PortData& data : ports_) { + if (data.port()->Network()->name() == network_name && + data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() && + ComparePort(data.port(), best_turn_port) < 0) { + pruned = true; + if (data.port() != newly_pairable_turn_port) { + // These ports will be pruned in PrunePortsAndRemoveCandidates. + ports_to_prune.push_back(&data); + } else { + data.Prune(); + } + } + } + + if (!ports_to_prune.empty()) { + RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() + << " low-priority TURN ports"; + PrunePortsAndRemoveCandidates(ports_to_prune); + } + return pruned; +} + +void BasicPortAllocatorSession::PruneAllPorts() { + RTC_DCHECK_RUN_ON(network_thread_); + for (PortData& data : ports_) { + data.Prune(); + } +} + +void BasicPortAllocatorSession::OnPortComplete(Port* port) { + RTC_DCHECK_RUN_ON(network_thread_); + RTC_LOG(LS_INFO) << port->ToString() + << ": Port completed gathering candidates."; + PortData* data = FindPort(port); + RTC_DCHECK(data != NULL); + + // Ignore any late signals. + if (!data->inprogress()) { + return; + } + + // Moving to COMPLETE state. + data->set_state(PortData::STATE_COMPLETE); + // Send candidate allocation complete signal if this was the last port. + MaybeSignalCandidatesAllocationDone(); +} + +void BasicPortAllocatorSession::OnPortError(Port* port) { + RTC_DCHECK_RUN_ON(network_thread_); + RTC_LOG(LS_INFO) << port->ToString() + << ": Port encountered error while gathering candidates."; + PortData* data = FindPort(port); + RTC_DCHECK(data != NULL); + // We might have already given up on this port and stopped it. + if (!data->inprogress()) { + return; + } + + // SignalAddressError is currently sent from StunPort/TurnPort. + // But this signal itself is generic. + data->set_state(PortData::STATE_ERROR); + // Send candidate allocation complete signal if this was the last port. + MaybeSignalCandidatesAllocationDone(); +} + +bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const { + RTC_DCHECK_RUN_ON(network_thread_); + + return IsAllowedByCandidateFilter(c, candidate_filter_); +} + +bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c, + const Port* port) const { + RTC_DCHECK_RUN_ON(network_thread_); + + bool candidate_signalable = CheckCandidateFilter(c); + + // When device enumeration is disabled (to prevent non-default IP addresses + // from leaking), we ping from some local candidates even though we don't + // signal them. However, if host candidates are also disabled (for example, to + // prevent even default IP addresses from leaking), we still don't want to + // ping from them, even if device enumeration is disabled. Thus, we check for + // both device enumeration and host candidates being disabled. + bool network_enumeration_disabled = c.address().IsAnyIP(); + bool can_ping_from_candidate = + (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME); + bool host_candidates_disabled = !(candidate_filter_ & CF_HOST); + + return candidate_signalable || + (network_enumeration_disabled && can_ping_from_candidate && + !host_candidates_disabled); +} + +void BasicPortAllocatorSession::OnPortAllocationComplete() { + RTC_DCHECK_RUN_ON(network_thread_); + // Send candidate allocation complete signal if all ports are done. + MaybeSignalCandidatesAllocationDone(); +} + +void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() { + RTC_DCHECK_RUN_ON(network_thread_); + if (CandidatesAllocationDone()) { + if (pooled()) { + RTC_LOG(LS_INFO) << "All candidates gathered for pooled session."; + } else { + RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name() + << ":" << component() << ":" << generation(); + } + for (const auto& event : candidate_error_events_) { + SignalCandidateError(this, event); + } + candidate_error_events_.clear(); + SignalCandidatesAllocationDone(this); + } +} + +void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) { + RTC_DCHECK_RUN_ON(network_thread_); + for (std::vector<PortData>::iterator iter = ports_.begin(); + iter != ports_.end(); ++iter) { + if (port == iter->port()) { + ports_.erase(iter); + RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator (" + << static_cast<int>(ports_.size()) << " remaining)"; + return; + } + } + RTC_DCHECK_NOTREACHED(); +} + +BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort( + Port* port) { + RTC_DCHECK_RUN_ON(network_thread_); + for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end(); + ++it) { + if (it->port() == port) { + return &*it; + } + } + return NULL; +} + +std::vector<BasicPortAllocatorSession::PortData*> +BasicPortAllocatorSession::GetUnprunedPorts( + const std::vector<const rtc::Network*>& networks) { + RTC_DCHECK_RUN_ON(network_thread_); + std::vector<PortData*> unpruned_ports; + for (PortData& port : ports_) { + if (!port.pruned() && + absl::c_linear_search(networks, port.sequence()->network())) { + unpruned_ports.push_back(&port); + } + } + return unpruned_ports; +} + +void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates( + const std::vector<PortData*>& port_data_list) { + RTC_DCHECK_RUN_ON(network_thread_); + std::vector<PortInterface*> pruned_ports; + std::vector<Candidate> removed_candidates; + for (PortData* data : port_data_list) { + // Prune the port so that it may be destroyed. + data->Prune(); + pruned_ports.push_back(data->port()); + if (data->has_pairable_candidate()) { + GetCandidatesFromPort(*data, &removed_candidates); + // Mark the port as having no pairable candidates so that its candidates + // won't be removed multiple times. + data->set_has_pairable_candidate(false); + } + } + if (!pruned_ports.empty()) { + SignalPortsPruned(this, pruned_ports); + } + if (!removed_candidates.empty()) { + RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size() + << " candidates"; + SignalCandidatesRemoved(this, removed_candidates); + } +} + +void BasicPortAllocator::SetVpnList( + const std::vector<rtc::NetworkMask>& vpn_list) { + network_manager_->set_vpn_list(vpn_list); +} + +// AllocationSequence + +AllocationSequence::AllocationSequence( + BasicPortAllocatorSession* session, + const rtc::Network* network, + PortConfiguration* config, + uint32_t flags, + std::function<void()> port_allocation_complete_callback) + : session_(session), + network_(network), + config_(config), + state_(kInit), + flags_(flags), + udp_socket_(), + udp_port_(NULL), + phase_(0), + port_allocation_complete_callback_( + std::move(port_allocation_complete_callback)) {} + +void AllocationSequence::Init() { + if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) { + udp_socket_.reset(session_->socket_factory()->CreateUdpSocket( + rtc::SocketAddress(network_->GetBestIP(), 0), + session_->allocator()->min_port(), session_->allocator()->max_port())); + if (udp_socket_) { + udp_socket_->SignalReadPacket.connect(this, + &AllocationSequence::OnReadPacket); + } + // Continuing if `udp_socket_` is NULL, as local TCP and RelayPort using TCP + // are next available options to setup a communication channel. + } +} + +void AllocationSequence::Clear() { + TRACE_EVENT0("webrtc", "AllocationSequence::Clear"); + udp_port_ = NULL; + relay_ports_.clear(); +} + +void AllocationSequence::OnNetworkFailed() { + RTC_DCHECK(!network_failed_); + network_failed_ = true; + // Stop the allocation sequence if its network failed. + Stop(); +} + +void AllocationSequence::DisableEquivalentPhases(const rtc::Network* network, + PortConfiguration* config, + uint32_t* flags) { + if (network_failed_) { + // If the network of this allocation sequence has ever become failed, + // it won't be equivalent to the new network. + return; + } + + if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) { + // Different network setup; nothing is equivalent. + return; + } + + // Else turn off the stuff that we've already got covered. + + // Every config implicitly specifies local, so turn that off right away if we + // already have a port of the corresponding type. Look for a port that + // matches this AllocationSequence's network, is the right protocol, and + // hasn't encountered an error. + // TODO(deadbeef): This doesn't take into account that there may be another + // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet. + // This can happen if, say, there's a network change event right before an + // application-triggered ICE restart. Hopefully this problem will just go + // away if we get rid of the gathering "phases" though, which is planned. + // + // + // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host + // candidate (and srflx candidate if Port::SharedSocket()), and we do not want + // to disable the gathering of these candidates just becaue of an existing + // Port over PROTO_UDP, namely a TurnPort over UDP. + if (absl::c_any_of(session_->ports_, + [this](const BasicPortAllocatorSession::PortData& p) { + return !p.pruned() && p.port()->Network() == network_ && + p.port()->GetProtocol() == PROTO_UDP && + p.port()->Type() == LOCAL_PORT_TYPE && !p.error(); + })) { + *flags |= PORTALLOCATOR_DISABLE_UDP; + } + // Similarly we need to check both the protocol used by an existing Port and + // its type. + if (absl::c_any_of(session_->ports_, + [this](const BasicPortAllocatorSession::PortData& p) { + return !p.pruned() && p.port()->Network() == network_ && + p.port()->GetProtocol() == PROTO_TCP && + p.port()->Type() == LOCAL_PORT_TYPE && !p.error(); + })) { + *flags |= PORTALLOCATOR_DISABLE_TCP; + } + + if (config_ && config) { + // We need to regather srflx candidates if either of the following + // conditions occurs: + // 1. The STUN servers are different from the previous gathering. + // 2. We will regather host candidates, hence possibly inducing new NAT + // bindings. + if (config_->StunServers() == config->StunServers() && + (*flags & PORTALLOCATOR_DISABLE_UDP)) { + // Already got this STUN servers covered. + *flags |= PORTALLOCATOR_DISABLE_STUN; + } + if (!config_->relays.empty()) { + // Already got relays covered. + // NOTE: This will even skip a _different_ set of relay servers if we + // were to be given one, but that never happens in our codebase. Should + // probably get rid of the list in PortConfiguration and just keep a + // single relay server in each one. + *flags |= PORTALLOCATOR_DISABLE_RELAY; + } + } +} + +void AllocationSequence::Start() { + state_ = kRunning; + + session_->network_thread()->PostTask( + SafeTask(safety_.flag(), [this, epoch = epoch_] { Process(epoch); })); + // Take a snapshot of the best IP, so that when DisableEquivalentPhases is + // called next time, we enable all phases if the best IP has since changed. + previous_best_ip_ = network_->GetBestIP(); +} + +void AllocationSequence::Stop() { + // If the port is completed, don't set it to stopped. + if (state_ == kRunning) { + state_ = kStopped; + // Cause further Process calls in the previous epoch to be ignored. + ++epoch_; + } +} + +void AllocationSequence::Process(int epoch) { + RTC_DCHECK(rtc::Thread::Current() == session_->network_thread()); + const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"}; + + if (epoch != epoch_) + return; + + // Perform all of the phases in the current step. + RTC_LOG(LS_INFO) << network_->ToString() + << ": Allocation Phase=" << PHASE_NAMES[phase_]; + + switch (phase_) { + case PHASE_UDP: + CreateUDPPorts(); + CreateStunPorts(); + break; + + case PHASE_RELAY: + CreateRelayPorts(); + break; + + case PHASE_TCP: + CreateTCPPorts(); + state_ = kCompleted; + break; + + default: + RTC_DCHECK_NOTREACHED(); + } + + if (state() == kRunning) { + ++phase_; + session_->network_thread()->PostDelayedTask( + SafeTask(safety_.flag(), [this, epoch = epoch_] { Process(epoch); }), + TimeDelta::Millis(session_->allocator()->step_delay())); + } else { + // No allocation steps needed further if all phases in AllocationSequence + // are completed. Cause further Process calls in the previous epoch to be + // ignored. + ++epoch_; + port_allocation_complete_callback_(); + } +} + +void AllocationSequence::CreateUDPPorts() { + if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) { + RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping."; + return; + } + + // TODO(mallinath) - Remove UDPPort creating socket after shared socket + // is enabled completely. + std::unique_ptr<UDPPort> port; + bool emit_local_candidate_for_anyaddress = + !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE); + if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) { + port = UDPPort::Create( + session_->network_thread(), session_->socket_factory(), network_, + udp_socket_.get(), session_->username(), session_->password(), + emit_local_candidate_for_anyaddress, + session_->allocator()->stun_candidate_keepalive_interval(), + session_->allocator()->field_trials()); + } else { + port = UDPPort::Create( + session_->network_thread(), session_->socket_factory(), network_, + session_->allocator()->min_port(), session_->allocator()->max_port(), + session_->username(), session_->password(), + emit_local_candidate_for_anyaddress, + session_->allocator()->stun_candidate_keepalive_interval(), + session_->allocator()->field_trials()); + } + + if (port) { + port->SetIceTiebreaker(session_->ice_tiebreaker()); + // If shared socket is enabled, STUN candidate will be allocated by the + // UDPPort. + if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) { + udp_port_ = port.get(); + port->SubscribePortDestroyed( + [this](PortInterface* port) { OnPortDestroyed(port); }); + + // If STUN is not disabled, setting stun server address to port. + if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) { + if (config_ && !config_->StunServers().empty()) { + RTC_LOG(LS_INFO) + << "AllocationSequence: UDPPort will be handling the " + "STUN candidate generation."; + port->set_server_addresses(config_->StunServers()); + } + } + } + + session_->AddAllocatedPort(port.release(), this); + } +} + +void AllocationSequence::CreateTCPPorts() { + if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) { + RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping."; + return; + } + + std::unique_ptr<Port> port = TCPPort::Create( + session_->network_thread(), session_->socket_factory(), network_, + session_->allocator()->min_port(), session_->allocator()->max_port(), + session_->username(), session_->password(), + session_->allocator()->allow_tcp_listen(), + session_->allocator()->field_trials()); + if (port) { + port->SetIceTiebreaker(session_->ice_tiebreaker()); + session_->AddAllocatedPort(port.release(), this); + // Since TCPPort is not created using shared socket, `port` will not be + // added to the dequeue. + } +} + +void AllocationSequence::CreateStunPorts() { + if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) { + RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping."; + return; + } + + if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) { + return; + } + + if (!(config_ && !config_->StunServers().empty())) { + RTC_LOG(LS_WARNING) + << "AllocationSequence: No STUN server configured, skipping."; + return; + } + + std::unique_ptr<StunPort> port = StunPort::Create( + session_->network_thread(), session_->socket_factory(), network_, + session_->allocator()->min_port(), session_->allocator()->max_port(), + session_->username(), session_->password(), config_->StunServers(), + session_->allocator()->stun_candidate_keepalive_interval(), + session_->allocator()->field_trials()); + if (port) { + port->SetIceTiebreaker(session_->ice_tiebreaker()); + session_->AddAllocatedPort(port.release(), this); + // Since StunPort is not created using shared socket, `port` will not be + // added to the dequeue. + } +} + +void AllocationSequence::CreateRelayPorts() { + if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) { + RTC_LOG(LS_VERBOSE) + << "AllocationSequence: Relay ports disabled, skipping."; + return; + } + + // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we + // ought to have a relay list for them here. + RTC_DCHECK(config_); + RTC_DCHECK(!config_->relays.empty()); + if (!(config_ && !config_->relays.empty())) { + RTC_LOG(LS_WARNING) + << "AllocationSequence: No relay server configured, skipping."; + return; + } + + // Relative priority of candidates from this TURN server in relation + // to the candidates from other servers. Required because ICE priorities + // need to be unique. + int relative_priority = config_->relays.size(); + for (RelayServerConfig& relay : config_->relays) { + CreateTurnPort(relay, relative_priority--); + } +} + +void AllocationSequence::CreateTurnPort(const RelayServerConfig& config, + int relative_priority) { + PortList::const_iterator relay_port; + for (relay_port = config.ports.begin(); relay_port != config.ports.end(); + ++relay_port) { + // Skip UDP connections to relay servers if it's disallowed. + if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) && + relay_port->proto == PROTO_UDP) { + continue; + } + + // Do not create a port if the server address family is known and does + // not match the local IP address family. + int server_ip_family = relay_port->address.ipaddr().family(); + int local_ip_family = network_->GetBestIP().family(); + if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) { + RTC_LOG(LS_INFO) + << "Server and local address families are not compatible. " + "Server address: " + << relay_port->address.ipaddr().ToSensitiveString() + << " Local address: " << network_->GetBestIP().ToSensitiveString(); + continue; + } + + CreateRelayPortArgs args; + args.network_thread = session_->network_thread(); + args.socket_factory = session_->socket_factory(); + args.network = network_; + args.username = session_->username(); + args.password = session_->password(); + args.server_address = &(*relay_port); + args.config = &config; + args.turn_customizer = session_->allocator()->turn_customizer(); + args.field_trials = session_->allocator()->field_trials(); + args.relative_priority = relative_priority; + + std::unique_ptr<cricket::Port> port; + // Shared socket mode must be enabled only for UDP based ports. Hence + // don't pass shared socket for ports which will create TCP sockets. + // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled + // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537 + if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && + relay_port->proto == PROTO_UDP && udp_socket_) { + port = session_->allocator()->relay_port_factory()->Create( + args, udp_socket_.get()); + + if (!port) { + RTC_LOG(LS_WARNING) << "Failed to create relay port with " + << args.server_address->address.ToSensitiveString(); + continue; + } + + relay_ports_.push_back(port.get()); + // Listen to the port destroyed signal, to allow AllocationSequence to + // remove the entry from it's map. + port->SubscribePortDestroyed( + [this](PortInterface* port) { OnPortDestroyed(port); }); + + } else { + port = session_->allocator()->relay_port_factory()->Create( + args, session_->allocator()->min_port(), + session_->allocator()->max_port()); + + if (!port) { + RTC_LOG(LS_WARNING) << "Failed to create relay port with " + << args.server_address->address.ToSensitiveString(); + continue; + } + } + RTC_DCHECK(port != NULL); + port->SetIceTiebreaker(session_->ice_tiebreaker()); + session_->AddAllocatedPort(port.release(), this); + } +} + +void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket, + const char* data, + size_t size, + const rtc::SocketAddress& remote_addr, + const int64_t& packet_time_us) { + RTC_DCHECK(socket == udp_socket_.get()); + + bool turn_port_found = false; + + // Try to find the TurnPort that matches the remote address. Note that the + // message could be a STUN binding response if the TURN server is also used as + // a STUN server. We don't want to parse every message here to check if it is + // a STUN binding response, so we pass the message to TurnPort regardless of + // the message type. The TurnPort will just ignore the message since it will + // not find any request by transaction ID. + for (auto* port : relay_ports_) { + if (port->CanHandleIncomingPacketsFrom(remote_addr)) { + if (port->HandleIncomingPacket(socket, data, size, remote_addr, + packet_time_us)) { + return; + } + turn_port_found = true; + } + } + + if (udp_port_) { + const ServerAddresses& stun_servers = udp_port_->server_addresses(); + + // Pass the packet to the UdpPort if there is no matching TurnPort, or if + // the TURN server is also a STUN server. + if (!turn_port_found || + stun_servers.find(remote_addr) != stun_servers.end()) { + RTC_DCHECK(udp_port_->SharedSocket()); + udp_port_->HandleIncomingPacket(socket, data, size, remote_addr, + packet_time_us); + } + } +} + +void AllocationSequence::OnPortDestroyed(PortInterface* port) { + if (udp_port_ == port) { + udp_port_ = NULL; + return; + } + + auto it = absl::c_find(relay_ports_, port); + if (it != relay_ports_.end()) { + relay_ports_.erase(it); + } else { + RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port."; + RTC_DCHECK_NOTREACHED(); + } +} + +PortConfiguration::PortConfiguration( + const ServerAddresses& stun_servers, + absl::string_view username, + absl::string_view password, + const webrtc::FieldTrialsView* field_trials) + : stun_servers(stun_servers), username(username), password(password) { + if (!stun_servers.empty()) + stun_address = *(stun_servers.begin()); + // Note that this won't change once the config is initialized. + if (field_trials) { + use_turn_server_as_stun_server_disabled = + field_trials->IsDisabled("WebRTC-UseTurnServerAsStunServer"); + } +} + +ServerAddresses PortConfiguration::StunServers() { + if (!stun_address.IsNil() && + stun_servers.find(stun_address) == stun_servers.end()) { + stun_servers.insert(stun_address); + } + + if (!stun_servers.empty() && use_turn_server_as_stun_server_disabled) { + return stun_servers; + } + + // Every UDP TURN server should also be used as a STUN server if + // use_turn_server_as_stun_server is not disabled or the stun servers are + // empty. + ServerAddresses turn_servers = GetRelayServerAddresses(PROTO_UDP); + for (const rtc::SocketAddress& turn_server : turn_servers) { + if (stun_servers.find(turn_server) == stun_servers.end()) { + stun_servers.insert(turn_server); + } + } + return stun_servers; +} + +void PortConfiguration::AddRelay(const RelayServerConfig& config) { + relays.push_back(config); +} + +bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay, + ProtocolType type) const { + PortList::const_iterator relay_port; + for (relay_port = relay.ports.begin(); relay_port != relay.ports.end(); + ++relay_port) { + if (relay_port->proto == type) + return true; + } + return false; +} + +bool PortConfiguration::SupportsProtocol(ProtocolType type) const { + for (size_t i = 0; i < relays.size(); ++i) { + if (SupportsProtocol(relays[i], type)) + return true; + } + return false; +} + +ServerAddresses PortConfiguration::GetRelayServerAddresses( + ProtocolType type) const { + ServerAddresses servers; + for (size_t i = 0; i < relays.size(); ++i) { + if (SupportsProtocol(relays[i], type)) { + servers.insert(relays[i].ports.front().address); + } + } + return servers; +} + +} // namespace cricket diff --git a/third_party/libwebrtc/p2p/client/basic_port_allocator.h b/third_party/libwebrtc/p2p/client/basic_port_allocator.h new file mode 100644 index 0000000000..38c3835ee8 --- /dev/null +++ b/third_party/libwebrtc/p2p/client/basic_port_allocator.h @@ -0,0 +1,433 @@ +/* + * Copyright 2004 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#ifndef P2P_CLIENT_BASIC_PORT_ALLOCATOR_H_ +#define P2P_CLIENT_BASIC_PORT_ALLOCATOR_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "absl/strings/string_view.h" +#include "api/field_trials_view.h" +#include "api/task_queue/pending_task_safety_flag.h" +#include "api/turn_customizer.h" +#include "p2p/base/port_allocator.h" +#include "p2p/client/relay_port_factory_interface.h" +#include "p2p/client/turn_port_factory.h" +#include "rtc_base/checks.h" +#include "rtc_base/memory/always_valid_pointer.h" +#include "rtc_base/network.h" +#include "rtc_base/system/rtc_export.h" +#include "rtc_base/thread.h" +#include "rtc_base/thread_annotations.h" + +namespace cricket { + +class RTC_EXPORT BasicPortAllocator : public PortAllocator { + public: + // The NetworkManager is a mandatory argument. The other arguments are + // optional. All pointers are owned by caller and must have a life time + // that exceeds that of BasicPortAllocator. + BasicPortAllocator(rtc::NetworkManager* network_manager, + rtc::PacketSocketFactory* socket_factory, + webrtc::TurnCustomizer* customizer = nullptr, + RelayPortFactoryInterface* relay_port_factory = nullptr, + const webrtc::FieldTrialsView* field_trials = nullptr); + BasicPortAllocator( + rtc::NetworkManager* network_manager, + std::unique_ptr<rtc::PacketSocketFactory> owned_socket_factory, + const webrtc::FieldTrialsView* field_trials = nullptr); + BasicPortAllocator( + rtc::NetworkManager* network_manager, + std::unique_ptr<rtc::PacketSocketFactory> owned_socket_factory, + const ServerAddresses& stun_servers, + const webrtc::FieldTrialsView* field_trials = nullptr); + BasicPortAllocator(rtc::NetworkManager* network_manager, + rtc::PacketSocketFactory* socket_factory, + const ServerAddresses& stun_servers, + const webrtc::FieldTrialsView* field_trials = nullptr); + ~BasicPortAllocator() override; + + // Set to kDefaultNetworkIgnoreMask by default. + void SetNetworkIgnoreMask(int network_ignore_mask) override; + int GetNetworkIgnoreMask() const; + + rtc::NetworkManager* network_manager() const { + CheckRunOnValidThreadIfInitialized(); + return network_manager_; + } + + // If socket_factory() is set to NULL each PortAllocatorSession + // creates its own socket factory. + rtc::PacketSocketFactory* socket_factory() { + CheckRunOnValidThreadIfInitialized(); + return socket_factory_.get(); + } + + PortAllocatorSession* CreateSessionInternal( + absl::string_view content_name, + int component, + absl::string_view ice_ufrag, + absl::string_view ice_pwd) override; + + // Convenience method that adds a TURN server to the configuration. + void AddTurnServerForTesting(const RelayServerConfig& turn_server); + + RelayPortFactoryInterface* relay_port_factory() { + CheckRunOnValidThreadIfInitialized(); + return relay_port_factory_; + } + + void SetVpnList(const std::vector<rtc::NetworkMask>& vpn_list) override; + + const webrtc::FieldTrialsView* field_trials() const { + return field_trials_.get(); + } + + private: + void OnIceRegathering(PortAllocatorSession* session, + IceRegatheringReason reason); + + // This function makes sure that relay_port_factory_ is set properly. + void Init(RelayPortFactoryInterface* relay_port_factory); + + bool MdnsObfuscationEnabled() const override; + + webrtc::AlwaysValidPointer<const webrtc::FieldTrialsView, + webrtc::FieldTrialBasedConfig> + field_trials_; + rtc::NetworkManager* network_manager_; + const webrtc::AlwaysValidPointerNoDefault<rtc::PacketSocketFactory> + socket_factory_; + int network_ignore_mask_ = rtc::kDefaultNetworkIgnoreMask; + + // This is the factory being used. + RelayPortFactoryInterface* relay_port_factory_; + + // This instance is created if caller does pass a factory. + std::unique_ptr<RelayPortFactoryInterface> default_relay_port_factory_; +}; + +struct PortConfiguration; +class AllocationSequence; + +enum class SessionState { + GATHERING, // Actively allocating ports and gathering candidates. + CLEARED, // Current allocation process has been stopped but may start + // new ones. + STOPPED // This session has completely stopped, no new allocation + // process will be started. +}; + +// This class is thread-compatible and assumes it's created, operated upon and +// destroyed on the network thread. +class RTC_EXPORT BasicPortAllocatorSession : public PortAllocatorSession { + public: + BasicPortAllocatorSession(BasicPortAllocator* allocator, + absl::string_view content_name, + int component, + absl::string_view ice_ufrag, + absl::string_view ice_pwd); + ~BasicPortAllocatorSession() override; + + virtual BasicPortAllocator* allocator(); + rtc::Thread* network_thread() { return network_thread_; } + rtc::PacketSocketFactory* socket_factory() { return socket_factory_; } + + // If the new filter allows new types of candidates compared to the previous + // filter, gathered candidates that were discarded because of not matching the + // previous filter will be signaled if they match the new one. + // + // We do not perform any regathering since the port allocator flags decide + // the type of candidates to gather and the candidate filter only controls the + // signaling of candidates. As a result, with the candidate filter changed + // alone, all newly allowed candidates for signaling should already be + // gathered by the respective cricket::Port. + void SetCandidateFilter(uint32_t filter) override; + void StartGettingPorts() override; + void StopGettingPorts() override; + void ClearGettingPorts() override; + bool IsGettingPorts() override; + bool IsCleared() const override; + bool IsStopped() const override; + // These will all be cricket::Ports. + std::vector<PortInterface*> ReadyPorts() const override; + std::vector<Candidate> ReadyCandidates() const override; + bool CandidatesAllocationDone() const override; + void RegatherOnFailedNetworks() override; + void GetCandidateStatsFromReadyPorts( + CandidateStatsList* candidate_stats_list) const override; + void SetStunKeepaliveIntervalForReadyPorts( + const absl::optional<int>& stun_keepalive_interval) override; + void PruneAllPorts() override; + static std::vector<const rtc::Network*> SelectIPv6Networks( + std::vector<const rtc::Network*>& all_ipv6_networks, + int max_ipv6_networks); + + protected: + void UpdateIceParametersInternal() override; + + // Starts the process of getting the port configurations. + virtual void GetPortConfigurations(); + + // Adds a port configuration that is now ready. Once we have one for each + // network (or a timeout occurs), we will start allocating ports. + void ConfigReady(std::unique_ptr<PortConfiguration> config); + // TODO(bugs.webrtc.org/12840) Remove once unused in downstream projects. + ABSL_DEPRECATED( + "Use ConfigReady(std::unique_ptr<PortConfiguration>) instead!") + void ConfigReady(PortConfiguration* config); + + private: + class PortData { + public: + enum State { + STATE_INPROGRESS, // Still gathering candidates. + STATE_COMPLETE, // All candidates allocated and ready for process. + STATE_ERROR, // Error in gathering candidates. + STATE_PRUNED // Pruned by higher priority ports on the same network + // interface. Only TURN ports may be pruned. + }; + + PortData() {} + PortData(Port* port, AllocationSequence* seq) + : port_(port), sequence_(seq) {} + + Port* port() const { return port_; } + AllocationSequence* sequence() const { return sequence_; } + bool has_pairable_candidate() const { return has_pairable_candidate_; } + State state() const { return state_; } + bool complete() const { return state_ == STATE_COMPLETE; } + bool error() const { return state_ == STATE_ERROR; } + bool pruned() const { return state_ == STATE_PRUNED; } + bool inprogress() const { return state_ == STATE_INPROGRESS; } + // Returns true if this port is ready to be used. + bool ready() const { + return has_pairable_candidate_ && state_ != STATE_ERROR && + state_ != STATE_PRUNED; + } + // Sets the state to "PRUNED" and prunes the Port. + void Prune() { + state_ = STATE_PRUNED; + if (port()) { + port()->Prune(); + } + } + void set_has_pairable_candidate(bool has_pairable_candidate) { + if (has_pairable_candidate) { + RTC_DCHECK(state_ == STATE_INPROGRESS); + } + has_pairable_candidate_ = has_pairable_candidate; + } + void set_state(State state) { + RTC_DCHECK(state != STATE_ERROR || state_ == STATE_INPROGRESS); + state_ = state; + } + + private: + Port* port_ = nullptr; + AllocationSequence* sequence_ = nullptr; + bool has_pairable_candidate_ = false; + State state_ = STATE_INPROGRESS; + }; + + void OnConfigReady(std::unique_ptr<PortConfiguration> config); + void OnConfigStop(); + void AllocatePorts(); + void OnAllocate(int allocation_epoch); + void DoAllocate(bool disable_equivalent_phases); + void OnNetworksChanged(); + void OnAllocationSequenceObjectsCreated(); + void DisableEquivalentPhases(const rtc::Network* network, + PortConfiguration* config, + uint32_t* flags); + void AddAllocatedPort(Port* port, AllocationSequence* seq); + void OnCandidateReady(Port* port, const Candidate& c); + void OnCandidateError(Port* port, const IceCandidateErrorEvent& event); + void OnPortComplete(Port* port); + void OnPortError(Port* port); + void OnProtocolEnabled(AllocationSequence* seq, ProtocolType proto); + void OnPortDestroyed(PortInterface* port); + void MaybeSignalCandidatesAllocationDone(); + void OnPortAllocationComplete(); + PortData* FindPort(Port* port); + std::vector<const rtc::Network*> GetNetworks(); + std::vector<const rtc::Network*> GetFailedNetworks(); + void Regather(const std::vector<const rtc::Network*>& networks, + bool disable_equivalent_phases, + IceRegatheringReason reason); + + bool CheckCandidateFilter(const Candidate& c) const; + bool CandidatePairable(const Candidate& c, const Port* port) const; + + std::vector<PortData*> GetUnprunedPorts( + const std::vector<const rtc::Network*>& networks); + // Prunes ports and signal the remote side to remove the candidates that + // were previously signaled from these ports. + void PrunePortsAndRemoveCandidates( + const std::vector<PortData*>& port_data_list); + // Gets filtered and sanitized candidates generated from a port and + // append to `candidates`. + void GetCandidatesFromPort(const PortData& data, + std::vector<Candidate>* candidates) const; + Port* GetBestTurnPortForNetwork(absl::string_view network_name) const; + // Returns true if at least one TURN port is pruned. + bool PruneTurnPorts(Port* newly_pairable_turn_port); + bool PruneNewlyPairableTurnPort(PortData* newly_pairable_turn_port); + + BasicPortAllocator* allocator_; + rtc::Thread* network_thread_; + rtc::PacketSocketFactory* socket_factory_; + bool allocation_started_; + bool network_manager_started_; + bool allocation_sequences_created_; + std::vector<std::unique_ptr<PortConfiguration>> configs_; + std::vector<AllocationSequence*> sequences_; + std::vector<PortData> ports_; + std::vector<IceCandidateErrorEvent> candidate_error_events_; + uint32_t candidate_filter_ = CF_ALL; + // Policy on how to prune turn ports, taken from the port allocator. + webrtc::PortPrunePolicy turn_port_prune_policy_; + SessionState state_ = SessionState::CLEARED; + int allocation_epoch_ RTC_GUARDED_BY(network_thread_) = 0; + webrtc::ScopedTaskSafety network_safety_; + + friend class AllocationSequence; +}; + +// Records configuration information useful in creating ports. +// TODO(deadbeef): Rename "relay" to "turn_server" in this struct. +struct RTC_EXPORT PortConfiguration { + // TODO(jiayl): remove `stun_address` when Chrome is updated. + rtc::SocketAddress stun_address; + ServerAddresses stun_servers; + std::string username; + std::string password; + bool use_turn_server_as_stun_server_disabled = false; + + typedef std::vector<RelayServerConfig> RelayList; + RelayList relays; + + PortConfiguration(const ServerAddresses& stun_servers, + absl::string_view username, + absl::string_view password, + const webrtc::FieldTrialsView* field_trials = nullptr); + + // Returns addresses of both the explicitly configured STUN servers, + // and TURN servers that should be used as STUN servers. + ServerAddresses StunServers(); + + // Adds another relay server, with the given ports and modifier, to the list. + void AddRelay(const RelayServerConfig& config); + + // Determines whether the given relay server supports the given protocol. + bool SupportsProtocol(const RelayServerConfig& relay, + ProtocolType type) const; + bool SupportsProtocol(ProtocolType type) const; + // Helper method returns the server addresses for the matching RelayType and + // Protocol type. + ServerAddresses GetRelayServerAddresses(ProtocolType type) const; +}; + +class UDPPort; +class TurnPort; + +// Performs the allocation of ports, in a sequenced (timed) manner, for a given +// network and IP address. +// This class is thread-compatible. +class AllocationSequence : public sigslot::has_slots<> { + public: + enum State { + kInit, // Initial state. + kRunning, // Started allocating ports. + kStopped, // Stopped from running. + kCompleted, // All ports are allocated. + + // kInit --> kRunning --> {kCompleted|kStopped} + }; + // `port_allocation_complete_callback` is called when AllocationSequence is + // done with allocating ports. This signal is useful when port allocation + // fails which doesn't result in any candidates. Using this signal + // BasicPortAllocatorSession can send its candidate discovery conclusion + // signal. Without this signal, BasicPortAllocatorSession doesn't have any + // event to trigger signal. This can also be achieved by starting a timer in + // BPAS, but this is less deterministic. + AllocationSequence(BasicPortAllocatorSession* session, + const rtc::Network* network, + PortConfiguration* config, + uint32_t flags, + std::function<void()> port_allocation_complete_callback); + void Init(); + void Clear(); + void OnNetworkFailed(); + + State state() const { return state_; } + const rtc::Network* network() const { return network_; } + + bool network_failed() const { return network_failed_; } + void set_network_failed() { network_failed_ = true; } + + // Disables the phases for a new sequence that this one already covers for an + // equivalent network setup. + void DisableEquivalentPhases(const rtc::Network* network, + PortConfiguration* config, + uint32_t* flags); + + // Starts and stops the sequence. When started, it will continue allocating + // new ports on its own timed schedule. + void Start(); + void Stop(); + + private: + void CreateTurnPort(const RelayServerConfig& config, int relative_priority); + + typedef std::vector<ProtocolType> ProtocolList; + + void Process(int epoch); + bool IsFlagSet(uint32_t flag) { return ((flags_ & flag) != 0); } + void CreateUDPPorts(); + void CreateTCPPorts(); + void CreateStunPorts(); + void CreateRelayPorts(); + + void OnReadPacket(rtc::AsyncPacketSocket* socket, + const char* data, + size_t size, + const rtc::SocketAddress& remote_addr, + const int64_t& packet_time_us); + + void OnPortDestroyed(PortInterface* port); + + BasicPortAllocatorSession* session_; + bool network_failed_ = false; + const rtc::Network* network_; + // Compared with the new best IP in DisableEquivalentPhases. + rtc::IPAddress previous_best_ip_; + PortConfiguration* config_; + State state_; + uint32_t flags_; + ProtocolList protocols_; + std::unique_ptr<rtc::AsyncPacketSocket> udp_socket_; + // There will be only one udp port per AllocationSequence. + UDPPort* udp_port_; + std::vector<Port*> relay_ports_; + int phase_; + std::function<void()> port_allocation_complete_callback_; + // This counter is sampled and passed together with tasks when tasks are + // posted. If the sampled counter doesn't match `epoch_` on reception, the + // posted task is ignored. + int epoch_ = 0; + webrtc::ScopedTaskSafety safety_; +}; + +} // namespace cricket + +#endif // P2P_CLIENT_BASIC_PORT_ALLOCATOR_H_ diff --git a/third_party/libwebrtc/p2p/client/basic_port_allocator_unittest.cc b/third_party/libwebrtc/p2p/client/basic_port_allocator_unittest.cc new file mode 100644 index 0000000000..d1a91afd63 --- /dev/null +++ b/third_party/libwebrtc/p2p/client/basic_port_allocator_unittest.cc @@ -0,0 +1,2802 @@ +/* + * Copyright 2009 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "p2p/client/basic_port_allocator.h" + +#include <memory> +#include <ostream> // no-presubmit-check TODO(webrtc:8982) + +#include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" +#include "p2p/base/basic_packet_socket_factory.h" +#include "p2p/base/p2p_constants.h" +#include "p2p/base/stun_port.h" +#include "p2p/base/stun_request.h" +#include "p2p/base/stun_server.h" +#include "p2p/base/test_stun_server.h" +#include "p2p/base/test_turn_server.h" +#include "rtc_base/fake_clock.h" +#include "rtc_base/fake_mdns_responder.h" +#include "rtc_base/fake_network.h" +#include "rtc_base/firewall_socket_server.h" +#include "rtc_base/gunit.h" +#include "rtc_base/ip_address.h" +#include "rtc_base/logging.h" +#include "rtc_base/nat_server.h" +#include "rtc_base/nat_socket_factory.h" +#include "rtc_base/nat_types.h" +#include "rtc_base/net_helper.h" +#include "rtc_base/net_helpers.h" +#include "rtc_base/network.h" +#include "rtc_base/network_constants.h" +#include "rtc_base/network_monitor.h" +#include "rtc_base/socket.h" +#include "rtc_base/socket_address.h" +#include "rtc_base/socket_address_pair.h" +#include "rtc_base/thread.h" +#include "rtc_base/virtual_socket_server.h" +#include "system_wrappers/include/metrics.h" +#include "test/gmock.h" +#include "test/gtest.h" +#include "test/scoped_key_value_config.h" + +using rtc::IPAddress; +using rtc::SocketAddress; +using ::testing::Contains; +using ::testing::Not; + +#define MAYBE_SKIP_IPV4 \ + if (!rtc::HasIPv4Enabled()) { \ + RTC_LOG(LS_INFO) << "No IPv4... skipping"; \ + return; \ + } + +static const SocketAddress kAnyAddr("0.0.0.0", 0); +static const SocketAddress kClientAddr("11.11.11.11", 0); +static const SocketAddress kClientAddr2("22.22.22.22", 0); +static const SocketAddress kLoopbackAddr("127.0.0.1", 0); +static const SocketAddress kPrivateAddr("192.168.1.11", 0); +static const SocketAddress kPrivateAddr2("192.168.1.12", 0); +static const SocketAddress kClientIPv6Addr("2401:fa00:4:1000:be30:5bff:fee5:c3", + 0); +static const SocketAddress kClientIPv6Addr2( + "2401:fa00:4:2000:be30:5bff:fee5:c3", + 0); +static const SocketAddress kClientIPv6Addr3( + "2401:fa00:4:3000:be30:5bff:fee5:c3", + 0); +static const SocketAddress kClientIPv6Addr4( + "2401:fa00:4:4000:be30:5bff:fee5:c3", + 0); +static const SocketAddress kClientIPv6Addr5( + "2401:fa00:4:5000:be30:5bff:fee5:c3", + 0); +static const SocketAddress kNatUdpAddr("77.77.77.77", rtc::NAT_SERVER_UDP_PORT); +static const SocketAddress kNatTcpAddr("77.77.77.77", rtc::NAT_SERVER_TCP_PORT); +static const SocketAddress kRemoteClientAddr("22.22.22.22", 0); +static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT); +static const SocketAddress kTurnUdpIntAddr("99.99.99.4", 3478); +static const SocketAddress kTurnUdpIntIPv6Addr( + "2402:fb00:4:1000:be30:5bff:fee5:c3", + 3479); +static const SocketAddress kTurnTcpIntAddr("99.99.99.5", 3478); +static const SocketAddress kTurnTcpIntIPv6Addr( + "2402:fb00:4:2000:be30:5bff:fee5:c3", + 3479); +static const SocketAddress kTurnUdpExtAddr("99.99.99.6", 0); + +// Minimum and maximum port for port range tests. +static const int kMinPort = 10000; +static const int kMaxPort = 10099; + +// Based on ICE_UFRAG_LENGTH +static const char kIceUfrag0[] = "UF00"; +// Based on ICE_PWD_LENGTH +static const char kIcePwd0[] = "TESTICEPWD00000000000000"; + +static const char kContentName[] = "test content"; + +static const int kDefaultAllocationTimeout = 3000; +static const char kTurnUsername[] = "test"; +static const char kTurnPassword[] = "test"; + +// STUN timeout (with all retries) is cricket::STUN_TOTAL_TIMEOUT. +// Add some margin of error for slow bots. +static const int kStunTimeoutMs = cricket::STUN_TOTAL_TIMEOUT; + +constexpr uint64_t kTiebreakerDefault = 44444; + +namespace { + +void CheckStunKeepaliveIntervalOfAllReadyPorts( + const cricket::PortAllocatorSession* allocator_session, + int expected) { + auto ready_ports = allocator_session->ReadyPorts(); + for (const auto* port : ready_ports) { + if (port->Type() == cricket::STUN_PORT_TYPE || + (port->Type() == cricket::LOCAL_PORT_TYPE && + port->GetProtocol() == cricket::PROTO_UDP)) { + EXPECT_EQ( + static_cast<const cricket::UDPPort*>(port)->stun_keepalive_delay(), + expected); + } + } +} + +} // namespace + +namespace cricket { + +// Helper for dumping candidates +std::ostream& operator<<(std::ostream& os, + const std::vector<Candidate>& candidates) { + os << '['; + bool first = true; + for (const Candidate& c : candidates) { + if (!first) { + os << ", "; + } + os << c.ToString(); + first = false; + } + os << ']'; + return os; +} + +class BasicPortAllocatorTestBase : public ::testing::Test, + public sigslot::has_slots<> { + public: + BasicPortAllocatorTestBase() + : vss_(new rtc::VirtualSocketServer()), + fss_(new rtc::FirewallSocketServer(vss_.get())), + thread_(fss_.get()), + // Note that the NAT is not used by default. ResetWithStunServerAndNat + // must be called. + nat_factory_(vss_.get(), kNatUdpAddr, kNatTcpAddr), + nat_socket_factory_(new rtc::BasicPacketSocketFactory(&nat_factory_)), + stun_server_(TestStunServer::Create(fss_.get(), kStunAddr)), + turn_server_(rtc::Thread::Current(), + fss_.get(), + kTurnUdpIntAddr, + kTurnUdpExtAddr), + candidate_allocation_done_(false) { + ServerAddresses stun_servers; + stun_servers.insert(kStunAddr); + + allocator_ = std::make_unique<BasicPortAllocator>( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()), + stun_servers, &field_trials_); + allocator_->Initialize(); + allocator_->set_step_delay(kMinimumStepDelay); + allocator_->SetIceTiebreaker(kTiebreakerDefault); + webrtc::metrics::Reset(); + } + + void AddInterface(const SocketAddress& addr) { + network_manager_.AddInterface(addr); + } + void AddInterface(const SocketAddress& addr, absl::string_view if_name) { + network_manager_.AddInterface(addr, if_name); + } + void AddInterface(const SocketAddress& addr, + absl::string_view if_name, + rtc::AdapterType type) { + network_manager_.AddInterface(addr, if_name, type); + } + // The default source address is the public address that STUN server will + // observe when the endpoint is sitting on the public internet and the local + // port is bound to the "any" address. Intended for simulating the situation + // that client binds the "any" address, and that's also the address returned + // by getsockname/GetLocalAddress, so that the client can learn the actual + // local address only from the STUN response. + void AddInterfaceAsDefaultSourceAddresss(const SocketAddress& addr) { + AddInterface(addr); + // When a binding comes from the any address, the `addr` will be used as the + // srflx address. + vss_->SetDefaultSourceAddress(addr.ipaddr()); + } + void RemoveInterface(const SocketAddress& addr) { + network_manager_.RemoveInterface(addr); + } + bool SetPortRange(int min_port, int max_port) { + return allocator_->SetPortRange(min_port, max_port); + } + // Endpoint is on the public network. No STUN or TURN. + void ResetWithNoServersOrNat() { + allocator_.reset(new BasicPortAllocator( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()))); + allocator_->Initialize(); + allocator_->SetIceTiebreaker(kTiebreakerDefault); + allocator_->set_step_delay(kMinimumStepDelay); + } + // Endpoint is behind a NAT, with STUN specified. + void ResetWithStunServerAndNat(const rtc::SocketAddress& stun_server) { + ResetWithStunServer(stun_server, true); + } + // Endpoint is on the public network, with STUN specified. + void ResetWithStunServerNoNat(const rtc::SocketAddress& stun_server) { + ResetWithStunServer(stun_server, false); + } + // Endpoint is on the public network, with TURN specified. + void ResetWithTurnServersNoNat(const rtc::SocketAddress& udp_turn, + const rtc::SocketAddress& tcp_turn) { + ResetWithNoServersOrNat(); + AddTurnServers(udp_turn, tcp_turn); + } + + RelayServerConfig CreateTurnServers(const rtc::SocketAddress& udp_turn, + const rtc::SocketAddress& tcp_turn) { + RelayServerConfig turn_server; + RelayCredentials credentials(kTurnUsername, kTurnPassword); + turn_server.credentials = credentials; + + if (!udp_turn.IsNil()) { + turn_server.ports.push_back(ProtocolAddress(udp_turn, PROTO_UDP)); + } + if (!tcp_turn.IsNil()) { + turn_server.ports.push_back(ProtocolAddress(tcp_turn, PROTO_TCP)); + } + return turn_server; + } + + void AddTurnServers(const rtc::SocketAddress& udp_turn, + const rtc::SocketAddress& tcp_turn) { + RelayServerConfig turn_server = CreateTurnServers(udp_turn, tcp_turn); + allocator_->AddTurnServerForTesting(turn_server); + } + + bool CreateSession(int component) { + session_ = CreateSession("session", component); + if (!session_) { + return false; + } + return true; + } + + bool CreateSession(int component, absl::string_view content_name) { + session_ = CreateSession("session", content_name, component); + if (!session_) { + return false; + } + return true; + } + + std::unique_ptr<PortAllocatorSession> CreateSession(absl::string_view sid, + int component) { + return CreateSession(sid, kContentName, component); + } + + std::unique_ptr<PortAllocatorSession> CreateSession( + absl::string_view sid, + absl::string_view content_name, + int component) { + return CreateSession(sid, content_name, component, kIceUfrag0, kIcePwd0); + } + + std::unique_ptr<PortAllocatorSession> CreateSession( + absl::string_view sid, + absl::string_view content_name, + int component, + absl::string_view ice_ufrag, + absl::string_view ice_pwd) { + std::unique_ptr<PortAllocatorSession> session = + allocator_->CreateSession(content_name, component, ice_ufrag, ice_pwd); + session->SignalPortReady.connect(this, + &BasicPortAllocatorTestBase::OnPortReady); + session->SignalPortsPruned.connect( + this, &BasicPortAllocatorTestBase::OnPortsPruned); + session->SignalCandidatesReady.connect( + this, &BasicPortAllocatorTestBase::OnCandidatesReady); + session->SignalCandidatesRemoved.connect( + this, &BasicPortAllocatorTestBase::OnCandidatesRemoved); + session->SignalCandidatesAllocationDone.connect( + this, &BasicPortAllocatorTestBase::OnCandidatesAllocationDone); + session->set_ice_tiebreaker(kTiebreakerDefault); + return session; + } + + // Return true if the addresses are the same, or the port is 0 in `pattern` + // (acting as a wildcard) and the IPs are the same. + // Even with a wildcard port, the port of the address should be nonzero if + // the IP is nonzero. + static bool AddressMatch(const SocketAddress& address, + const SocketAddress& pattern) { + return address.ipaddr() == pattern.ipaddr() && + ((pattern.port() == 0 && + (address.port() != 0 || IPIsAny(address.ipaddr()))) || + (pattern.port() != 0 && address.port() == pattern.port())); + } + + // Returns the number of ports that have matching type, protocol and + // address. + static int CountPorts(const std::vector<PortInterface*>& ports, + absl::string_view type, + ProtocolType protocol, + const SocketAddress& client_addr) { + return absl::c_count_if( + ports, [type, protocol, client_addr](PortInterface* port) { + return port->Type() == type && port->GetProtocol() == protocol && + port->Network()->GetBestIP() == client_addr.ipaddr(); + }); + } + + static int CountCandidates(const std::vector<Candidate>& candidates, + absl::string_view type, + absl::string_view proto, + const SocketAddress& addr) { + return absl::c_count_if( + candidates, [type, proto, addr](const Candidate& c) { + return c.type() == type && c.protocol() == proto && + AddressMatch(c.address(), addr); + }); + } + + // Find a candidate and return it. + static bool FindCandidate(const std::vector<Candidate>& candidates, + absl::string_view type, + absl::string_view proto, + const SocketAddress& addr, + Candidate* found) { + auto it = + absl::c_find_if(candidates, [type, proto, addr](const Candidate& c) { + return c.type() == type && c.protocol() == proto && + AddressMatch(c.address(), addr); + }); + if (it != candidates.end() && found) { + *found = *it; + } + return it != candidates.end(); + } + + // Convenience method to call FindCandidate with no return. + static bool HasCandidate(const std::vector<Candidate>& candidates, + absl::string_view type, + absl::string_view proto, + const SocketAddress& addr) { + return FindCandidate(candidates, type, proto, addr, nullptr); + } + + // Version of HasCandidate that also takes a related address. + static bool HasCandidateWithRelatedAddr( + const std::vector<Candidate>& candidates, + absl::string_view type, + absl::string_view proto, + const SocketAddress& addr, + const SocketAddress& related_addr) { + return absl::c_any_of( + candidates, [type, proto, addr, related_addr](const Candidate& c) { + return c.type() == type && c.protocol() == proto && + AddressMatch(c.address(), addr) && + AddressMatch(c.related_address(), related_addr); + }); + } + + static bool CheckPort(const rtc::SocketAddress& addr, + int min_port, + int max_port) { + return (addr.port() >= min_port && addr.port() <= max_port); + } + + static bool HasNetwork(const std::vector<const rtc::Network*>& networks, + const rtc::Network& to_be_found) { + auto it = + absl::c_find_if(networks, [to_be_found](const rtc::Network* network) { + return network->description() == to_be_found.description() && + network->name() == to_be_found.name() && + network->prefix() == to_be_found.prefix(); + }); + return it != networks.end(); + } + + void OnCandidatesAllocationDone(PortAllocatorSession* session) { + // We should only get this callback once, except in the mux test where + // we have multiple port allocation sessions. + if (session == session_.get()) { + ASSERT_FALSE(candidate_allocation_done_); + candidate_allocation_done_ = true; + } + EXPECT_TRUE(session->CandidatesAllocationDone()); + } + + // Check if all ports allocated have send-buffer size `expected`. If + // `expected` == -1, check if GetOptions returns SOCKET_ERROR. + void CheckSendBufferSizesOfAllPorts(int expected) { + std::vector<PortInterface*>::iterator it; + for (it = ports_.begin(); it < ports_.end(); ++it) { + int send_buffer_size; + if (expected == -1) { + EXPECT_EQ(SOCKET_ERROR, + (*it)->GetOption(rtc::Socket::OPT_SNDBUF, &send_buffer_size)); + } else { + EXPECT_EQ(0, + (*it)->GetOption(rtc::Socket::OPT_SNDBUF, &send_buffer_size)); + ASSERT_EQ(expected, send_buffer_size); + } + } + } + + rtc::VirtualSocketServer* virtual_socket_server() { return vss_.get(); } + + protected: + BasicPortAllocator& allocator() { return *allocator_; } + + void OnPortReady(PortAllocatorSession* ses, PortInterface* port) { + RTC_LOG(LS_INFO) << "OnPortReady: " << port->ToString(); + ports_.push_back(port); + // Make sure the new port is added to ReadyPorts. + auto ready_ports = ses->ReadyPorts(); + EXPECT_THAT(ready_ports, Contains(port)); + } + void OnPortsPruned(PortAllocatorSession* ses, + const std::vector<PortInterface*>& pruned_ports) { + RTC_LOG(LS_INFO) << "Number of ports pruned: " << pruned_ports.size(); + auto ready_ports = ses->ReadyPorts(); + auto new_end = ports_.end(); + for (PortInterface* port : pruned_ports) { + new_end = std::remove(ports_.begin(), new_end, port); + // Make sure the pruned port is not in ReadyPorts. + EXPECT_THAT(ready_ports, Not(Contains(port))); + } + ports_.erase(new_end, ports_.end()); + } + + void OnCandidatesReady(PortAllocatorSession* ses, + const std::vector<Candidate>& candidates) { + for (const Candidate& candidate : candidates) { + RTC_LOG(LS_INFO) << "OnCandidatesReady: " << candidate.ToString(); + // Sanity check that the ICE component is set. + EXPECT_EQ(ICE_CANDIDATE_COMPONENT_RTP, candidate.component()); + candidates_.push_back(candidate); + } + // Make sure the new candidates are added to Candidates. + auto ses_candidates = ses->ReadyCandidates(); + for (const Candidate& candidate : candidates) { + EXPECT_THAT(ses_candidates, Contains(candidate)); + } + } + + void OnCandidatesRemoved(PortAllocatorSession* session, + const std::vector<Candidate>& removed_candidates) { + auto new_end = std::remove_if( + candidates_.begin(), candidates_.end(), + [removed_candidates](Candidate& candidate) { + for (const Candidate& removed_candidate : removed_candidates) { + if (candidate.MatchesForRemoval(removed_candidate)) { + return true; + } + } + return false; + }); + candidates_.erase(new_end, candidates_.end()); + } + + bool HasRelayAddress(const ProtocolAddress& proto_addr) { + for (size_t i = 0; i < allocator_->turn_servers().size(); ++i) { + RelayServerConfig server_config = allocator_->turn_servers()[i]; + PortList::const_iterator relay_port; + for (relay_port = server_config.ports.begin(); + relay_port != server_config.ports.end(); ++relay_port) { + if (proto_addr.address == relay_port->address && + proto_addr.proto == relay_port->proto) + return true; + } + } + return false; + } + + void ResetWithStunServer(const rtc::SocketAddress& stun_server, + bool with_nat) { + if (with_nat) { + nat_server_.reset(new rtc::NATServer( + rtc::NAT_OPEN_CONE, vss_.get(), kNatUdpAddr, kNatTcpAddr, vss_.get(), + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0))); + } else { + nat_socket_factory_ = + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()); + } + + ServerAddresses stun_servers; + if (!stun_server.IsNil()) { + stun_servers.insert(stun_server); + } + allocator_.reset(new BasicPortAllocator(&network_manager_, + nat_socket_factory_.get(), + stun_servers, &field_trials_)); + allocator_->Initialize(); + allocator_->set_step_delay(kMinimumStepDelay); + } + + std::unique_ptr<rtc::VirtualSocketServer> vss_; + std::unique_ptr<rtc::FirewallSocketServer> fss_; + rtc::AutoSocketServerThread thread_; + std::unique_ptr<rtc::NATServer> nat_server_; + rtc::NATSocketFactory nat_factory_; + std::unique_ptr<rtc::BasicPacketSocketFactory> nat_socket_factory_; + std::unique_ptr<TestStunServer> stun_server_; + TestTurnServer turn_server_; + rtc::FakeNetworkManager network_manager_; + std::unique_ptr<BasicPortAllocator> allocator_; + std::unique_ptr<PortAllocatorSession> session_; + std::vector<PortInterface*> ports_; + std::vector<Candidate> candidates_; + bool candidate_allocation_done_; + webrtc::test::ScopedKeyValueConfig field_trials_; +}; + +class BasicPortAllocatorTestWithRealClock : public BasicPortAllocatorTestBase { +}; + +class FakeClockBase { + public: + rtc::ScopedFakeClock fake_clock; +}; + +class BasicPortAllocatorTest : public FakeClockBase, + public BasicPortAllocatorTestBase { + public: + // This function starts the port/address gathering and check the existence of + // candidates as specified. When `expect_stun_candidate` is true, + // `stun_candidate_addr` carries the expected reflective address, which is + // also the related address for TURN candidate if it is expected. Otherwise, + // it should be ignore. + void CheckDisableAdapterEnumeration( + uint32_t total_ports, + const rtc::IPAddress& host_candidate_addr, + const rtc::IPAddress& stun_candidate_addr, + const rtc::IPAddress& relay_candidate_udp_transport_addr, + const rtc::IPAddress& relay_candidate_tcp_transport_addr) { + network_manager_.set_default_local_addresses(kPrivateAddr.ipaddr(), + rtc::IPAddress()); + if (!session_) { + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + } + session_->set_flags(session_->flags() | + PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + allocator().set_allow_tcp_listen(false); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + uint32_t total_candidates = 0; + if (!host_candidate_addr.IsNil()) { + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", + rtc::SocketAddress(kPrivateAddr.ipaddr(), 0))); + ++total_candidates; + } + if (!stun_candidate_addr.IsNil()) { + rtc::SocketAddress related_address(host_candidate_addr, 0); + if (host_candidate_addr.IsNil()) { + related_address.SetIP(rtc::GetAnyIP(stun_candidate_addr.family())); + } + EXPECT_TRUE(HasCandidateWithRelatedAddr( + candidates_, "stun", "udp", + rtc::SocketAddress(stun_candidate_addr, 0), related_address)); + ++total_candidates; + } + if (!relay_candidate_udp_transport_addr.IsNil()) { + EXPECT_TRUE(HasCandidateWithRelatedAddr( + candidates_, "relay", "udp", + rtc::SocketAddress(relay_candidate_udp_transport_addr, 0), + rtc::SocketAddress(stun_candidate_addr, 0))); + ++total_candidates; + } + if (!relay_candidate_tcp_transport_addr.IsNil()) { + EXPECT_TRUE(HasCandidateWithRelatedAddr( + candidates_, "relay", "udp", + rtc::SocketAddress(relay_candidate_tcp_transport_addr, 0), + rtc::SocketAddress(stun_candidate_addr, 0))); + ++total_candidates; + } + + EXPECT_EQ(total_candidates, candidates_.size()); + EXPECT_EQ(total_ports, ports_.size()); + } + + void TestIPv6TurnPortPrunesIPv4TurnPort() { + turn_server_.AddInternalSocket(kTurnUdpIntIPv6Addr, PROTO_UDP); + // Add two IP addresses on the same interface. + AddInterface(kClientAddr, "net1"); + AddInterface(kClientIPv6Addr, "net1"); + allocator_.reset(new BasicPortAllocator( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()))); + allocator_->Initialize(); + allocator_->SetConfiguration(allocator_->stun_servers(), + allocator_->turn_servers(), 0, + webrtc::PRUNE_BASED_ON_PRIORITY); + AddTurnServers(kTurnUdpIntIPv6Addr, rtc::SocketAddress()); + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_step_delay(kMinimumStepDelay); + allocator_->set_flags( + allocator().flags() | PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Three ports (one IPv4 STUN, one IPv6 STUN and one TURN) will be ready. + EXPECT_EQ(3U, session_->ReadyPorts().size()); + EXPECT_EQ(3U, ports_.size()); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientAddr)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientIPv6Addr)); + EXPECT_EQ(1, CountPorts(ports_, "relay", PROTO_UDP, kClientIPv6Addr)); + EXPECT_EQ(0, CountPorts(ports_, "relay", PROTO_UDP, kClientAddr)); + + // Now that we remove candidates when a TURN port is pruned, there will be + // exactly 3 candidates in both `candidates_` and `ready_candidates`. + EXPECT_EQ(3U, candidates_.size()); + const std::vector<Candidate>& ready_candidates = + session_->ReadyCandidates(); + EXPECT_EQ(3U, ready_candidates.size()); + EXPECT_TRUE(HasCandidate(ready_candidates, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(ready_candidates, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + } + + void TestTurnPortPrunesWithUdpAndTcpPorts( + webrtc::PortPrunePolicy prune_policy, + bool tcp_pruned) { + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddInterface(kClientAddr); + allocator_.reset(new BasicPortAllocator( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()))); + allocator_->Initialize(); + allocator_->SetConfiguration(allocator_->stun_servers(), + allocator_->turn_servers(), 0, prune_policy); + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + allocator_->set_step_delay(kMinimumStepDelay); + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Only 2 ports (one STUN and one TURN) are actually being used. + EXPECT_EQ(2U, session_->ReadyPorts().size()); + // We have verified that each port, when it is added to `ports_`, it is + // found in `ready_ports`, and when it is pruned, it is not found in + // `ready_ports`, so we only need to verify the content in one of them. + EXPECT_EQ(2U, ports_.size()); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientAddr)); + int num_udp_ports = tcp_pruned ? 1 : 0; + EXPECT_EQ(num_udp_ports, + CountPorts(ports_, "relay", PROTO_UDP, kClientAddr)); + EXPECT_EQ(1 - num_udp_ports, + CountPorts(ports_, "relay", PROTO_TCP, kClientAddr)); + + // Now that we remove candidates when a TURN port is pruned, `candidates_` + // should only contains two candidates regardless whether the TCP TURN port + // is created before or after the UDP turn port. + EXPECT_EQ(2U, candidates_.size()); + // There will only be 2 candidates in `ready_candidates` because it only + // includes the candidates in the ready ports. + const std::vector<Candidate>& ready_candidates = + session_->ReadyCandidates(); + EXPECT_EQ(2U, ready_candidates.size()); + EXPECT_TRUE(HasCandidate(ready_candidates, "local", "udp", kClientAddr)); + + // The external candidate is always udp. + EXPECT_TRUE(HasCandidate(ready_candidates, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + } + + void TestEachInterfaceHasItsOwnTurnPorts() { + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + turn_server_.AddInternalSocket(kTurnUdpIntIPv6Addr, PROTO_UDP); + turn_server_.AddInternalSocket(kTurnTcpIntIPv6Addr, PROTO_TCP); + // Add two interfaces both having IPv4 and IPv6 addresses. + AddInterface(kClientAddr, "net1", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr, "net1", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientAddr2, "net2", rtc::ADAPTER_TYPE_CELLULAR); + AddInterface(kClientIPv6Addr2, "net2", rtc::ADAPTER_TYPE_CELLULAR); + allocator_.reset(new BasicPortAllocator( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()))); + allocator_->Initialize(); + allocator_->SetConfiguration(allocator_->stun_servers(), + allocator_->turn_servers(), 0, + webrtc::PRUNE_BASED_ON_PRIORITY); + // Have both UDP/TCP and IPv4/IPv6 TURN ports. + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + AddTurnServers(kTurnUdpIntIPv6Addr, kTurnTcpIntIPv6Addr); + + allocator_->set_step_delay(kMinimumStepDelay); + allocator_->set_flags( + allocator().flags() | PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // 10 ports (4 STUN and 1 TURN ports on each interface) will be ready to + // use. + EXPECT_EQ(10U, session_->ReadyPorts().size()); + EXPECT_EQ(10U, ports_.size()); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientAddr)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientAddr2)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientIPv6Addr)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_UDP, kClientIPv6Addr2)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_TCP, kClientAddr)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_TCP, kClientAddr2)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_TCP, kClientIPv6Addr)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_TCP, kClientIPv6Addr2)); + EXPECT_EQ(1, CountPorts(ports_, "relay", PROTO_UDP, kClientIPv6Addr)); + EXPECT_EQ(1, CountPorts(ports_, "relay", PROTO_UDP, kClientIPv6Addr2)); + + // Now that we remove candidates when TURN ports are pruned, there will be + // exactly 10 candidates in `candidates_`. + EXPECT_EQ(10U, candidates_.size()); + const std::vector<Candidate>& ready_candidates = + session_->ReadyCandidates(); + EXPECT_EQ(10U, ready_candidates.size()); + EXPECT_TRUE(HasCandidate(ready_candidates, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(ready_candidates, "local", "udp", kClientAddr2)); + EXPECT_TRUE( + HasCandidate(ready_candidates, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE( + HasCandidate(ready_candidates, "local", "udp", kClientIPv6Addr2)); + EXPECT_TRUE(HasCandidate(ready_candidates, "local", "tcp", kClientAddr)); + EXPECT_TRUE(HasCandidate(ready_candidates, "local", "tcp", kClientAddr2)); + EXPECT_TRUE( + HasCandidate(ready_candidates, "local", "tcp", kClientIPv6Addr)); + EXPECT_TRUE( + HasCandidate(ready_candidates, "local", "tcp", kClientIPv6Addr2)); + EXPECT_TRUE(HasCandidate(ready_candidates, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + } +}; + +// Tests that we can init the port allocator and create a session. +TEST_F(BasicPortAllocatorTest, TestBasic) { + EXPECT_EQ(&network_manager_, allocator().network_manager()); + EXPECT_EQ(kStunAddr, *allocator().stun_servers().begin()); + ASSERT_EQ(0u, allocator().turn_servers().size()); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + EXPECT_FALSE(session_->CandidatesAllocationDone()); +} + +// Tests that our network filtering works properly. +TEST_F(BasicPortAllocatorTest, TestIgnoreOnlyLoopbackNetworkByDefault) { + AddInterface(SocketAddress(IPAddress(0x12345600U), 0), "test_eth0", + rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(SocketAddress(IPAddress(0x12345601U), 0), "test_wlan0", + rtc::ADAPTER_TYPE_WIFI); + AddInterface(SocketAddress(IPAddress(0x12345602U), 0), "test_cell0", + rtc::ADAPTER_TYPE_CELLULAR); + AddInterface(SocketAddress(IPAddress(0x12345603U), 0), "test_vpn0", + rtc::ADAPTER_TYPE_VPN); + AddInterface(SocketAddress(IPAddress(0x12345604U), 0), "test_lo", + rtc::ADAPTER_TYPE_LOOPBACK); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(4U, candidates_.size()); + for (const Candidate& candidate : candidates_) { + EXPECT_LT(candidate.address().ip(), 0x12345604U); + } +} + +TEST_F(BasicPortAllocatorTest, TestIgnoreNetworksAccordingToIgnoreMask) { + AddInterface(SocketAddress(IPAddress(0x12345600U), 0), "test_eth0", + rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(SocketAddress(IPAddress(0x12345601U), 0), "test_wlan0", + rtc::ADAPTER_TYPE_WIFI); + AddInterface(SocketAddress(IPAddress(0x12345602U), 0), "test_cell0", + rtc::ADAPTER_TYPE_CELLULAR); + allocator_->SetNetworkIgnoreMask(rtc::ADAPTER_TYPE_ETHERNET | + rtc::ADAPTER_TYPE_LOOPBACK | + rtc::ADAPTER_TYPE_WIFI); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(1U, candidates_.size()); + EXPECT_EQ(0x12345602U, candidates_[0].address().ip()); +} + +// Test that when the PORTALLOCATOR_DISABLE_COSTLY_NETWORKS flag is set and +// both Wi-Fi and cell interfaces are available, only Wi-Fi is used. +TEST_F(BasicPortAllocatorTest, + WifiUsedInsteadOfCellWhenCostlyNetworksDisabled) { + SocketAddress wifi(IPAddress(0x12345600U), 0); + SocketAddress cell(IPAddress(0x12345601U), 0); + AddInterface(wifi, "test_wlan0", rtc::ADAPTER_TYPE_WIFI); + AddInterface(cell, "test_cell0", rtc::ADAPTER_TYPE_CELLULAR); + // Disable all but UDP candidates to make the test simpler. + allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | + cricket::PORTALLOCATOR_DISABLE_RELAY | + cricket::PORTALLOCATOR_DISABLE_TCP | + cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS); + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Should only get one Wi-Fi candidate. + EXPECT_EQ(1U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", wifi)); +} + +// Test that when the PORTALLOCATOR_DISABLE_COSTLY_NETWORKS flag is set and +// both "unknown" and cell interfaces are available, only the unknown are used. +// The unknown interface may be something that ultimately uses Wi-Fi, so we do +// this to be on the safe side. +TEST_F(BasicPortAllocatorTest, + UnknownInterfaceUsedInsteadOfCellWhenCostlyNetworksDisabled) { + SocketAddress cell(IPAddress(0x12345601U), 0); + SocketAddress unknown1(IPAddress(0x12345602U), 0); + SocketAddress unknown2(IPAddress(0x12345603U), 0); + AddInterface(cell, "test_cell0", rtc::ADAPTER_TYPE_CELLULAR); + AddInterface(unknown1, "test_unknown0", rtc::ADAPTER_TYPE_UNKNOWN); + AddInterface(unknown2, "test_unknown1", rtc::ADAPTER_TYPE_UNKNOWN); + // Disable all but UDP candidates to make the test simpler. + allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | + cricket::PORTALLOCATOR_DISABLE_RELAY | + cricket::PORTALLOCATOR_DISABLE_TCP | + cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS); + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Should only get two candidates, none of which is cell. + EXPECT_EQ(2U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", unknown1)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", unknown2)); +} + +// Test that when the PORTALLOCATOR_DISABLE_COSTLY_NETWORKS flag is set and +// there are a mix of Wi-Fi, "unknown" and cell interfaces, only the Wi-Fi +// interface is used. +TEST_F(BasicPortAllocatorTest, + WifiUsedInsteadOfUnknownOrCellWhenCostlyNetworksDisabled) { + SocketAddress wifi(IPAddress(0x12345600U), 0); + SocketAddress cellular(IPAddress(0x12345601U), 0); + SocketAddress unknown1(IPAddress(0x12345602U), 0); + SocketAddress unknown2(IPAddress(0x12345603U), 0); + AddInterface(wifi, "test_wlan0", rtc::ADAPTER_TYPE_WIFI); + AddInterface(cellular, "test_cell0", rtc::ADAPTER_TYPE_CELLULAR); + AddInterface(unknown1, "test_unknown0", rtc::ADAPTER_TYPE_UNKNOWN); + AddInterface(unknown2, "test_unknown1", rtc::ADAPTER_TYPE_UNKNOWN); + // Disable all but UDP candidates to make the test simpler. + allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | + cricket::PORTALLOCATOR_DISABLE_RELAY | + cricket::PORTALLOCATOR_DISABLE_TCP | + cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS); + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Should only get one Wi-Fi candidate. + EXPECT_EQ(1U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", wifi)); +} + +// Test that if the PORTALLOCATOR_DISABLE_COSTLY_NETWORKS flag is set, but the +// only interface available is cellular, it ends up used anyway. A costly +// connection is always better than no connection. +TEST_F(BasicPortAllocatorTest, + CellUsedWhenCostlyNetworksDisabledButThereAreNoOtherInterfaces) { + SocketAddress cellular(IPAddress(0x12345601U), 0); + AddInterface(cellular, "test_cell0", rtc::ADAPTER_TYPE_CELLULAR); + // Disable all but UDP candidates to make the test simpler. + allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | + cricket::PORTALLOCATOR_DISABLE_RELAY | + cricket::PORTALLOCATOR_DISABLE_TCP | + cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS); + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Make sure we got the cell candidate. + EXPECT_EQ(1U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", cellular)); +} + +// Test that if both PORTALLOCATOR_DISABLE_COSTLY_NETWORKS is set, and there is +// a WiFi network with link-local IP address and a cellular network, then the +// cellular candidate will still be gathered. +TEST_F(BasicPortAllocatorTest, + CellNotRemovedWhenCostlyNetworksDisabledAndWifiIsLinkLocal) { + SocketAddress wifi_link_local("169.254.0.1", 0); + SocketAddress cellular(IPAddress(0x12345601U), 0); + AddInterface(wifi_link_local, "test_wlan0", rtc::ADAPTER_TYPE_WIFI); + AddInterface(cellular, "test_cell0", rtc::ADAPTER_TYPE_CELLULAR); + + allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | + cricket::PORTALLOCATOR_DISABLE_RELAY | + cricket::PORTALLOCATOR_DISABLE_TCP | + cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS); + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Make sure we got both wifi and cell candidates. + EXPECT_EQ(2U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", wifi_link_local)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", cellular)); +} + +// Test that if both PORTALLOCATOR_DISABLE_COSTLY_NETWORKS is set, and there is +// a WiFi network with link-local IP address, a WiFi network with a normal IP +// address and a cellular network, then the cellular candidate will not be +// gathered. +TEST_F(BasicPortAllocatorTest, + CellRemovedWhenCostlyNetworksDisabledAndBothWifisPresent) { + SocketAddress wifi(IPAddress(0x12345600U), 0); + SocketAddress wifi_link_local("169.254.0.1", 0); + SocketAddress cellular(IPAddress(0x12345601U), 0); + AddInterface(wifi, "test_wlan0", rtc::ADAPTER_TYPE_WIFI); + AddInterface(wifi_link_local, "test_wlan1", rtc::ADAPTER_TYPE_WIFI); + AddInterface(cellular, "test_cell0", rtc::ADAPTER_TYPE_CELLULAR); + + allocator().set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | + cricket::PORTALLOCATOR_DISABLE_RELAY | + cricket::PORTALLOCATOR_DISABLE_TCP | + cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS); + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Make sure we got only wifi candidates. + EXPECT_EQ(2U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", wifi)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", wifi_link_local)); +} + +// Test that the adapter types of the Ethernet and the VPN can be correctly +// identified so that the Ethernet has a lower network cost than the VPN, and +// the Ethernet is not filtered out if PORTALLOCATOR_DISABLE_COSTLY_NETWORKS is +// set. +TEST_F(BasicPortAllocatorTest, + EthernetIsNotFilteredOutWhenCostlyNetworksDisabledAndVpnPresent) { + AddInterface(kClientAddr, "eth0", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientAddr2, "tap0", rtc::ADAPTER_TYPE_VPN); + allocator().set_flags(PORTALLOCATOR_DISABLE_COSTLY_NETWORKS | + PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // The VPN tap0 network should be filtered out as a costly network, and we + // should have a UDP port and a STUN port from the Ethernet eth0. + ASSERT_EQ(2U, ports_.size()); + EXPECT_EQ(ports_[0]->Network()->name(), "eth0"); + EXPECT_EQ(ports_[1]->Network()->name(), "eth0"); +} + +// Test that no more than allocator.max_ipv6_networks() IPv6 networks are used +// to gather candidates. +TEST_F(BasicPortAllocatorTest, MaxIpv6NetworksLimitEnforced) { + // Add three IPv6 network interfaces, but tell the allocator to only use two. + allocator().set_max_ipv6_networks(2); + AddInterface(kClientIPv6Addr, "eth0", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "eth1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr3, "eth2", rtc::ADAPTER_TYPE_ETHERNET); + + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(2U, candidates_.size()); + // Ensure the expected two interfaces (eth0 and eth1) were used. + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr2)); +} + +// Ensure that allocator.max_ipv6_networks() doesn't prevent IPv4 networks from +// being used. +TEST_F(BasicPortAllocatorTest, MaxIpv6NetworksLimitDoesNotImpactIpv4Networks) { + // Set the "max IPv6" limit to 1, adding two IPv6 and two IPv4 networks. + allocator().set_max_ipv6_networks(1); + AddInterface(kClientIPv6Addr, "eth0", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "eth1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientAddr, "eth2", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientAddr2, "eth3", rtc::ADAPTER_TYPE_ETHERNET); + + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + // Ensure that only one IPv6 interface was used, but both IPv4 interfaces + // were used. + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr2)); +} + +// Test that we could use loopback interface as host candidate. +TEST_F(BasicPortAllocatorTest, TestLoopbackNetworkInterface) { + AddInterface(kLoopbackAddr, "test_loopback", rtc::ADAPTER_TYPE_LOOPBACK); + allocator_->SetNetworkIgnoreMask(0); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(1U, candidates_.size()); +} + +// Tests that we can get all the desired addresses successfully. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsWithMinimumStepDelay) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "stun", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); +} + +// Test that when the same network interface is brought down and up, the +// port allocator session will restart a new allocation sequence if +// it is not stopped. +TEST_F(BasicPortAllocatorTest, TestSameNetworkDownAndUpWhenSessionNotStopped) { + std::string if_name("test_net0"); + AddInterface(kClientAddr, if_name); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); + candidate_allocation_done_ = false; + candidates_.clear(); + ports_.clear(); + + // Disable socket creation to simulate the network interface being down. When + // no network interfaces are available, BasicPortAllocator will fall back to + // binding to the "ANY" address, so we need to make sure that fails too. + fss_->set_tcp_sockets_enabled(false); + fss_->set_udp_sockets_enabled(false); + RemoveInterface(kClientAddr); + SIMULATED_WAIT(false, 1000, fake_clock); + EXPECT_EQ(0U, candidates_.size()); + ports_.clear(); + candidate_allocation_done_ = false; + + // When the same interfaces are added again, new candidates/ports should be + // generated. + fss_->set_tcp_sockets_enabled(true); + fss_->set_udp_sockets_enabled(true); + AddInterface(kClientAddr, if_name); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); +} + +// Test that when the same network interface is brought down and up, the +// port allocator session will not restart a new allocation sequence if +// it is stopped. +TEST_F(BasicPortAllocatorTest, TestSameNetworkDownAndUpWhenSessionStopped) { + std::string if_name("test_net0"); + AddInterface(kClientAddr, if_name); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); + session_->StopGettingPorts(); + candidates_.clear(); + ports_.clear(); + + RemoveInterface(kClientAddr); + // Wait one (simulated) second and then verify no new candidates have + // appeared. + SIMULATED_WAIT(false, 1000, fake_clock); + EXPECT_EQ(0U, candidates_.size()); + EXPECT_EQ(0U, ports_.size()); + + // When the same interfaces are added again, new candidates/ports should not + // be generated because the session has stopped. + AddInterface(kClientAddr, if_name); + SIMULATED_WAIT(false, 1000, fake_clock); + EXPECT_EQ(0U, candidates_.size()); + EXPECT_EQ(0U, ports_.size()); +} + +// Similar to the above tests, but tests a situation when sockets can't be +// bound to a network interface, then after a network change event can be. +// Related bug: https://bugs.chromium.org/p/webrtc/issues/detail?id=8256 +TEST_F(BasicPortAllocatorTest, CandidatesRegatheredAfterBindingFails) { + // Only test local ports to simplify test. + ResetWithNoServersOrNat(); + // Provide a situation where the interface appears to be available, but + // binding the sockets fails. See bug for description of when this can + // happen. + std::string if_name("test_net0"); + AddInterface(kClientAddr, if_name); + fss_->set_tcp_sockets_enabled(false); + fss_->set_udp_sockets_enabled(false); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Make sure we actually prevented candidates from being gathered (other than + // a single TCP active candidate, since that doesn't require creating a + // socket). + ASSERT_EQ(1U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); + candidate_allocation_done_ = false; + + // Now simulate the interface coming up, with the newfound ability to bind + // sockets. + fss_->set_tcp_sockets_enabled(true); + fss_->set_udp_sockets_enabled(true); + AddInterface(kClientAddr, if_name); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Should get UDP and TCP candidate. + ASSERT_EQ(2U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + // TODO(deadbeef): This is actually the same active TCP candidate as before. + // We should extend this test to also verify that a server candidate is + // gathered. + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); +} + +// Verify candidates with default step delay of 1sec. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsWithOneSecondStepDelay) { + AddInterface(kClientAddr); + allocator_->set_step_delay(kDefaultStepDelay); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(2U, candidates_.size(), 1000, fake_clock); + EXPECT_EQ(2U, ports_.size()); + ASSERT_EQ_SIMULATED_WAIT(3U, candidates_.size(), 2000, fake_clock); + EXPECT_EQ(3U, ports_.size()); + + ASSERT_EQ_SIMULATED_WAIT(3U, candidates_.size(), 1500, fake_clock); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); + EXPECT_EQ(3U, ports_.size()); + EXPECT_TRUE(candidate_allocation_done_); + // If we Stop gathering now, we shouldn't get a second "done" callback. + session_->StopGettingPorts(); +} + +TEST_F(BasicPortAllocatorTest, TestSetupVideoRtpPortsWithNormalSendBuffers) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP, CN_VIDEO)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + // If we Stop gathering now, we shouldn't get a second "done" callback. + session_->StopGettingPorts(); + + // All ports should have unset send-buffer sizes. + CheckSendBufferSizesOfAllPorts(-1); +} + +// Tests that we can get callback after StopGetAllPorts when called in the +// middle of gathering. +TEST_F(BasicPortAllocatorTest, TestStopGetAllPorts) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(2U, ports_.size()); + session_->StopGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); +} + +// Test that we restrict client ports appropriately when a port range is set. +// We check the candidates for udp/stun/tcp ports, and the from address +// for relay ports. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsPortRange) { + AddInterface(kClientAddr); + // Check that an invalid port range fails. + EXPECT_FALSE(SetPortRange(kMaxPort, kMinPort)); + // Check that a null port range succeeds. + EXPECT_TRUE(SetPortRange(0, 0)); + // Check that a valid port range succeeds. + EXPECT_TRUE(SetPortRange(kMinPort, kMaxPort)); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); + + int num_nonrelay_candidates = 0; + for (const Candidate& candidate : candidates_) { + // Check the port number for the UDP/STUN/TCP port objects. + if (candidate.type() != RELAY_PORT_TYPE) { + EXPECT_TRUE(CheckPort(candidate.address(), kMinPort, kMaxPort)); + ++num_nonrelay_candidates; + } + } + EXPECT_EQ(3, num_nonrelay_candidates); +} + +// Test that if we have no network adapters, we bind to the ANY address and +// still get non-host candidates. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsNoAdapters) { + // Default config uses GTURN and no NAT, so replace that with the + // desired setup (NAT, STUN server, TURN server, UDP/TCP). + ResetWithStunServerAndNat(kStunAddr); + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + AddTurnServers(kTurnUdpIntIPv6Addr, kTurnTcpIntIPv6Addr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(4U, ports_.size()); + EXPECT_EQ(1, CountPorts(ports_, "stun", PROTO_UDP, kAnyAddr)); + EXPECT_EQ(1, CountPorts(ports_, "local", PROTO_TCP, kAnyAddr)); + // Two TURN ports, using UDP/TCP for the first hop to the TURN server. + EXPECT_EQ(1, CountPorts(ports_, "relay", PROTO_UDP, kAnyAddr)); + EXPECT_EQ(1, CountPorts(ports_, "relay", PROTO_TCP, kAnyAddr)); + // The "any" address port should be in the signaled ready ports, but the host + // candidate for it is useless and shouldn't be signaled. So we only have + // STUN/TURN candidates. + EXPECT_EQ(3U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "stun", "udp", + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0))); + // Again, two TURN candidates, using UDP/TCP for the first hop to the TURN + // server. + EXPECT_EQ(2, + CountCandidates(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); +} + +// Test that when enumeration is disabled, we should not have any ports when +// candidate_filter() is set to CF_RELAY and no relay is specified. +TEST_F(BasicPortAllocatorTest, + TestDisableAdapterEnumerationWithoutNatRelayTransportOnly) { + ResetWithStunServerNoNat(kStunAddr); + allocator().SetCandidateFilter(CF_RELAY); + // Expect to see no ports and no candidates. + CheckDisableAdapterEnumeration(0U, rtc::IPAddress(), rtc::IPAddress(), + rtc::IPAddress(), rtc::IPAddress()); +} + +// Test that even with multiple interfaces, the result should still be a single +// default private, one STUN and one TURN candidate since we bind to any address +// (i.e. all 0s). +TEST_F(BasicPortAllocatorTest, + TestDisableAdapterEnumerationBehindNatMultipleInterfaces) { + AddInterface(kPrivateAddr); + AddInterface(kPrivateAddr2); + ResetWithStunServerAndNat(kStunAddr); + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + // Enable IPv6 here. Since the network_manager doesn't have IPv6 default + // address set and we have no IPv6 STUN server, there should be no IPv6 + // candidates. + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_ENABLE_IPV6); + + // Expect to see 3 ports for IPv4: HOST/STUN, TURN/UDP and TCP ports, 2 ports + // for IPv6: HOST, and TCP. Only IPv4 candidates: a default private, STUN and + // TURN/UDP candidates. + CheckDisableAdapterEnumeration(5U, kPrivateAddr.ipaddr(), + kNatUdpAddr.ipaddr(), kTurnUdpExtAddr.ipaddr(), + rtc::IPAddress()); +} + +// Test that we should get a default private, STUN, TURN/UDP and TURN/TCP +// candidates when both TURN/UDP and TURN/TCP servers are specified. +TEST_F(BasicPortAllocatorTest, TestDisableAdapterEnumerationBehindNatWithTcp) { + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddInterface(kPrivateAddr); + ResetWithStunServerAndNat(kStunAddr); + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + // Expect to see 4 ports - STUN, TURN/UDP, TURN/TCP and TCP port. A default + // private, STUN, TURN/UDP, and TURN/TCP candidates. + CheckDisableAdapterEnumeration(4U, kPrivateAddr.ipaddr(), + kNatUdpAddr.ipaddr(), kTurnUdpExtAddr.ipaddr(), + kTurnUdpExtAddr.ipaddr()); +} + +// Test that when adapter enumeration is disabled, for endpoints without +// STUN/TURN specified, a default private candidate is still generated. +TEST_F(BasicPortAllocatorTest, + TestDisableAdapterEnumerationWithoutNatOrServers) { + ResetWithNoServersOrNat(); + // Expect to see 2 ports: STUN and TCP ports, one default private candidate. + CheckDisableAdapterEnumeration(2U, kPrivateAddr.ipaddr(), rtc::IPAddress(), + rtc::IPAddress(), rtc::IPAddress()); +} + +// Test that when adapter enumeration is disabled, with +// PORTALLOCATOR_DISABLE_LOCALHOST_CANDIDATE specified, for endpoints not behind +// a NAT, there is no local candidate. +TEST_F(BasicPortAllocatorTest, + TestDisableAdapterEnumerationWithoutNatLocalhostCandidateDisabled) { + ResetWithStunServerNoNat(kStunAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE); + // Expect to see 2 ports: STUN and TCP ports, localhost candidate and STUN + // candidate. + CheckDisableAdapterEnumeration(2U, rtc::IPAddress(), rtc::IPAddress(), + rtc::IPAddress(), rtc::IPAddress()); +} + +// Test that when adapter enumeration is disabled, with +// PORTALLOCATOR_DISABLE_LOCALHOST_CANDIDATE specified, for endpoints not behind +// a NAT, there is no local candidate. However, this specified default route +// (kClientAddr) which was discovered when sending STUN requests, will become +// the srflx addresses. +TEST_F(BasicPortAllocatorTest, + TestDisableAdapterEnumerationWithoutNatLocalhostCandDisabledDiffRoute) { + ResetWithStunServerNoNat(kStunAddr); + AddInterfaceAsDefaultSourceAddresss(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE); + // Expect to see 2 ports: STUN and TCP ports, localhost candidate and STUN + // candidate. + CheckDisableAdapterEnumeration(2U, rtc::IPAddress(), kClientAddr.ipaddr(), + rtc::IPAddress(), rtc::IPAddress()); +} + +// Test that when adapter enumeration is disabled, with +// PORTALLOCATOR_DISABLE_LOCALHOST_CANDIDATE specified, for endpoints behind a +// NAT, there is only one STUN candidate. +TEST_F(BasicPortAllocatorTest, + TestDisableAdapterEnumerationWithNatLocalhostCandidateDisabled) { + ResetWithStunServerAndNat(kStunAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE); + // Expect to see 2 ports: STUN and TCP ports, and single STUN candidate. + CheckDisableAdapterEnumeration(2U, rtc::IPAddress(), kNatUdpAddr.ipaddr(), + rtc::IPAddress(), rtc::IPAddress()); +} + +// Test that we disable relay over UDP, and only TCP is used when connecting to +// the relay server. +TEST_F(BasicPortAllocatorTest, TestDisableUdpTurn) { + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddInterface(kClientAddr); + ResetWithStunServerAndNat(kStunAddr); + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_UDP_RELAY | + PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + // Expect to see 2 ports and 2 candidates - TURN/TCP and TCP ports, TCP and + // TURN/TCP candidates. + EXPECT_EQ(2U, ports_.size()); + EXPECT_EQ(2U, candidates_.size()); + Candidate turn_candidate; + EXPECT_TRUE(FindCandidate(candidates_, "relay", "udp", kTurnUdpExtAddr, + &turn_candidate)); + // The TURN candidate should use TCP to contact the TURN server. + EXPECT_EQ(TCP_PROTOCOL_NAME, turn_candidate.relay_protocol()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); +} + +// Test that we can get OnCandidatesAllocationDone callback when all the ports +// are disabled. +TEST_F(BasicPortAllocatorTest, TestDisableAllPorts) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->set_flags(PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY | PORTALLOCATOR_DISABLE_TCP); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, 1000, fake_clock); + EXPECT_EQ(0U, candidates_.size()); +} + +// Test that we don't crash or malfunction if we can't create UDP sockets. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsNoUdpSockets) { + AddInterface(kClientAddr); + fss_->set_udp_sockets_enabled(false); + ASSERT_TRUE(CreateSession(1)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(1U, candidates_.size()); + EXPECT_EQ(1U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); +} + +// Test that we don't crash or malfunction if we can't create UDP sockets or +// listen on TCP sockets. We still give out a local TCP address, since +// apparently this is needed for the remote side to accept our connection. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsNoUdpSocketsNoTcpListen) { + AddInterface(kClientAddr); + fss_->set_udp_sockets_enabled(false); + fss_->set_tcp_listen_enabled(false); + ASSERT_TRUE(CreateSession(1)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(1U, candidates_.size()); + EXPECT_EQ(1U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); +} + +// Test that we don't crash or malfunction if we can't create any sockets. +// TODO(deadbeef): Find a way to exit early here. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsNoSockets) { + AddInterface(kClientAddr); + fss_->set_tcp_sockets_enabled(false); + fss_->set_udp_sockets_enabled(false); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + SIMULATED_WAIT(candidates_.size() > 0, 2000, fake_clock); + // TODO(deadbeef): Check candidate_allocation_done signal. + // In case of Relay, ports creation will succeed but sockets will fail. + // There is no error reporting from RelayEntry to handle this failure. +} + +// Testing STUN timeout. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsNoUdpAllowed) { + fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr); + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_EQ_SIMULATED_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(2U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); + // We wait at least for a full STUN timeout, which + // cricket::STUN_TOTAL_TIMEOUT seconds. + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + cricket::STUN_TOTAL_TIMEOUT, fake_clock); + // No additional (STUN) candidates. + EXPECT_EQ(2U, candidates_.size()); +} + +TEST_F(BasicPortAllocatorTest, TestCandidatePriorityOfMultipleInterfaces) { + AddInterface(kClientAddr); + AddInterface(kClientAddr2); + // Allocating only host UDP ports. This is done purely for testing + // convenience. + allocator().set_flags(PORTALLOCATOR_DISABLE_TCP | PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + ASSERT_EQ(2U, candidates_.size()); + EXPECT_EQ(2U, ports_.size()); + // Candidates priorities should be different. + EXPECT_NE(candidates_[0].priority(), candidates_[1].priority()); +} + +// Test to verify ICE restart process. +TEST_F(BasicPortAllocatorTest, TestGetAllPortsRestarts) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); + // TODO(deadbeef): Extend this to verify ICE restart. +} + +// Test that the allocator session uses the candidate filter it's created with, +// rather than the filter of its parent allocator. +// The filter of the allocator should only affect the next gathering phase, +// according to JSEP, which means the *next* allocator session returned. +TEST_F(BasicPortAllocatorTest, TestSessionUsesOwnCandidateFilter) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + // Set candidate filter *after* creating the session. Should have no effect. + allocator().SetCandidateFilter(CF_RELAY); + session_->StartGettingPorts(); + // 7 candidates and 4 ports is what we would normally get (see the + // TestGetAllPorts* tests). + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_EQ(3U, ports_.size()); +} + +// Test ICE candidate filter mechanism with options Relay/Host/Reflexive. +// This test also verifies that when the allocator is only allowed to use +// relay (i.e. IceTransportsType is relay), the raddr is an empty +// address with the correct family. This is to prevent any local +// reflective address leakage in the sdp line. +TEST_F(BasicPortAllocatorTest, TestCandidateFilterWithRelayOnly) { + AddInterface(kClientAddr); + // GTURN is not configured here. + ResetWithTurnServersNoNat(kTurnUdpIntAddr, rtc::SocketAddress()); + allocator().SetCandidateFilter(CF_RELAY); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_TRUE(HasCandidate(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + + EXPECT_EQ(1U, candidates_.size()); + EXPECT_EQ(1U, ports_.size()); // Only Relay port will be in ready state. + EXPECT_EQ(std::string(RELAY_PORT_TYPE), candidates_[0].type()); + EXPECT_EQ( + candidates_[0].related_address(), + rtc::EmptySocketAddressWithFamily(candidates_[0].address().family())); +} + +TEST_F(BasicPortAllocatorTest, TestCandidateFilterWithHostOnly) { + AddInterface(kClientAddr); + allocator().set_flags(PORTALLOCATOR_ENABLE_SHARED_SOCKET); + allocator().SetCandidateFilter(CF_HOST); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(2U, candidates_.size()); // Host UDP/TCP candidates only. + EXPECT_EQ(2U, ports_.size()); // UDP/TCP ports only. + for (const Candidate& candidate : candidates_) { + EXPECT_EQ(std::string(LOCAL_PORT_TYPE), candidate.type()); + } +} + +// Host is behind the NAT. +TEST_F(BasicPortAllocatorTest, TestCandidateFilterWithReflexiveOnly) { + AddInterface(kPrivateAddr); + ResetWithStunServerAndNat(kStunAddr); + + allocator().set_flags(PORTALLOCATOR_ENABLE_SHARED_SOCKET); + allocator().SetCandidateFilter(CF_REFLEXIVE); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Host is behind NAT, no private address will be exposed. Hence only UDP + // port with STUN candidate will be sent outside. + EXPECT_EQ(1U, candidates_.size()); // Only STUN candidate. + EXPECT_EQ(1U, ports_.size()); // Only UDP port will be in ready state. + EXPECT_EQ(std::string(STUN_PORT_TYPE), candidates_[0].type()); + EXPECT_EQ( + candidates_[0].related_address(), + rtc::EmptySocketAddressWithFamily(candidates_[0].address().family())); +} + +// Host is not behind the NAT. +TEST_F(BasicPortAllocatorTest, TestCandidateFilterWithReflexiveOnlyAndNoNAT) { + AddInterface(kClientAddr); + allocator().set_flags(PORTALLOCATOR_ENABLE_SHARED_SOCKET); + allocator().SetCandidateFilter(CF_REFLEXIVE); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Host has a public address, both UDP and TCP candidates will be exposed. + EXPECT_EQ(2U, candidates_.size()); // Local UDP + TCP candidate. + EXPECT_EQ(2U, ports_.size()); // UDP and TCP ports will be in ready state. + for (const Candidate& candidate : candidates_) { + EXPECT_EQ(std::string(LOCAL_PORT_TYPE), candidate.type()); + } +} + +// Test that we get the same ufrag and pwd for all candidates. +TEST_F(BasicPortAllocatorTest, TestEnableSharedUfrag) { + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "stun", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); + EXPECT_EQ(3U, ports_.size()); + for (const Candidate& candidate : candidates_) { + EXPECT_EQ(kIceUfrag0, candidate.username()); + EXPECT_EQ(kIcePwd0, candidate.password()); + } +} + +// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port +// is allocated for udp and stun. Also verify there is only one candidate +// (local) if stun candidate is same as local candidate, which will be the case +// in a public network like the below test. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithoutNat) { + AddInterface(kClientAddr); + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(2U, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(2U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); +} + +// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port +// is allocated for udp and stun. In this test we should expect both stun and +// local candidates as client behind a nat. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithNat) { + AddInterface(kClientAddr); + ResetWithStunServerAndNat(kStunAddr); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + ASSERT_EQ(2U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "stun", "udp", + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0))); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); +} + +// Test TURN port in shared socket mode with UDP and TCP TURN server addresses. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithoutNatUsingTurn) { + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddInterface(kClientAddr); + allocator_.reset(new BasicPortAllocator( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()))); + allocator_->Initialize(); + + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + + allocator_->set_step_delay(kMinimumStepDelay); + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + ASSERT_EQ(3U, candidates_.size()); + ASSERT_EQ(3U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + EXPECT_TRUE(HasCandidate(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); +} + +// Test that if the turn port prune policy is PRUNE_BASED_ON_PRIORITY, TCP TURN +// port will not be used if UDP TurnPort is used, given that TCP TURN port +// becomes ready first. +TEST_F(BasicPortAllocatorTest, + TestUdpTurnPortPrunesTcpTurnPortWithTcpPortReadyFirst) { + // UDP has longer delay than TCP so that TCP TURN port becomes ready first. + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 200); + virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntAddr, 100); + + TestTurnPortPrunesWithUdpAndTcpPorts(webrtc::PRUNE_BASED_ON_PRIORITY, + true /* tcp_pruned */); +} + +// Test that if turn port prune policy is PRUNE_BASED_ON_PRIORITY, TCP TURN port +// will not be used if UDP TurnPort is used, given that UDP TURN port becomes +// ready first. +TEST_F(BasicPortAllocatorTest, + TestUdpTurnPortPrunesTcpTurnPortsWithUdpPortReadyFirst) { + // UDP has shorter delay than TCP so that UDP TURN port becomes ready first. + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 100); + virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntAddr, 200); + + TestTurnPortPrunesWithUdpAndTcpPorts(webrtc::PRUNE_BASED_ON_PRIORITY, + true /* tcp_pruned */); +} + +// Test that if turn_port_prune policy is KEEP_FIRST_READY, the first ready port +// will be kept regardless of the priority. +TEST_F(BasicPortAllocatorTest, + TestUdpTurnPortPrunesTcpTurnPortIfUdpReadyFirst) { + // UDP has shorter delay than TCP so that UDP TURN port becomes ready first. + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 100); + virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntAddr, 200); + + TestTurnPortPrunesWithUdpAndTcpPorts(webrtc::KEEP_FIRST_READY, + true /* tcp_pruned */); +} + +// Test that if turn_port_prune policy is KEEP_FIRST_READY, the first ready port +// will be kept regardless of the priority. +TEST_F(BasicPortAllocatorTest, + TestTcpTurnPortPrunesUdpTurnPortIfTcpReadyFirst) { + // UDP has longer delay than TCP so that TCP TURN port becomes ready first. + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 200); + virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntAddr, 100); + + TestTurnPortPrunesWithUdpAndTcpPorts(webrtc::KEEP_FIRST_READY, + false /* tcp_pruned */); +} + +// Tests that if turn port prune policy is PRUNE_BASED_ON_PRIORITY, IPv4 +// TurnPort will not be used if IPv6 TurnPort is used, given that IPv4 TURN port +// becomes ready first. +TEST_F(BasicPortAllocatorTest, + TestIPv6TurnPortPrunesIPv4TurnPortWithIPv4PortReadyFirst) { + // IPv6 has longer delay than IPv4, so that IPv4 TURN port becomes ready + // first. + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 100); + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntIPv6Addr, 200); + + TestIPv6TurnPortPrunesIPv4TurnPort(); +} + +// Tests that if turn port prune policy is PRUNE_BASED_ON_PRIORITY, IPv4 +// TurnPort will not be used if IPv6 TurnPort is used, given that IPv6 TURN port +// becomes ready first. +TEST_F(BasicPortAllocatorTest, + TestIPv6TurnPortPrunesIPv4TurnPortWithIPv6PortReadyFirst) { + // IPv6 has longer delay than IPv4, so that IPv6 TURN port becomes ready + // first. + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 200); + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntIPv6Addr, 100); + + TestIPv6TurnPortPrunesIPv4TurnPort(); +} + +// Tests that if turn port prune policy is PRUNE_BASED_ON_PRIORITY, each network +// interface will has its own set of TurnPorts based on their priorities, in the +// default case where no transit delay is set. +TEST_F(BasicPortAllocatorTest, TestEachInterfaceHasItsOwnTurnPortsNoDelay) { + TestEachInterfaceHasItsOwnTurnPorts(); +} + +// Tests that if turn port prune policy is PRUNE_BASED_ON_PRIORITY, each network +// interface will has its own set of TurnPorts based on their priorities, given +// that IPv4/TCP TURN port becomes ready first. +TEST_F(BasicPortAllocatorTest, + TestEachInterfaceHasItsOwnTurnPortsWithTcpIPv4ReadyFirst) { + // IPv6/UDP have longer delay than IPv4/TCP, so that IPv4/TCP TURN port + // becomes ready last. + virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntAddr, 10); + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntAddr, 100); + virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntIPv6Addr, 20); + virtual_socket_server()->SetDelayOnAddress(kTurnUdpIntIPv6Addr, 300); + + TestEachInterfaceHasItsOwnTurnPorts(); +} + +// Testing DNS resolve for the TURN server, this will test AllocationSequence +// handling the unresolved address signal from TurnPort. +// TODO(pthatcher): Make this test work with SIMULATED_WAIT. It +// appears that it doesn't currently because of the DNS look up not +// using the fake clock. +TEST_F(BasicPortAllocatorTestWithRealClock, + TestSharedSocketWithServerAddressResolve) { + // This test relies on a real query for "localhost", so it won't work on an + // IPv6-only machine. + MAYBE_SKIP_IPV4; + turn_server_.AddInternalSocket(rtc::SocketAddress("127.0.0.1", 3478), + PROTO_UDP); + AddInterface(kClientAddr); + allocator_.reset(new BasicPortAllocator( + &network_manager_, + std::make_unique<rtc::BasicPacketSocketFactory>(fss_.get()))); + allocator_->Initialize(); + RelayServerConfig turn_server; + RelayCredentials credentials(kTurnUsername, kTurnPassword); + turn_server.credentials = credentials; + turn_server.ports.push_back( + ProtocolAddress(rtc::SocketAddress("localhost", 3478), PROTO_UDP)); + allocator_->AddTurnServerForTesting(turn_server); + + allocator_->set_step_delay(kMinimumStepDelay); + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + EXPECT_EQ_WAIT(2U, ports_.size(), kDefaultAllocationTimeout); +} + +// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled only one port +// is allocated for udp/stun/turn. In this test we should expect all local, +// stun and turn candidates. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithNatUsingTurn) { + AddInterface(kClientAddr); + ResetWithStunServerAndNat(kStunAddr); + + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + ASSERT_EQ(2U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "stun", "udp", + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0))); + EXPECT_TRUE(HasCandidate(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + // Local port will be created first and then TURN port. + // TODO(deadbeef): This isn't something the BasicPortAllocator API contract + // guarantees... + EXPECT_EQ(2U, ports_[0]->Candidates().size()); + EXPECT_EQ(1U, ports_[1]->Candidates().size()); +} + +// Test that when PORTALLOCATOR_ENABLE_SHARED_SOCKET is enabled and the TURN +// server is also used as the STUN server, we should get 'local', 'stun', and +// 'relay' candidates. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithNatUsingTurnAsStun) { + AddInterface(kClientAddr); + // Use an empty SocketAddress to add a NAT without STUN server. + ResetWithStunServerAndNat(SocketAddress()); + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + // Must set the step delay to 0 to make sure the relay allocation phase is + // started before the STUN candidates are obtained, so that the STUN binding + // response is processed when both StunPort and TurnPort exist to reproduce + // webrtc issue 3537. + allocator_->set_step_delay(0); + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + Candidate stun_candidate; + EXPECT_TRUE(FindCandidate(candidates_, "stun", "udp", + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0), + &stun_candidate)); + EXPECT_TRUE(HasCandidateWithRelatedAddr( + candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0), + stun_candidate.address())); + + // Local port will be created first and then TURN port. + // TODO(deadbeef): This isn't something the BasicPortAllocator API contract + // guarantees... + EXPECT_EQ(2U, ports_[0]->Candidates().size()); + EXPECT_EQ(1U, ports_[1]->Candidates().size()); +} + +// Test that when only a TCP TURN server is available, we do NOT use it as +// a UDP STUN server, as this could leak our IP address. Thus we should only +// expect two ports, a UDPPort and TurnPort. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithNatUsingTurnTcpOnly) { + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddInterface(kClientAddr); + ResetWithStunServerAndNat(rtc::SocketAddress()); + AddTurnServers(rtc::SocketAddress(), kTurnTcpIntAddr); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(2U, candidates_.size()); + ASSERT_EQ(2U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0))); + EXPECT_EQ(1U, ports_[0]->Candidates().size()); + EXPECT_EQ(1U, ports_[1]->Candidates().size()); +} + +// Test that even when PORTALLOCATOR_ENABLE_SHARED_SOCKET is NOT enabled, the +// TURN server is used as the STUN server and we get 'local', 'stun', and +// 'relay' candidates. +// TODO(deadbeef): Remove this test when support for non-shared socket mode +// is removed. +TEST_F(BasicPortAllocatorTest, TestNonSharedSocketWithNatUsingTurnAsStun) { + AddInterface(kClientAddr); + // Use an empty SocketAddress to add a NAT without STUN server. + ResetWithStunServerAndNat(SocketAddress()); + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_flags(allocator().flags() | PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3U, candidates_.size()); + ASSERT_EQ(3U, ports_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + Candidate stun_candidate; + EXPECT_TRUE(FindCandidate(candidates_, "stun", "udp", + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0), + &stun_candidate)); + Candidate turn_candidate; + EXPECT_TRUE(FindCandidate(candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0), + &turn_candidate)); + // Not using shared socket, so the STUN request's server reflexive address + // should be different than the TURN request's server reflexive address. + EXPECT_NE(turn_candidate.related_address(), stun_candidate.address()); + + EXPECT_EQ(1U, ports_[0]->Candidates().size()); + EXPECT_EQ(1U, ports_[1]->Candidates().size()); + EXPECT_EQ(1U, ports_[2]->Candidates().size()); +} + +// Test that even when both a STUN and TURN server are configured, the TURN +// server is used as a STUN server and we get a 'stun' candidate. +TEST_F(BasicPortAllocatorTest, TestSharedSocketWithNatUsingTurnAndStun) { + AddInterface(kClientAddr); + // Configure with STUN server but destroy it, so we can ensure that it's + // the TURN server actually being used as a STUN server. + ResetWithStunServerAndNat(kStunAddr); + stun_server_.reset(); + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + + ASSERT_EQ_SIMULATED_WAIT(3U, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + Candidate stun_candidate; + EXPECT_TRUE(FindCandidate(candidates_, "stun", "udp", + rtc::SocketAddress(kNatUdpAddr.ipaddr(), 0), + &stun_candidate)); + EXPECT_TRUE(HasCandidateWithRelatedAddr( + candidates_, "relay", "udp", + rtc::SocketAddress(kTurnUdpExtAddr.ipaddr(), 0), + stun_candidate.address())); + + // Don't bother waiting for STUN timeout, since we already verified + // that we got a STUN candidate from the TURN server. +} + +// This test verifies when PORTALLOCATOR_ENABLE_SHARED_SOCKET flag is enabled +// and fail to generate STUN candidate, local UDP candidate is generated +// properly. +TEST_F(BasicPortAllocatorTest, TestSharedSocketNoUdpAllowed) { + allocator().set_flags(allocator().flags() | PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + fss_->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kClientAddr); + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(1U, ports_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(1U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + // STUN timeout is 9.5sec. We need to wait to get candidate done signal. + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, kStunTimeoutMs, + fake_clock); + EXPECT_EQ(1U, candidates_.size()); +} + +// Test that when the NetworkManager doesn't have permission to enumerate +// adapters, the PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION is specified +// automatically. +TEST_F(BasicPortAllocatorTest, TestNetworkPermissionBlocked) { + network_manager_.set_default_local_addresses(kPrivateAddr.ipaddr(), + rtc::IPAddress()); + network_manager_.set_enumeration_permission( + rtc::NetworkManager::ENUMERATION_BLOCKED); + allocator().set_flags(allocator().flags() | PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + EXPECT_EQ(0U, + allocator_->flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + EXPECT_EQ(0U, session_->flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION); + session_->StartGettingPorts(); + EXPECT_EQ_SIMULATED_WAIT(1U, ports_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(1U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kPrivateAddr)); + EXPECT_NE(0U, session_->flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION); +} + +// This test verifies allocator can use IPv6 addresses along with IPv4. +TEST_F(BasicPortAllocatorTest, TestEnableIPv6Addresses) { + allocator().set_flags(allocator().flags() | PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_ENABLE_IPV6 | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + AddInterface(kClientIPv6Addr); + AddInterface(kClientAddr); + allocator_->set_step_delay(kMinimumStepDelay); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(4U, ports_.size()); + EXPECT_EQ(4U, candidates_.size()); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientAddr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "tcp", kClientAddr)); +} + +TEST_F(BasicPortAllocatorTest, TestStopGettingPorts) { + AddInterface(kClientAddr); + allocator_->set_step_delay(kDefaultStepDelay); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(2U, candidates_.size(), 1000, fake_clock); + EXPECT_EQ(2U, ports_.size()); + session_->StopGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, 1000, fake_clock); + + // After stopping getting ports, adding a new interface will not start + // getting ports again. + allocator_->set_step_delay(kMinimumStepDelay); + candidates_.clear(); + ports_.clear(); + candidate_allocation_done_ = false; + network_manager_.AddInterface(kClientAddr2); + SIMULATED_WAIT(false, 1000, fake_clock); + EXPECT_EQ(0U, candidates_.size()); + EXPECT_EQ(0U, ports_.size()); +} + +TEST_F(BasicPortAllocatorTest, TestClearGettingPorts) { + AddInterface(kClientAddr); + allocator_->set_step_delay(kDefaultStepDelay); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_EQ_SIMULATED_WAIT(2U, candidates_.size(), 1000, fake_clock); + EXPECT_EQ(2U, ports_.size()); + session_->ClearGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, 1000, fake_clock); + + // After clearing getting ports, adding a new interface will start getting + // ports again. + allocator_->set_step_delay(kMinimumStepDelay); + candidates_.clear(); + ports_.clear(); + candidate_allocation_done_ = false; + network_manager_.AddInterface(kClientAddr2); + ASSERT_EQ_SIMULATED_WAIT(2U, candidates_.size(), 1000, fake_clock); + EXPECT_EQ(2U, ports_.size()); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); +} + +// Test that the ports and candidates are updated with new ufrag/pwd/etc. when +// a pooled session is taken out of the pool. +TEST_F(BasicPortAllocatorTest, TestTransportInformationUpdated) { + AddInterface(kClientAddr); + int pool_size = 1; + allocator_->SetConfiguration(allocator_->stun_servers(), + allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE); + const PortAllocatorSession* peeked_session = allocator_->GetPooledSession(); + ASSERT_NE(nullptr, peeked_session); + EXPECT_EQ_SIMULATED_WAIT(true, peeked_session->CandidatesAllocationDone(), + kDefaultAllocationTimeout, fake_clock); + // Expect that when TakePooledSession is called, + // UpdateTransportInformationInternal will be called and the + // BasicPortAllocatorSession will update the ufrag/pwd of ports and + // candidates. + session_ = + allocator_->TakePooledSession(kContentName, 1, kIceUfrag0, kIcePwd0); + ASSERT_NE(nullptr, session_.get()); + auto ready_ports = session_->ReadyPorts(); + auto candidates = session_->ReadyCandidates(); + EXPECT_FALSE(ready_ports.empty()); + EXPECT_FALSE(candidates.empty()); + for (const PortInterface* port_interface : ready_ports) { + const Port* port = static_cast<const Port*>(port_interface); + EXPECT_EQ(kContentName, port->content_name()); + EXPECT_EQ(1, port->component()); + EXPECT_EQ(kIceUfrag0, port->username_fragment()); + EXPECT_EQ(kIcePwd0, port->password()); + } + for (const Candidate& candidate : candidates) { + EXPECT_EQ(1, candidate.component()); + EXPECT_EQ(kIceUfrag0, candidate.username()); + EXPECT_EQ(kIcePwd0, candidate.password()); + } +} + +// Test that a new candidate filter takes effect even on already-gathered +// candidates. +TEST_F(BasicPortAllocatorTest, TestSetCandidateFilterAfterCandidatesGathered) { + AddInterface(kClientAddr); + int pool_size = 1; + allocator_->SetConfiguration(allocator_->stun_servers(), + allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE); + const PortAllocatorSession* peeked_session = allocator_->GetPooledSession(); + ASSERT_NE(nullptr, peeked_session); + EXPECT_EQ_SIMULATED_WAIT(true, peeked_session->CandidatesAllocationDone(), + kDefaultAllocationTimeout, fake_clock); + size_t initial_candidates_size = peeked_session->ReadyCandidates().size(); + size_t initial_ports_size = peeked_session->ReadyPorts().size(); + allocator_->SetCandidateFilter(CF_RELAY); + // Assume that when TakePooledSession is called, the candidate filter will be + // applied to the pooled session. This is tested by PortAllocatorTest. + session_ = + allocator_->TakePooledSession(kContentName, 1, kIceUfrag0, kIcePwd0); + ASSERT_NE(nullptr, session_.get()); + auto candidates = session_->ReadyCandidates(); + auto ports = session_->ReadyPorts(); + // Sanity check that the number of candidates and ports decreased. + EXPECT_GT(initial_candidates_size, candidates.size()); + EXPECT_GT(initial_ports_size, ports.size()); + for (const PortInterface* port : ports) { + // Expect only relay ports. + EXPECT_EQ(RELAY_PORT_TYPE, port->Type()); + } + for (const Candidate& candidate : candidates) { + // Expect only relay candidates now that the filter is applied. + EXPECT_EQ(std::string(RELAY_PORT_TYPE), candidate.type()); + // Expect that the raddr is emptied due to the CF_RELAY filter. + EXPECT_EQ(candidate.related_address(), + rtc::EmptySocketAddressWithFamily(candidate.address().family())); + } +} + +// Test that candidates that do not match a previous candidate filter can be +// surfaced if they match the new one after setting the filter value. +TEST_F(BasicPortAllocatorTest, + SurfaceNewCandidatesAfterSetCandidateFilterToAddCandidateTypes) { + // We would still surface a host candidate if the IP is public, even though it + // is disabled by the candidate filter. See + // BasicPortAllocatorSession::CheckCandidateFilter. Use the private address so + // that the srflx candidate is not equivalent to the host candidate. + AddInterface(kPrivateAddr); + ResetWithStunServerAndNat(kStunAddr); + + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + allocator_->SetCandidateFilter(CF_NONE); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_TRUE(candidates_.empty()); + EXPECT_TRUE(ports_.empty()); + + // Surface the relay candidate previously gathered but not signaled. + session_->SetCandidateFilter(CF_RELAY); + ASSERT_EQ_SIMULATED_WAIT(1u, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(RELAY_PORT_TYPE, candidates_.back().type()); + EXPECT_EQ(1u, ports_.size()); + + // Surface the srflx candidate previously gathered but not signaled. + session_->SetCandidateFilter(CF_RELAY | CF_REFLEXIVE); + ASSERT_EQ_SIMULATED_WAIT(2u, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(STUN_PORT_TYPE, candidates_.back().type()); + EXPECT_EQ(2u, ports_.size()); + + // Surface the srflx candidate previously gathered but not signaled. + session_->SetCandidateFilter(CF_ALL); + ASSERT_EQ_SIMULATED_WAIT(3u, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(LOCAL_PORT_TYPE, candidates_.back().type()); + EXPECT_EQ(2u, ports_.size()); +} + +// This is a similar test as +// SurfaceNewCandidatesAfterSetCandidateFilterToAddCandidateTypes, and we +// test the transitions for which the new filter value is not a super set of the +// previous value. +TEST_F( + BasicPortAllocatorTest, + SurfaceNewCandidatesAfterSetCandidateFilterToAllowDifferentCandidateTypes) { + // We would still surface a host candidate if the IP is public, even though it + // is disabled by the candidate filter. See + // BasicPortAllocatorSession::CheckCandidateFilter. Use the private address so + // that the srflx candidate is not equivalent to the host candidate. + AddInterface(kPrivateAddr); + ResetWithStunServerAndNat(kStunAddr); + + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + allocator_->SetCandidateFilter(CF_NONE); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_TRUE(candidates_.empty()); + EXPECT_TRUE(ports_.empty()); + + // Surface the relay candidate previously gathered but not signaled. + session_->SetCandidateFilter(CF_RELAY); + EXPECT_EQ_SIMULATED_WAIT(1u, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(RELAY_PORT_TYPE, candidates_.back().type()); + EXPECT_EQ(1u, ports_.size()); + + // Surface the srflx candidate previously gathered but not signaled. + session_->SetCandidateFilter(CF_REFLEXIVE); + EXPECT_EQ_SIMULATED_WAIT(2u, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(STUN_PORT_TYPE, candidates_.back().type()); + EXPECT_EQ(2u, ports_.size()); + + // Surface the host candidate previously gathered but not signaled. + session_->SetCandidateFilter(CF_HOST); + EXPECT_EQ_SIMULATED_WAIT(3u, candidates_.size(), kDefaultAllocationTimeout, + fake_clock); + EXPECT_EQ(LOCAL_PORT_TYPE, candidates_.back().type()); + // We use a shared socket and cricket::UDPPort handles the srflx candidate. + EXPECT_EQ(2u, ports_.size()); +} + +// Test that after an allocation session has stopped getting ports, changing the +// candidate filter to allow new types of gathered candidates does not surface +// any candidate. +TEST_F(BasicPortAllocatorTest, + NoCandidateSurfacedWhenUpdatingCandidateFilterIfSessionStopped) { + AddInterface(kPrivateAddr); + ResetWithStunServerAndNat(kStunAddr); + + AddTurnServers(kTurnUdpIntAddr, rtc::SocketAddress()); + + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET | + PORTALLOCATOR_DISABLE_TCP); + + allocator_->SetCandidateFilter(CF_NONE); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + auto test_invariants = [this]() { + EXPECT_TRUE(candidates_.empty()); + EXPECT_TRUE(ports_.empty()); + }; + + test_invariants(); + + session_->StopGettingPorts(); + + session_->SetCandidateFilter(CF_RELAY); + SIMULATED_WAIT(false, kDefaultAllocationTimeout, fake_clock); + test_invariants(); + + session_->SetCandidateFilter(CF_RELAY | CF_REFLEXIVE); + SIMULATED_WAIT(false, kDefaultAllocationTimeout, fake_clock); + test_invariants(); + + session_->SetCandidateFilter(CF_ALL); + SIMULATED_WAIT(false, kDefaultAllocationTimeout, fake_clock); + test_invariants(); +} + +TEST_F(BasicPortAllocatorTest, SetStunKeepaliveIntervalForPorts) { + const int pool_size = 1; + const int expected_stun_keepalive_interval = 123; + AddInterface(kClientAddr); + allocator_->SetConfiguration( + allocator_->stun_servers(), allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE, nullptr, expected_stun_keepalive_interval); + auto* pooled_session = allocator_->GetPooledSession(); + ASSERT_NE(nullptr, pooled_session); + EXPECT_EQ_SIMULATED_WAIT(true, pooled_session->CandidatesAllocationDone(), + kDefaultAllocationTimeout, fake_clock); + CheckStunKeepaliveIntervalOfAllReadyPorts(pooled_session, + expected_stun_keepalive_interval); +} + +TEST_F(BasicPortAllocatorTest, + ChangeStunKeepaliveIntervalForPortsAfterInitialConfig) { + const int pool_size = 1; + AddInterface(kClientAddr); + allocator_->SetConfiguration( + allocator_->stun_servers(), allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE, nullptr, 123 /* stun keepalive interval */); + auto* pooled_session = allocator_->GetPooledSession(); + ASSERT_NE(nullptr, pooled_session); + EXPECT_EQ_SIMULATED_WAIT(true, pooled_session->CandidatesAllocationDone(), + kDefaultAllocationTimeout, fake_clock); + const int expected_stun_keepalive_interval = 321; + allocator_->SetConfiguration( + allocator_->stun_servers(), allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE, nullptr, expected_stun_keepalive_interval); + CheckStunKeepaliveIntervalOfAllReadyPorts(pooled_session, + expected_stun_keepalive_interval); +} + +TEST_F(BasicPortAllocatorTest, + SetStunKeepaliveIntervalForPortsWithSharedSocket) { + const int pool_size = 1; + const int expected_stun_keepalive_interval = 123; + AddInterface(kClientAddr); + allocator_->set_flags(allocator().flags() | + PORTALLOCATOR_ENABLE_SHARED_SOCKET); + allocator_->SetConfiguration( + allocator_->stun_servers(), allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE, nullptr, expected_stun_keepalive_interval); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + CheckStunKeepaliveIntervalOfAllReadyPorts(session_.get(), + expected_stun_keepalive_interval); +} + +TEST_F(BasicPortAllocatorTest, + SetStunKeepaliveIntervalForPortsWithoutSharedSocket) { + const int pool_size = 1; + const int expected_stun_keepalive_interval = 123; + AddInterface(kClientAddr); + allocator_->set_flags(allocator().flags() & + ~(PORTALLOCATOR_ENABLE_SHARED_SOCKET)); + allocator_->SetConfiguration( + allocator_->stun_servers(), allocator_->turn_servers(), pool_size, + webrtc::NO_PRUNE, nullptr, expected_stun_keepalive_interval); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + CheckStunKeepaliveIntervalOfAllReadyPorts(session_.get(), + expected_stun_keepalive_interval); +} + +TEST_F(BasicPortAllocatorTest, IceRegatheringMetricsLoggedWhenNetworkChanges) { + // Only test local ports to simplify test. + ResetWithNoServersOrNat(); + AddInterface(kClientAddr, "test_net0"); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + candidate_allocation_done_ = false; + AddInterface(kClientAddr2, "test_net1"); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_METRIC_EQ(1, + webrtc::metrics::NumEvents( + "WebRTC.PeerConnection.IceRegatheringReason", + static_cast<int>(IceRegatheringReason::NETWORK_CHANGE))); +} + +// Test that when an mDNS responder is present, the local address of a host +// candidate is concealed by an mDNS hostname and the related address of a srflx +// candidate is set to 0.0.0.0 or ::0. +TEST_F(BasicPortAllocatorTest, HostCandidateAddressIsReplacedByHostname) { + // Default config uses GTURN and no NAT, so replace that with the + // desired setup (NAT, STUN server, TURN server, UDP/TCP). + ResetWithStunServerAndNat(kStunAddr); + turn_server_.AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP); + AddTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + AddTurnServers(kTurnUdpIntIPv6Addr, kTurnTcpIntIPv6Addr); + + ASSERT_EQ(&network_manager_, allocator().network_manager()); + network_manager_.set_mdns_responder( + std::make_unique<webrtc::FakeMdnsResponder>(rtc::Thread::Current())); + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(5u, candidates_.size()); + int num_host_udp_candidates = 0; + int num_host_tcp_candidates = 0; + int num_srflx_candidates = 0; + int num_relay_candidates = 0; + for (const auto& candidate : candidates_) { + const auto& raddr = candidate.related_address(); + + if (candidate.type() == LOCAL_PORT_TYPE) { + EXPECT_FALSE(candidate.address().hostname().empty()); + EXPECT_TRUE(raddr.IsNil()); + if (candidate.protocol() == UDP_PROTOCOL_NAME) { + ++num_host_udp_candidates; + } else { + ++num_host_tcp_candidates; + } + } else if (candidate.type() == STUN_PORT_TYPE) { + // For a srflx candidate, the related address should be set to 0.0.0.0 or + // ::0 + EXPECT_TRUE(IPIsAny(raddr.ipaddr())); + EXPECT_EQ(raddr.port(), 0); + ++num_srflx_candidates; + } else if (candidate.type() == RELAY_PORT_TYPE) { + EXPECT_EQ(kNatUdpAddr.ipaddr(), raddr.ipaddr()); + EXPECT_EQ(kNatUdpAddr.family(), raddr.family()); + ++num_relay_candidates; + } else { + // prflx candidates are not expected + FAIL(); + } + } + EXPECT_EQ(1, num_host_udp_candidates); + EXPECT_EQ(1, num_host_tcp_candidates); + EXPECT_EQ(1, num_srflx_candidates); + EXPECT_EQ(2, num_relay_candidates); +} + +TEST_F(BasicPortAllocatorTest, TestUseTurnServerAsStunSever) { + ServerAddresses stun_servers; + stun_servers.insert(kStunAddr); + PortConfiguration port_config(stun_servers, "", ""); + RelayServerConfig turn_servers = + CreateTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + port_config.AddRelay(turn_servers); + + EXPECT_EQ(2U, port_config.StunServers().size()); +} + +TEST_F(BasicPortAllocatorTest, TestDoNotUseTurnServerAsStunSever) { + webrtc::test::ScopedKeyValueConfig field_trials( + "WebRTC-UseTurnServerAsStunServer/Disabled/"); + ServerAddresses stun_servers; + stun_servers.insert(kStunAddr); + PortConfiguration port_config(stun_servers, "" /* user_name */, + "" /* password */, &field_trials); + RelayServerConfig turn_servers = + CreateTurnServers(kTurnUdpIntAddr, kTurnTcpIntAddr); + port_config.AddRelay(turn_servers); + + EXPECT_EQ(1U, port_config.StunServers().size()); +} + +// Test that candidates from different servers get assigned a unique local +// preference (the middle 16 bits of the priority) +TEST_F(BasicPortAllocatorTest, AssignsUniqueLocalPreferencetoRelayCandidates) { + allocator_->SetCandidateFilter(CF_RELAY); + allocator_->AddTurnServerForTesting( + CreateTurnServers(kTurnUdpIntAddr, SocketAddress())); + allocator_->AddTurnServerForTesting( + CreateTurnServers(kTurnUdpIntAddr, SocketAddress())); + allocator_->AddTurnServerForTesting( + CreateTurnServers(kTurnUdpIntAddr, SocketAddress())); + + AddInterface(kClientAddr); + ASSERT_TRUE(CreateSession(ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + ASSERT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + EXPECT_EQ(3u, candidates_.size()); + EXPECT_GT((candidates_[0].priority() >> 8) & 0xFFFF, + (candidates_[1].priority() >> 8) & 0xFFFF); + EXPECT_GT((candidates_[1].priority() >> 8) & 0xFFFF, + (candidates_[2].priority() >> 8) & 0xFFFF); +} + +// Test that no more than allocator.max_ipv6_networks() IPv6 networks are used +// to gather candidates. +TEST_F(BasicPortAllocatorTest, TwoIPv6AreSelectedBecauseOfMaxIpv6Limit) { + rtc::Network wifi1("wifi1", "Test NetworkAdapter 1", kClientIPv6Addr.ipaddr(), + 64, rtc::ADAPTER_TYPE_WIFI); + rtc::Network ethe1("ethe1", "Test NetworkAdapter 2", + kClientIPv6Addr2.ipaddr(), 64, rtc::ADAPTER_TYPE_ETHERNET); + rtc::Network wifi2("wifi2", "Test NetworkAdapter 3", + kClientIPv6Addr3.ipaddr(), 64, rtc::ADAPTER_TYPE_WIFI); + std::vector<const rtc::Network*> networks = {&wifi1, ðe1, &wifi2}; + + // Ensure that only 2 interfaces were selected. + EXPECT_EQ(2U, BasicPortAllocatorSession::SelectIPv6Networks( + networks, /*max_ipv6_networks=*/2) + .size()); +} + +// Test that if the number of available IPv6 networks is less than +// allocator.max_ipv6_networks(), all IPv6 networks will be selected. +TEST_F(BasicPortAllocatorTest, AllIPv6AreSelected) { + rtc::Network wifi1("wifi1", "Test NetworkAdapter 1", kClientIPv6Addr.ipaddr(), + 64, rtc::ADAPTER_TYPE_WIFI); + rtc::Network ethe1("ethe1", "Test NetworkAdapter 2", + kClientIPv6Addr2.ipaddr(), 64, rtc::ADAPTER_TYPE_ETHERNET); + std::vector<const rtc::Network*> networks = {&wifi1, ðe1}; + + // Ensure that all 2 interfaces were selected. + EXPECT_EQ(2U, BasicPortAllocatorSession::SelectIPv6Networks( + networks, /*max_ipv6_networks=*/3) + .size()); +} + +// If there are some IPv6 networks with different types, diversify IPv6 +// networks. +TEST_F(BasicPortAllocatorTest, TwoIPv6WifiAreSelectedIfThereAreTwo) { + rtc::Network wifi1("wifi1", "Test NetworkAdapter 1", kClientIPv6Addr.ipaddr(), + 64, rtc::ADAPTER_TYPE_WIFI); + rtc::Network ethe1("ethe1", "Test NetworkAdapter 2", + kClientIPv6Addr2.ipaddr(), 64, rtc::ADAPTER_TYPE_ETHERNET); + rtc::Network ethe2("ethe2", "Test NetworkAdapter 3", + kClientIPv6Addr3.ipaddr(), 64, rtc::ADAPTER_TYPE_ETHERNET); + rtc::Network unknown1("unknown1", "Test NetworkAdapter 4", + kClientIPv6Addr2.ipaddr(), 64, + rtc::ADAPTER_TYPE_UNKNOWN); + rtc::Network cell1("cell1", "Test NetworkAdapter 5", + kClientIPv6Addr3.ipaddr(), 64, + rtc::ADAPTER_TYPE_CELLULAR_4G); + std::vector<const rtc::Network*> networks = {&wifi1, ðe1, ðe2, + &unknown1, &cell1}; + + networks = BasicPortAllocatorSession::SelectIPv6Networks( + networks, /*max_ipv6_networks=*/4); + + EXPECT_EQ(4U, networks.size()); + // Ensure the expected 4 interfaces (wifi1, ethe1, cell1, unknown1) were + // selected. + EXPECT_TRUE(HasNetwork(networks, wifi1)); + EXPECT_TRUE(HasNetwork(networks, ethe1)); + EXPECT_TRUE(HasNetwork(networks, cell1)); + EXPECT_TRUE(HasNetwork(networks, unknown1)); +} + +// If there are some IPv6 networks with the same type, select them because there +// is no other option. +TEST_F(BasicPortAllocatorTest, IPv6WithSameTypeAreSelectedIfNoOtherOption) { + // Add 5 cellular interfaces + rtc::Network cell1("cell1", "Test NetworkAdapter 1", kClientIPv6Addr.ipaddr(), + 64, rtc::ADAPTER_TYPE_CELLULAR_2G); + rtc::Network cell2("cell2", "Test NetworkAdapter 2", + kClientIPv6Addr2.ipaddr(), 64, + rtc::ADAPTER_TYPE_CELLULAR_3G); + rtc::Network cell3("cell3", "Test NetworkAdapter 3", + kClientIPv6Addr3.ipaddr(), 64, + rtc::ADAPTER_TYPE_CELLULAR_4G); + rtc::Network cell4("cell4", "Test NetworkAdapter 4", + kClientIPv6Addr2.ipaddr(), 64, + rtc::ADAPTER_TYPE_CELLULAR_5G); + rtc::Network cell5("cell5", "Test NetworkAdapter 5", + kClientIPv6Addr3.ipaddr(), 64, + rtc::ADAPTER_TYPE_CELLULAR_3G); + std::vector<const rtc::Network*> networks = {&cell1, &cell2, &cell3, &cell4, + &cell5}; + + // Ensure that 4 interfaces were selected. + EXPECT_EQ(4U, BasicPortAllocatorSession::SelectIPv6Networks( + networks, /*max_ipv6_networks=*/4) + .size()); +} + +TEST_F(BasicPortAllocatorTest, IPv6EthernetHasHigherPriorityThanWifi) { + rtc::Network wifi1("wifi1", "Test NetworkAdapter 1", kClientIPv6Addr.ipaddr(), + 64, rtc::ADAPTER_TYPE_WIFI); + rtc::Network ethe1("ethe1", "Test NetworkAdapter 2", + kClientIPv6Addr2.ipaddr(), 64, rtc::ADAPTER_TYPE_ETHERNET); + rtc::Network wifi2("wifi2", "Test NetworkAdapter 3", + kClientIPv6Addr3.ipaddr(), 64, rtc::ADAPTER_TYPE_WIFI); + std::vector<const rtc::Network*> networks = {&wifi1, ðe1, &wifi2}; + + networks = BasicPortAllocatorSession::SelectIPv6Networks( + networks, /*max_ipv6_networks=*/1); + + EXPECT_EQ(1U, networks.size()); + // Ensure ethe1 was selected. + EXPECT_TRUE(HasNetwork(networks, ethe1)); +} + +TEST_F(BasicPortAllocatorTest, IPv6EtherAndWifiHaveHigherPriorityThanOthers) { + rtc::Network cell1("cell1", "Test NetworkAdapter 1", kClientIPv6Addr.ipaddr(), + 64, rtc::ADAPTER_TYPE_CELLULAR_3G); + rtc::Network ethe1("ethe1", "Test NetworkAdapter 2", + kClientIPv6Addr2.ipaddr(), 64, rtc::ADAPTER_TYPE_ETHERNET); + rtc::Network wifi1("wifi1", "Test NetworkAdapter 3", + kClientIPv6Addr3.ipaddr(), 64, rtc::ADAPTER_TYPE_WIFI); + rtc::Network unknown("unknown", "Test NetworkAdapter 4", + kClientIPv6Addr2.ipaddr(), 64, + rtc::ADAPTER_TYPE_UNKNOWN); + rtc::Network vpn1("vpn1", "Test NetworkAdapter 5", kClientIPv6Addr3.ipaddr(), + 64, rtc::ADAPTER_TYPE_VPN); + std::vector<const rtc::Network*> networks = {&cell1, ðe1, &wifi1, &unknown, + &vpn1}; + + networks = BasicPortAllocatorSession::SelectIPv6Networks( + networks, /*max_ipv6_networks=*/2); + + EXPECT_EQ(2U, networks.size()); + // Ensure ethe1 and wifi1 were selected. + EXPECT_TRUE(HasNetwork(networks, wifi1)); + EXPECT_TRUE(HasNetwork(networks, ethe1)); +} + +// Do not change the default IPv6 selection behavior if +// IPv6NetworkResolutionFixes is disabled. +TEST_F(BasicPortAllocatorTest, + NotDiversifyIPv6NetworkTypesIfIPv6NetworkResolutionFixesDisabled) { + webrtc::test::ScopedKeyValueConfig field_trials( + field_trials_, "WebRTC-IPv6NetworkResolutionFixes/Disabled/"); + // Add three IPv6 network interfaces, but tell the allocator to only use two. + allocator().set_max_ipv6_networks(2); + AddInterface(kClientIPv6Addr, "ethe1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "ethe2", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr3, "wifi1", rtc::ADAPTER_TYPE_WIFI); + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + EXPECT_EQ(2U, candidates_.size()); + // Wifi1 was not selected because it comes after ethe1 and ethe2. + EXPECT_FALSE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr3)); +} + +// Do not change the default IPv6 selection behavior if +// IPv6NetworkResolutionFixes is enabled but DiversifyIpv6Interfaces is not +// enabled. +TEST_F(BasicPortAllocatorTest, + NotDiversifyIPv6NetworkTypesIfDiversifyIpv6InterfacesDisabled) { + webrtc::test::ScopedKeyValueConfig field_trials( + field_trials_, + "WebRTC-IPv6NetworkResolutionFixes/" + "Enabled,DiversifyIpv6Interfaces:false/"); + // Add three IPv6 network interfaces, but tell the allocator to only use two. + allocator().set_max_ipv6_networks(2); + AddInterface(kClientIPv6Addr, "ethe1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "ethe2", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr3, "wifi1", rtc::ADAPTER_TYPE_WIFI); + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + EXPECT_EQ(2U, candidates_.size()); + // Wifi1 was not selected because it comes after ethe1 and ethe2. + EXPECT_FALSE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr3)); +} + +TEST_F(BasicPortAllocatorTest, + Select2DifferentIntefacesIfDiversifyIpv6InterfacesEnabled) { + webrtc::test::ScopedKeyValueConfig field_trials( + field_trials_, + "WebRTC-IPv6NetworkResolutionFixes/" + "Enabled,DiversifyIpv6Interfaces:true/"); + allocator().set_max_ipv6_networks(2); + AddInterface(kClientIPv6Addr, "ethe1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "ethe2", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr3, "wifi1", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr4, "wifi2", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr5, "cell1", rtc::ADAPTER_TYPE_CELLULAR_3G); + + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + EXPECT_EQ(2U, candidates_.size()); + // ethe1 and wifi1 were selected. + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr3)); +} + +TEST_F(BasicPortAllocatorTest, + Select3DifferentIntefacesIfDiversifyIpv6InterfacesEnabled) { + webrtc::test::ScopedKeyValueConfig field_trials( + field_trials_, + "WebRTC-IPv6NetworkResolutionFixes/" + "Enabled,DiversifyIpv6Interfaces:true/"); + allocator().set_max_ipv6_networks(3); + AddInterface(kClientIPv6Addr, "ethe1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "ethe2", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr3, "wifi1", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr4, "wifi2", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr5, "cell1", rtc::ADAPTER_TYPE_CELLULAR_3G); + + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + EXPECT_EQ(3U, candidates_.size()); + // ethe1, wifi1, and cell1 were selected. + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr3)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr5)); +} + +TEST_F(BasicPortAllocatorTest, + Select4DifferentIntefacesIfDiversifyIpv6InterfacesEnabled) { + webrtc::test::ScopedKeyValueConfig field_trials( + field_trials_, + "WebRTC-IPv6NetworkResolutionFixes/" + "Enabled,DiversifyIpv6Interfaces:true/"); + allocator().set_max_ipv6_networks(4); + AddInterface(kClientIPv6Addr, "ethe1", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr2, "ethe2", rtc::ADAPTER_TYPE_ETHERNET); + AddInterface(kClientIPv6Addr3, "wifi1", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr4, "wifi2", rtc::ADAPTER_TYPE_WIFI); + AddInterface(kClientIPv6Addr5, "cell1", rtc::ADAPTER_TYPE_CELLULAR_3G); + + // To simplify the test, only gather UDP host candidates. + allocator().set_flags(PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_DISABLE_TCP | + PORTALLOCATOR_DISABLE_STUN | + PORTALLOCATOR_DISABLE_RELAY | + PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); + + ASSERT_TRUE(CreateSession(cricket::ICE_CANDIDATE_COMPONENT_RTP)); + session_->StartGettingPorts(); + EXPECT_TRUE_SIMULATED_WAIT(candidate_allocation_done_, + kDefaultAllocationTimeout, fake_clock); + + EXPECT_EQ(4U, candidates_.size()); + // ethe1, ethe2, wifi1, and cell1 were selected. + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr2)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr3)); + EXPECT_TRUE(HasCandidate(candidates_, "local", "udp", kClientIPv6Addr5)); +} + +} // namespace cricket diff --git a/third_party/libwebrtc/p2p/client/relay_port_factory_interface.h b/third_party/libwebrtc/p2p/client/relay_port_factory_interface.h new file mode 100644 index 0000000000..edfca3697b --- /dev/null +++ b/third_party/libwebrtc/p2p/client/relay_port_factory_interface.h @@ -0,0 +1,72 @@ +/* + * Copyright 2017 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#ifndef P2P_CLIENT_RELAY_PORT_FACTORY_INTERFACE_H_ +#define P2P_CLIENT_RELAY_PORT_FACTORY_INTERFACE_H_ + +#include <memory> +#include <string> + +#include "p2p/base/port_interface.h" +#include "rtc_base/ref_count.h" + +namespace rtc { +class AsyncPacketSocket; +class Network; +class PacketSocketFactory; +class Thread; +} // namespace rtc + +namespace webrtc { +class TurnCustomizer; +class FieldTrialsView; +} // namespace webrtc + +namespace cricket { +class Port; +struct ProtocolAddress; +struct RelayServerConfig; + +// A struct containing arguments to RelayPortFactory::Create() +struct CreateRelayPortArgs { + rtc::Thread* network_thread; + rtc::PacketSocketFactory* socket_factory; + const rtc::Network* network; + const ProtocolAddress* server_address; + const RelayServerConfig* config; + std::string username; + std::string password; + webrtc::TurnCustomizer* turn_customizer = nullptr; + const webrtc::FieldTrialsView* field_trials = nullptr; + // Relative priority of candidates from this TURN server in relation + // to the candidates from other servers. Required because ICE priorities + // need to be unique. + int relative_priority = 0; +}; + +// A factory for creating RelayPort's. +class RelayPortFactoryInterface { + public: + virtual ~RelayPortFactoryInterface() {} + + // This variant is used for UDP connection to the relay server + // using a already existing shared socket. + virtual std::unique_ptr<Port> Create(const CreateRelayPortArgs& args, + rtc::AsyncPacketSocket* udp_socket) = 0; + + // This variant is used for the other cases. + virtual std::unique_ptr<Port> Create(const CreateRelayPortArgs& args, + int min_port, + int max_port) = 0; +}; + +} // namespace cricket + +#endif // P2P_CLIENT_RELAY_PORT_FACTORY_INTERFACE_H_ diff --git a/third_party/libwebrtc/p2p/client/turn_port_factory.cc b/third_party/libwebrtc/p2p/client/turn_port_factory.cc new file mode 100644 index 0000000000..555387dbbf --- /dev/null +++ b/third_party/libwebrtc/p2p/client/turn_port_factory.cc @@ -0,0 +1,45 @@ +/* + * Copyright 2017 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "p2p/client/turn_port_factory.h" + +#include <memory> +#include <utility> + +#include "p2p/base/port_allocator.h" +#include "p2p/base/turn_port.h" + +namespace cricket { + +TurnPortFactory::~TurnPortFactory() {} + +std::unique_ptr<Port> TurnPortFactory::Create( + const CreateRelayPortArgs& args, + rtc::AsyncPacketSocket* udp_socket) { + auto port = TurnPort::Create(args, udp_socket); + if (!port) + return nullptr; + port->SetTlsCertPolicy(args.config->tls_cert_policy); + port->SetTurnLoggingId(args.config->turn_logging_id); + return std::move(port); +} + +std::unique_ptr<Port> TurnPortFactory::Create(const CreateRelayPortArgs& args, + int min_port, + int max_port) { + auto port = TurnPort::Create(args, min_port, max_port); + if (!port) + return nullptr; + port->SetTlsCertPolicy(args.config->tls_cert_policy); + port->SetTurnLoggingId(args.config->turn_logging_id); + return std::move(port); +} + +} // namespace cricket diff --git a/third_party/libwebrtc/p2p/client/turn_port_factory.h b/third_party/libwebrtc/p2p/client/turn_port_factory.h new file mode 100644 index 0000000000..abb1f67fe9 --- /dev/null +++ b/third_party/libwebrtc/p2p/client/turn_port_factory.h @@ -0,0 +1,37 @@ +/* + * Copyright 2017 The WebRTC Project Authors. All rights reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#ifndef P2P_CLIENT_TURN_PORT_FACTORY_H_ +#define P2P_CLIENT_TURN_PORT_FACTORY_H_ + +#include <memory> + +#include "p2p/base/port.h" +#include "p2p/client/relay_port_factory_interface.h" +#include "rtc_base/async_packet_socket.h" + +namespace cricket { + +// This is a RelayPortFactory that produces TurnPorts. +class TurnPortFactory : public RelayPortFactoryInterface { + public: + ~TurnPortFactory() override; + + std::unique_ptr<Port> Create(const CreateRelayPortArgs& args, + rtc::AsyncPacketSocket* udp_socket) override; + + std::unique_ptr<Port> Create(const CreateRelayPortArgs& args, + int min_port, + int max_port) override; +}; + +} // namespace cricket + +#endif // P2P_CLIENT_TURN_PORT_FACTORY_H_ |