• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "p2p/client/basic_port_allocator.h"
12 
13 #include <algorithm>
14 #include <functional>
15 #include <set>
16 #include <string>
17 #include <utility>
18 #include <vector>
19 
20 #include "absl/algorithm/container.h"
21 #include "p2p/base/basic_packet_socket_factory.h"
22 #include "p2p/base/port.h"
23 #include "p2p/base/stun_port.h"
24 #include "p2p/base/tcp_port.h"
25 #include "p2p/base/turn_port.h"
26 #include "p2p/base/udp_port.h"
27 #include "rtc_base/checks.h"
28 #include "rtc_base/helpers.h"
29 #include "rtc_base/logging.h"
30 #include "system_wrappers/include/field_trial.h"
31 #include "system_wrappers/include/metrics.h"
32 
33 using rtc::CreateRandomId;
34 
35 namespace cricket {
36 namespace {
37 
38 enum {
39   MSG_CONFIG_START,
40   MSG_CONFIG_READY,
41   MSG_ALLOCATE,
42   MSG_ALLOCATION_PHASE,
43   MSG_SEQUENCEOBJECTS_CREATED,
44   MSG_CONFIG_STOP,
45 };
46 
47 const int PHASE_UDP = 0;
48 const int PHASE_RELAY = 1;
49 const int PHASE_TCP = 2;
50 
51 const int kNumPhases = 3;
52 
53 // Gets protocol priority: UDP > TCP > SSLTCP == TLS.
GetProtocolPriority(cricket::ProtocolType protocol)54 int GetProtocolPriority(cricket::ProtocolType protocol) {
55   switch (protocol) {
56     case cricket::PROTO_UDP:
57       return 2;
58     case cricket::PROTO_TCP:
59       return 1;
60     case cricket::PROTO_SSLTCP:
61     case cricket::PROTO_TLS:
62       return 0;
63     default:
64       RTC_NOTREACHED();
65       return 0;
66   }
67 }
68 // Gets address family priority:  IPv6 > IPv4 > Unspecified.
GetAddressFamilyPriority(int ip_family)69 int GetAddressFamilyPriority(int ip_family) {
70   switch (ip_family) {
71     case AF_INET6:
72       return 2;
73     case AF_INET:
74       return 1;
75     default:
76       RTC_NOTREACHED();
77       return 0;
78   }
79 }
80 
81 // Returns positive if a is better, negative if b is better, and 0 otherwise.
ComparePort(const cricket::Port * a,const cricket::Port * b)82 int ComparePort(const cricket::Port* a, const cricket::Port* b) {
83   int a_protocol = GetProtocolPriority(a->GetProtocol());
84   int b_protocol = GetProtocolPriority(b->GetProtocol());
85   int cmp_protocol = a_protocol - b_protocol;
86   if (cmp_protocol != 0) {
87     return cmp_protocol;
88   }
89 
90   int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
91   int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
92   return a_family - b_family;
93 }
94 
95 struct NetworkFilter {
96   using Predicate = std::function<bool(rtc::Network*)>;
NetworkFiltercricket::__anon8d73b1370111::NetworkFilter97   NetworkFilter(Predicate pred, const std::string& description)
98       : predRemain([pred](rtc::Network* network) { return !pred(network); }),
99         description(description) {}
100   Predicate predRemain;
101   const std::string description;
102 };
103 
104 using NetworkList = rtc::NetworkManager::NetworkList;
FilterNetworks(NetworkList * networks,NetworkFilter filter)105 void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
106   auto start_to_remove =
107       std::partition(networks->begin(), networks->end(), filter.predRemain);
108   if (start_to_remove == networks->end()) {
109     return;
110   }
111   RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
112   for (auto it = start_to_remove; it != networks->end(); ++it) {
113     RTC_LOG(INFO) << (*it)->ToString();
114   }
115   networks->erase(start_to_remove, networks->end());
116 }
117 
IsAllowedByCandidateFilter(const Candidate & c,uint32_t filter)118 bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) {
119   // When binding to any address, before sending packets out, the getsockname
120   // returns all 0s, but after sending packets, it'll be the NIC used to
121   // send. All 0s is not a valid ICE candidate address and should be filtered
122   // out.
123   if (c.address().IsAnyIP()) {
124     return false;
125   }
126 
127   if (c.type() == RELAY_PORT_TYPE) {
128     return ((filter & CF_RELAY) != 0);
129   } else if (c.type() == STUN_PORT_TYPE) {
130     return ((filter & CF_REFLEXIVE) != 0);
131   } else if (c.type() == LOCAL_PORT_TYPE) {
132     if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
133       // We allow host candidates if the filter allows server-reflexive
134       // candidates and the candidate is a public IP. Because we don't generate
135       // server-reflexive candidates if they have the same IP as the host
136       // candidate (i.e. when the host candidate is a public IP), filtering to
137       // only server-reflexive candidates won't work right when the host
138       // candidates have public IPs.
139       return true;
140     }
141 
142     return ((filter & CF_HOST) != 0);
143   }
144   return false;
145 }
146 
147 }  // namespace
148 
149 const uint32_t DISABLE_ALL_PHASES =
150     PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
151     PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
152 
153 // BasicPortAllocator
BasicPortAllocator(rtc::NetworkManager * network_manager,rtc::PacketSocketFactory * socket_factory,webrtc::TurnCustomizer * customizer,RelayPortFactoryInterface * relay_port_factory)154 BasicPortAllocator::BasicPortAllocator(
155     rtc::NetworkManager* network_manager,
156     rtc::PacketSocketFactory* socket_factory,
157     webrtc::TurnCustomizer* customizer,
158     RelayPortFactoryInterface* relay_port_factory)
159     : network_manager_(network_manager), socket_factory_(socket_factory) {
160   InitRelayPortFactory(relay_port_factory);
161   RTC_DCHECK(relay_port_factory_ != nullptr);
162   RTC_DCHECK(network_manager_ != nullptr);
163   RTC_DCHECK(socket_factory_ != nullptr);
164   SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
165                    webrtc::NO_PRUNE, customizer);
166 }
167 
BasicPortAllocator(rtc::NetworkManager * network_manager)168 BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
169     : network_manager_(network_manager), socket_factory_(nullptr) {
170   InitRelayPortFactory(nullptr);
171   RTC_DCHECK(relay_port_factory_ != nullptr);
172   RTC_DCHECK(network_manager_ != nullptr);
173 }
174 
BasicPortAllocator(rtc::NetworkManager * network_manager,const ServerAddresses & stun_servers)175 BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
176                                        const ServerAddresses& stun_servers)
177     : BasicPortAllocator(network_manager,
178                          /*socket_factory=*/nullptr,
179                          stun_servers) {}
180 
BasicPortAllocator(rtc::NetworkManager * network_manager,rtc::PacketSocketFactory * socket_factory,const ServerAddresses & stun_servers)181 BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
182                                        rtc::PacketSocketFactory* socket_factory,
183                                        const ServerAddresses& stun_servers)
184     : network_manager_(network_manager), socket_factory_(socket_factory) {
185   InitRelayPortFactory(nullptr);
186   RTC_DCHECK(relay_port_factory_ != nullptr);
187   SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0,
188                    webrtc::NO_PRUNE, nullptr);
189 }
190 
OnIceRegathering(PortAllocatorSession * session,IceRegatheringReason reason)191 void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
192                                           IceRegatheringReason reason) {
193   // If the session has not been taken by an active channel, do not report the
194   // metric.
195   for (auto& allocator_session : pooled_sessions()) {
196     if (allocator_session.get() == session) {
197       return;
198     }
199   }
200 
201   RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
202                             static_cast<int>(reason),
203                             static_cast<int>(IceRegatheringReason::MAX_VALUE));
204 }
205 
~BasicPortAllocator()206 BasicPortAllocator::~BasicPortAllocator() {
207   CheckRunOnValidThreadIfInitialized();
208   // Our created port allocator sessions depend on us, so destroy our remaining
209   // pooled sessions before anything else.
210   DiscardCandidatePool();
211 }
212 
SetNetworkIgnoreMask(int network_ignore_mask)213 void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
214   // TODO(phoglund): implement support for other types than loopback.
215   // See https://code.google.com/p/webrtc/issues/detail?id=4288.
216   // Then remove set_network_ignore_list from NetworkManager.
217   CheckRunOnValidThreadIfInitialized();
218   network_ignore_mask_ = network_ignore_mask;
219 }
220 
CreateSessionInternal(const std::string & content_name,int component,const std::string & ice_ufrag,const std::string & ice_pwd)221 PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
222     const std::string& content_name,
223     int component,
224     const std::string& ice_ufrag,
225     const std::string& ice_pwd) {
226   CheckRunOnValidThreadAndInitialized();
227   PortAllocatorSession* session = new BasicPortAllocatorSession(
228       this, content_name, component, ice_ufrag, ice_pwd);
229   session->SignalIceRegathering.connect(this,
230                                         &BasicPortAllocator::OnIceRegathering);
231   return session;
232 }
233 
AddTurnServer(const RelayServerConfig & turn_server)234 void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
235   CheckRunOnValidThreadAndInitialized();
236   std::vector<RelayServerConfig> new_turn_servers = turn_servers();
237   new_turn_servers.push_back(turn_server);
238   SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
239                    turn_port_prune_policy(), turn_customizer());
240 }
241 
InitRelayPortFactory(RelayPortFactoryInterface * relay_port_factory)242 void BasicPortAllocator::InitRelayPortFactory(
243     RelayPortFactoryInterface* relay_port_factory) {
244   if (relay_port_factory != nullptr) {
245     relay_port_factory_ = relay_port_factory;
246   } else {
247     default_relay_port_factory_.reset(new TurnPortFactory());
248     relay_port_factory_ = default_relay_port_factory_.get();
249   }
250 }
251 
252 // BasicPortAllocatorSession
BasicPortAllocatorSession(BasicPortAllocator * allocator,const std::string & content_name,int component,const std::string & ice_ufrag,const std::string & ice_pwd)253 BasicPortAllocatorSession::BasicPortAllocatorSession(
254     BasicPortAllocator* allocator,
255     const std::string& content_name,
256     int component,
257     const std::string& ice_ufrag,
258     const std::string& ice_pwd)
259     : PortAllocatorSession(content_name,
260                            component,
261                            ice_ufrag,
262                            ice_pwd,
263                            allocator->flags()),
264       allocator_(allocator),
265       network_thread_(rtc::Thread::Current()),
266       socket_factory_(allocator->socket_factory()),
267       allocation_started_(false),
268       network_manager_started_(false),
269       allocation_sequences_created_(false),
270       turn_port_prune_policy_(allocator->turn_port_prune_policy()) {
271   allocator_->network_manager()->SignalNetworksChanged.connect(
272       this, &BasicPortAllocatorSession::OnNetworksChanged);
273   allocator_->network_manager()->StartUpdating();
274 }
275 
~BasicPortAllocatorSession()276 BasicPortAllocatorSession::~BasicPortAllocatorSession() {
277   RTC_DCHECK_RUN_ON(network_thread_);
278   allocator_->network_manager()->StopUpdating();
279   if (network_thread_ != NULL)
280     network_thread_->Clear(this);
281 
282   for (uint32_t i = 0; i < sequences_.size(); ++i) {
283     // AllocationSequence should clear it's map entry for turn ports before
284     // ports are destroyed.
285     sequences_[i]->Clear();
286   }
287 
288   std::vector<PortData>::iterator it;
289   for (it = ports_.begin(); it != ports_.end(); it++)
290     delete it->port();
291 
292   for (uint32_t i = 0; i < configs_.size(); ++i)
293     delete configs_[i];
294 
295   for (uint32_t i = 0; i < sequences_.size(); ++i)
296     delete sequences_[i];
297 }
298 
allocator()299 BasicPortAllocator* BasicPortAllocatorSession::allocator() {
300   RTC_DCHECK_RUN_ON(network_thread_);
301   return allocator_;
302 }
303 
SetCandidateFilter(uint32_t filter)304 void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
305   RTC_DCHECK_RUN_ON(network_thread_);
306   if (filter == candidate_filter_) {
307     return;
308   }
309   uint32_t prev_filter = candidate_filter_;
310   candidate_filter_ = filter;
311   for (PortData& port_data : ports_) {
312     if (port_data.error() || port_data.pruned()) {
313       continue;
314     }
315     PortData::State cur_state = port_data.state();
316     bool found_signalable_candidate = false;
317     bool found_pairable_candidate = false;
318     cricket::Port* port = port_data.port();
319     for (const auto& c : port->Candidates()) {
320       if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) &&
321           IsAllowedByCandidateFilter(c, filter)) {
322         // This candidate was not signaled because of not matching the previous
323         // filter (see OnCandidateReady below). Let the Port to fire the signal
324         // again.
325         //
326         // Note that
327         //  1) we would need the Port to enter the state of in-progress of
328         //     gathering to have candidates signaled;
329         //
330         //  2) firing the signal would also let the session set the port ready
331         //     if needed, so that we could form candidate pairs with candidates
332         //     from this port;
333         //
334         //  *  See again OnCandidateReady below for 1) and 2).
335         //
336         //  3) we only try to resurface candidates if we have not stopped
337         //     getting ports, which is always true for the continual gathering.
338         if (!found_signalable_candidate) {
339           found_signalable_candidate = true;
340           port_data.set_state(PortData::STATE_INPROGRESS);
341         }
342         port->SignalCandidateReady(port, c);
343       }
344 
345       if (CandidatePairable(c, port)) {
346         found_pairable_candidate = true;
347       }
348     }
349     // Restore the previous state.
350     port_data.set_state(cur_state);
351     // Setting a filter may cause a ready port to become non-ready
352     // if it no longer has any pairable candidates.
353     //
354     // Note that we only set for the negative case here, since a port would be
355     // set to have pairable candidates when it signals a ready candidate, which
356     // requires the port is still in the progress of gathering/surfacing
357     // candidates, and would be done in the firing of the signal above.
358     if (!found_pairable_candidate) {
359       port_data.set_has_pairable_candidate(false);
360     }
361   }
362 }
363 
StartGettingPorts()364 void BasicPortAllocatorSession::StartGettingPorts() {
365   RTC_DCHECK_RUN_ON(network_thread_);
366   state_ = SessionState::GATHERING;
367   if (!socket_factory_) {
368     owned_socket_factory_.reset(
369         new rtc::BasicPacketSocketFactory(network_thread_));
370     socket_factory_ = owned_socket_factory_.get();
371   }
372 
373   network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
374 
375   RTC_LOG(LS_INFO) << "Start getting ports with turn_port_prune_policy "
376                    << turn_port_prune_policy_;
377 }
378 
StopGettingPorts()379 void BasicPortAllocatorSession::StopGettingPorts() {
380   RTC_DCHECK_RUN_ON(network_thread_);
381   ClearGettingPorts();
382   // Note: this must be called after ClearGettingPorts because both may set the
383   // session state and we should set the state to STOPPED.
384   state_ = SessionState::STOPPED;
385 }
386 
ClearGettingPorts()387 void BasicPortAllocatorSession::ClearGettingPorts() {
388   RTC_DCHECK_RUN_ON(network_thread_);
389   network_thread_->Clear(this, MSG_ALLOCATE);
390   for (uint32_t i = 0; i < sequences_.size(); ++i) {
391     sequences_[i]->Stop();
392   }
393   network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
394   state_ = SessionState::CLEARED;
395 }
396 
IsGettingPorts()397 bool BasicPortAllocatorSession::IsGettingPorts() {
398   RTC_DCHECK_RUN_ON(network_thread_);
399   return state_ == SessionState::GATHERING;
400 }
401 
IsCleared() const402 bool BasicPortAllocatorSession::IsCleared() const {
403   RTC_DCHECK_RUN_ON(network_thread_);
404   return state_ == SessionState::CLEARED;
405 }
406 
IsStopped() const407 bool BasicPortAllocatorSession::IsStopped() const {
408   RTC_DCHECK_RUN_ON(network_thread_);
409   return state_ == SessionState::STOPPED;
410 }
411 
GetFailedNetworks()412 std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
413   RTC_DCHECK_RUN_ON(network_thread_);
414 
415   std::vector<rtc::Network*> networks = GetNetworks();
416 
417   // A network interface may have both IPv4 and IPv6 networks. Only if
418   // neither of the networks has any connections, the network interface
419   // is considered failed and need to be regathered on.
420   std::set<std::string> networks_with_connection;
421   for (const PortData& data : ports_) {
422     Port* port = data.port();
423     if (!port->connections().empty()) {
424       networks_with_connection.insert(port->Network()->name());
425     }
426   }
427 
428   networks.erase(
429       std::remove_if(networks.begin(), networks.end(),
430                      [networks_with_connection](rtc::Network* network) {
431                        // If a network does not have any connection, it is
432                        // considered failed.
433                        return networks_with_connection.find(network->name()) !=
434                               networks_with_connection.end();
435                      }),
436       networks.end());
437   return networks;
438 }
439 
RegatherOnFailedNetworks()440 void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
441   RTC_DCHECK_RUN_ON(network_thread_);
442 
443   // Find the list of networks that have no connection.
444   std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
445   if (failed_networks.empty()) {
446     return;
447   }
448 
449   RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
450 
451   // Mark a sequence as "network failed" if its network is in the list of failed
452   // networks, so that it won't be considered as equivalent when the session
453   // regathers ports and candidates.
454   for (AllocationSequence* sequence : sequences_) {
455     if (!sequence->network_failed() &&
456         absl::c_linear_search(failed_networks, sequence->network())) {
457       sequence->set_network_failed();
458     }
459   }
460 
461   bool disable_equivalent_phases = true;
462   Regather(failed_networks, disable_equivalent_phases,
463            IceRegatheringReason::NETWORK_FAILURE);
464 }
465 
Regather(const std::vector<rtc::Network * > & networks,bool disable_equivalent_phases,IceRegatheringReason reason)466 void BasicPortAllocatorSession::Regather(
467     const std::vector<rtc::Network*>& networks,
468     bool disable_equivalent_phases,
469     IceRegatheringReason reason) {
470   RTC_DCHECK_RUN_ON(network_thread_);
471   // Remove ports from being used locally and send signaling to remove
472   // the candidates on the remote side.
473   std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
474   if (!ports_to_prune.empty()) {
475     RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
476     PrunePortsAndRemoveCandidates(ports_to_prune);
477   }
478 
479   if (allocation_started_ && network_manager_started_ && !IsStopped()) {
480     SignalIceRegathering(this, reason);
481 
482     DoAllocate(disable_equivalent_phases);
483   }
484 }
485 
GetCandidateStatsFromReadyPorts(CandidateStatsList * candidate_stats_list) const486 void BasicPortAllocatorSession::GetCandidateStatsFromReadyPorts(
487     CandidateStatsList* candidate_stats_list) const {
488   auto ports = ReadyPorts();
489   for (auto* port : ports) {
490     auto candidates = port->Candidates();
491     for (const auto& candidate : candidates) {
492       CandidateStats candidate_stats(allocator_->SanitizeCandidate(candidate));
493       port->GetStunStats(&candidate_stats.stun_stats);
494       candidate_stats_list->push_back(std::move(candidate_stats));
495     }
496   }
497 }
498 
SetStunKeepaliveIntervalForReadyPorts(const absl::optional<int> & stun_keepalive_interval)499 void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
500     const absl::optional<int>& stun_keepalive_interval) {
501   RTC_DCHECK_RUN_ON(network_thread_);
502   auto ports = ReadyPorts();
503   for (PortInterface* port : ports) {
504     // The port type and protocol can be used to identify different subclasses
505     // of Port in the current implementation. Note that a TCPPort has the type
506     // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
507     if (port->Type() == STUN_PORT_TYPE ||
508         (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
509       static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
510           stun_keepalive_interval);
511     }
512   }
513 }
514 
ReadyPorts() const515 std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
516   RTC_DCHECK_RUN_ON(network_thread_);
517   std::vector<PortInterface*> ret;
518   for (const PortData& data : ports_) {
519     if (data.ready()) {
520       ret.push_back(data.port());
521     }
522   }
523   return ret;
524 }
525 
ReadyCandidates() const526 std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
527   RTC_DCHECK_RUN_ON(network_thread_);
528   std::vector<Candidate> candidates;
529   for (const PortData& data : ports_) {
530     if (!data.ready()) {
531       continue;
532     }
533     GetCandidatesFromPort(data, &candidates);
534   }
535   return candidates;
536 }
537 
GetCandidatesFromPort(const PortData & data,std::vector<Candidate> * candidates) const538 void BasicPortAllocatorSession::GetCandidatesFromPort(
539     const PortData& data,
540     std::vector<Candidate>* candidates) const {
541   RTC_DCHECK_RUN_ON(network_thread_);
542   RTC_CHECK(candidates != nullptr);
543   for (const Candidate& candidate : data.port()->Candidates()) {
544     if (!CheckCandidateFilter(candidate)) {
545       continue;
546     }
547     candidates->push_back(allocator_->SanitizeCandidate(candidate));
548   }
549 }
550 
MdnsObfuscationEnabled() const551 bool BasicPortAllocator::MdnsObfuscationEnabled() const {
552   return network_manager()->GetMdnsResponder() != nullptr;
553 }
554 
CandidatesAllocationDone() const555 bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
556   RTC_DCHECK_RUN_ON(network_thread_);
557   // Done only if all required AllocationSequence objects
558   // are created.
559   if (!allocation_sequences_created_) {
560     return false;
561   }
562 
563   // Check that all port allocation sequences are complete (not running).
564   if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
565         return sequence->state() == AllocationSequence::kRunning;
566       })) {
567     return false;
568   }
569 
570   // If all allocated ports are no longer gathering, session must have got all
571   // expected candidates. Session will trigger candidates allocation complete
572   // signal.
573   return absl::c_none_of(
574       ports_, [](const PortData& port) { return port.inprogress(); });
575 }
576 
OnMessage(rtc::Message * message)577 void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
578   switch (message->message_id) {
579     case MSG_CONFIG_START:
580       GetPortConfigurations();
581       break;
582     case MSG_CONFIG_READY:
583       OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
584       break;
585     case MSG_ALLOCATE:
586       OnAllocate();
587       break;
588     case MSG_SEQUENCEOBJECTS_CREATED:
589       OnAllocationSequenceObjectsCreated();
590       break;
591     case MSG_CONFIG_STOP:
592       OnConfigStop();
593       break;
594     default:
595       RTC_NOTREACHED();
596   }
597 }
598 
UpdateIceParametersInternal()599 void BasicPortAllocatorSession::UpdateIceParametersInternal() {
600   RTC_DCHECK_RUN_ON(network_thread_);
601   for (PortData& port : ports_) {
602     port.port()->set_content_name(content_name());
603     port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
604   }
605 }
606 
GetPortConfigurations()607 void BasicPortAllocatorSession::GetPortConfigurations() {
608   RTC_DCHECK_RUN_ON(network_thread_);
609 
610   PortConfiguration* config =
611       new PortConfiguration(allocator_->stun_servers(), username(), password());
612 
613   for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
614     config->AddRelay(turn_server);
615   }
616   ConfigReady(config);
617 }
618 
ConfigReady(PortConfiguration * config)619 void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
620   RTC_DCHECK_RUN_ON(network_thread_);
621   network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
622 }
623 
624 // Adds a configuration to the list.
OnConfigReady(PortConfiguration * config)625 void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
626   RTC_DCHECK_RUN_ON(network_thread_);
627   if (config) {
628     configs_.push_back(config);
629   }
630 
631   AllocatePorts();
632 }
633 
OnConfigStop()634 void BasicPortAllocatorSession::OnConfigStop() {
635   RTC_DCHECK_RUN_ON(network_thread_);
636 
637   // If any of the allocated ports have not completed the candidates allocation,
638   // mark those as error. Since session doesn't need any new candidates
639   // at this stage of the allocation, it's safe to discard any new candidates.
640   bool send_signal = false;
641   for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
642        ++it) {
643     if (it->inprogress()) {
644       // Updating port state to error, which didn't finish allocating candidates
645       // yet.
646       it->set_state(PortData::STATE_ERROR);
647       send_signal = true;
648     }
649   }
650 
651   // Did we stop any running sequences?
652   for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
653        it != sequences_.end() && !send_signal; ++it) {
654     if ((*it)->state() == AllocationSequence::kStopped) {
655       send_signal = true;
656     }
657   }
658 
659   // If we stopped anything that was running, send a done signal now.
660   if (send_signal) {
661     MaybeSignalCandidatesAllocationDone();
662   }
663 }
664 
AllocatePorts()665 void BasicPortAllocatorSession::AllocatePorts() {
666   RTC_DCHECK_RUN_ON(network_thread_);
667   network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
668 }
669 
OnAllocate()670 void BasicPortAllocatorSession::OnAllocate() {
671   RTC_DCHECK_RUN_ON(network_thread_);
672 
673   if (network_manager_started_ && !IsStopped()) {
674     bool disable_equivalent_phases = true;
675     DoAllocate(disable_equivalent_phases);
676   }
677 
678   allocation_started_ = true;
679 }
680 
GetNetworks()681 std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
682   RTC_DCHECK_RUN_ON(network_thread_);
683   std::vector<rtc::Network*> networks;
684   rtc::NetworkManager* network_manager = allocator_->network_manager();
685   RTC_DCHECK(network_manager != nullptr);
686   // If the network permission state is BLOCKED, we just act as if the flag has
687   // been passed in.
688   if (network_manager->enumeration_permission() ==
689       rtc::NetworkManager::ENUMERATION_BLOCKED) {
690     set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
691   }
692   // If the adapter enumeration is disabled, we'll just bind to any address
693   // instead of specific NIC. This is to ensure the same routing for http
694   // traffic by OS is also used here to avoid any local or public IP leakage
695   // during stun process.
696   if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
697     network_manager->GetAnyAddressNetworks(&networks);
698   } else {
699     network_manager->GetNetworks(&networks);
700     // If network enumeration fails, use the ANY address as a fallback, so we
701     // can at least try gathering candidates using the default route chosen by
702     // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
703     // set, we'll use ANY address candidates either way.
704     if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
705       network_manager->GetAnyAddressNetworks(&networks);
706     }
707   }
708   // Filter out link-local networks if needed.
709   if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
710     NetworkFilter link_local_filter(
711         [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
712         "link-local");
713     FilterNetworks(&networks, link_local_filter);
714   }
715   // Do some more filtering, depending on the network ignore mask and "disable
716   // costly networks" flag.
717   NetworkFilter ignored_filter(
718       [this](rtc::Network* network) {
719         return allocator_->network_ignore_mask() & network->type();
720       },
721       "ignored");
722   FilterNetworks(&networks, ignored_filter);
723   if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
724     uint16_t lowest_cost = rtc::kNetworkCostMax;
725     for (rtc::Network* network : networks) {
726       // Don't determine the lowest cost from a link-local network.
727       // On iOS, a device connected to the computer will get a link-local
728       // network for communicating with the computer, however this network can't
729       // be used to connect to a peer outside the network.
730       if (rtc::IPIsLinkLocal(network->GetBestIP())) {
731         continue;
732       }
733       lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
734     }
735     NetworkFilter costly_filter(
736         [lowest_cost](rtc::Network* network) {
737           return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
738         },
739         "costly");
740     FilterNetworks(&networks, costly_filter);
741   }
742   // Lastly, if we have a limit for the number of IPv6 network interfaces (by
743   // default, it's 5), remove networks to ensure that limit is satisfied.
744   //
745   // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
746   // networks, we could try to choose a set that's "most likely to work". It's
747   // hard to define what that means though; it's not just "lowest cost".
748   // Alternatively, we could just focus on making our ICE pinging logic smarter
749   // such that this filtering isn't necessary in the first place.
750   int ipv6_networks = 0;
751   for (auto it = networks.begin(); it != networks.end();) {
752     if ((*it)->prefix().family() == AF_INET6) {
753       if (ipv6_networks >= allocator_->max_ipv6_networks()) {
754         it = networks.erase(it);
755         continue;
756       } else {
757         ++ipv6_networks;
758       }
759     }
760     ++it;
761   }
762   return networks;
763 }
764 
765 // For each network, see if we have a sequence that covers it already.  If not,
766 // create a new sequence to create the appropriate ports.
DoAllocate(bool disable_equivalent)767 void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
768   RTC_DCHECK_RUN_ON(network_thread_);
769   bool done_signal_needed = false;
770   std::vector<rtc::Network*> networks = GetNetworks();
771   if (networks.empty()) {
772     RTC_LOG(LS_WARNING)
773         << "Machine has no networks; no ports will be allocated";
774     done_signal_needed = true;
775   } else {
776     RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
777     PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
778     for (uint32_t i = 0; i < networks.size(); ++i) {
779       uint32_t sequence_flags = flags();
780       if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
781         // If all the ports are disabled we should just fire the allocation
782         // done event and return.
783         done_signal_needed = true;
784         break;
785       }
786 
787       if (!config || config->relays.empty()) {
788         // No relay ports specified in this config.
789         sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
790       }
791 
792       if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
793           networks[i]->GetBestIP().family() == AF_INET6) {
794         // Skip IPv6 networks unless the flag's been set.
795         continue;
796       }
797 
798       if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
799           networks[i]->GetBestIP().family() == AF_INET6 &&
800           networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
801         // Skip IPv6 Wi-Fi networks unless the flag's been set.
802         continue;
803       }
804 
805       if (disable_equivalent) {
806         // Disable phases that would only create ports equivalent to
807         // ones that we have already made.
808         DisableEquivalentPhases(networks[i], config, &sequence_flags);
809 
810         if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
811           // New AllocationSequence would have nothing to do, so don't make it.
812           continue;
813         }
814       }
815 
816       AllocationSequence* sequence =
817           new AllocationSequence(this, networks[i], config, sequence_flags);
818       sequence->SignalPortAllocationComplete.connect(
819           this, &BasicPortAllocatorSession::OnPortAllocationComplete);
820       sequence->Init();
821       sequence->Start();
822       sequences_.push_back(sequence);
823       done_signal_needed = true;
824     }
825   }
826   if (done_signal_needed) {
827     network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
828   }
829 }
830 
OnNetworksChanged()831 void BasicPortAllocatorSession::OnNetworksChanged() {
832   RTC_DCHECK_RUN_ON(network_thread_);
833   std::vector<rtc::Network*> networks = GetNetworks();
834   std::vector<rtc::Network*> failed_networks;
835   for (AllocationSequence* sequence : sequences_) {
836     // Mark the sequence as "network failed" if its network is not in
837     // |networks|.
838     if (!sequence->network_failed() &&
839         !absl::c_linear_search(networks, sequence->network())) {
840       sequence->OnNetworkFailed();
841       failed_networks.push_back(sequence->network());
842     }
843   }
844   std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
845   if (!ports_to_prune.empty()) {
846     RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
847                      << " ports because their networks were gone";
848     PrunePortsAndRemoveCandidates(ports_to_prune);
849   }
850 
851   if (allocation_started_ && !IsStopped()) {
852     if (network_manager_started_) {
853       // If the network manager has started, it must be regathering.
854       SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
855     }
856     bool disable_equivalent_phases = true;
857     DoAllocate(disable_equivalent_phases);
858   }
859 
860   if (!network_manager_started_) {
861     RTC_LOG(LS_INFO) << "Network manager has started";
862     network_manager_started_ = true;
863   }
864 }
865 
DisableEquivalentPhases(rtc::Network * network,PortConfiguration * config,uint32_t * flags)866 void BasicPortAllocatorSession::DisableEquivalentPhases(
867     rtc::Network* network,
868     PortConfiguration* config,
869     uint32_t* flags) {
870   RTC_DCHECK_RUN_ON(network_thread_);
871   for (uint32_t i = 0; i < sequences_.size() &&
872                        (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
873        ++i) {
874     sequences_[i]->DisableEquivalentPhases(network, config, flags);
875   }
876 }
877 
AddAllocatedPort(Port * port,AllocationSequence * seq,bool prepare_address)878 void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
879                                                  AllocationSequence* seq,
880                                                  bool prepare_address) {
881   RTC_DCHECK_RUN_ON(network_thread_);
882   if (!port)
883     return;
884 
885   RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
886   port->set_content_name(content_name());
887   port->set_component(component());
888   port->set_generation(generation());
889   if (allocator_->proxy().type != rtc::PROXY_NONE)
890     port->set_proxy(allocator_->user_agent(), allocator_->proxy());
891   port->set_send_retransmit_count_attribute(
892       (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
893 
894   PortData data(port, seq);
895   ports_.push_back(data);
896 
897   port->SignalCandidateReady.connect(
898       this, &BasicPortAllocatorSession::OnCandidateReady);
899   port->SignalCandidateError.connect(
900       this, &BasicPortAllocatorSession::OnCandidateError);
901   port->SignalPortComplete.connect(this,
902                                    &BasicPortAllocatorSession::OnPortComplete);
903   port->SignalDestroyed.connect(this,
904                                 &BasicPortAllocatorSession::OnPortDestroyed);
905   port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
906   RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
907 
908   if (prepare_address)
909     port->PrepareAddress();
910 }
911 
OnAllocationSequenceObjectsCreated()912 void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
913   RTC_DCHECK_RUN_ON(network_thread_);
914   allocation_sequences_created_ = true;
915   // Send candidate allocation complete signal if we have no sequences.
916   MaybeSignalCandidatesAllocationDone();
917 }
918 
OnCandidateReady(Port * port,const Candidate & c)919 void BasicPortAllocatorSession::OnCandidateReady(Port* port,
920                                                  const Candidate& c) {
921   RTC_DCHECK_RUN_ON(network_thread_);
922   PortData* data = FindPort(port);
923   RTC_DCHECK(data != NULL);
924   RTC_LOG(LS_INFO) << port->ToString()
925                    << ": Gathered candidate: " << c.ToSensitiveString();
926   // Discarding any candidate signal if port allocation status is
927   // already done with gathering.
928   if (!data->inprogress()) {
929     RTC_LOG(LS_WARNING)
930         << "Discarding candidate because port is already done gathering.";
931     return;
932   }
933 
934   // Mark that the port has a pairable candidate, either because we have a
935   // usable candidate from the port, or simply because the port is bound to the
936   // any address and therefore has no host candidate. This will trigger the port
937   // to start creating candidate pairs (connections) and issue connectivity
938   // checks. If port has already been marked as having a pairable candidate,
939   // do nothing here.
940   // Note: We should check whether any candidates may become ready after this
941   // because there we will check whether the candidate is generated by the ready
942   // ports, which may include this port.
943   bool pruned = false;
944   if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
945     data->set_has_pairable_candidate(true);
946 
947     if (port->Type() == RELAY_PORT_TYPE) {
948       if (turn_port_prune_policy_ == webrtc::KEEP_FIRST_READY) {
949         pruned = PruneNewlyPairableTurnPort(data);
950       } else if (turn_port_prune_policy_ == webrtc::PRUNE_BASED_ON_PRIORITY) {
951         pruned = PruneTurnPorts(port);
952       }
953     }
954 
955     // If the current port is not pruned yet, SignalPortReady.
956     if (!data->pruned()) {
957       RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
958       SignalPortReady(this, port);
959       port->KeepAliveUntilPruned();
960     }
961   }
962 
963   if (data->ready() && CheckCandidateFilter(c)) {
964     std::vector<Candidate> candidates;
965     candidates.push_back(allocator_->SanitizeCandidate(c));
966     SignalCandidatesReady(this, candidates);
967   } else {
968     RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
969   }
970 
971   // If we have pruned any port, maybe need to signal port allocation done.
972   if (pruned) {
973     MaybeSignalCandidatesAllocationDone();
974   }
975 }
976 
OnCandidateError(Port * port,const IceCandidateErrorEvent & event)977 void BasicPortAllocatorSession::OnCandidateError(
978     Port* port,
979     const IceCandidateErrorEvent& event) {
980   RTC_DCHECK_RUN_ON(network_thread_);
981   RTC_DCHECK(FindPort(port));
982   if (event.address.empty()) {
983     candidate_error_events_.push_back(event);
984   } else {
985     SignalCandidateError(this, event);
986   }
987 }
988 
GetBestTurnPortForNetwork(const std::string & network_name) const989 Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
990     const std::string& network_name) const {
991   RTC_DCHECK_RUN_ON(network_thread_);
992   Port* best_turn_port = nullptr;
993   for (const PortData& data : ports_) {
994     if (data.port()->Network()->name() == network_name &&
995         data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
996         (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
997       best_turn_port = data.port();
998     }
999   }
1000   return best_turn_port;
1001 }
1002 
PruneNewlyPairableTurnPort(PortData * newly_pairable_port_data)1003 bool BasicPortAllocatorSession::PruneNewlyPairableTurnPort(
1004     PortData* newly_pairable_port_data) {
1005   RTC_DCHECK_RUN_ON(network_thread_);
1006   RTC_DCHECK(newly_pairable_port_data->port()->Type() == RELAY_PORT_TYPE);
1007   // If an existing turn port is ready on the same network, prune the newly
1008   // pairable port.
1009   const std::string& network_name =
1010       newly_pairable_port_data->port()->Network()->name();
1011 
1012   for (PortData& data : ports_) {
1013     if (data.port()->Network()->name() == network_name &&
1014         data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1015         &data != newly_pairable_port_data) {
1016       RTC_LOG(LS_INFO) << "Port pruned: "
1017                        << newly_pairable_port_data->port()->ToString();
1018       newly_pairable_port_data->Prune();
1019       return true;
1020     }
1021   }
1022   return false;
1023 }
1024 
PruneTurnPorts(Port * newly_pairable_turn_port)1025 bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
1026   RTC_DCHECK_RUN_ON(network_thread_);
1027   // Note: We determine the same network based only on their network names. So
1028   // if an IPv4 address and an IPv6 address have the same network name, they
1029   // are considered the same network here.
1030   const std::string& network_name = newly_pairable_turn_port->Network()->name();
1031   Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1032   // |port| is already in the list of ports, so the best port cannot be nullptr.
1033   RTC_CHECK(best_turn_port != nullptr);
1034 
1035   bool pruned = false;
1036   std::vector<PortData*> ports_to_prune;
1037   for (PortData& data : ports_) {
1038     if (data.port()->Network()->name() == network_name &&
1039         data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1040         ComparePort(data.port(), best_turn_port) < 0) {
1041       pruned = true;
1042       if (data.port() != newly_pairable_turn_port) {
1043         // These ports will be pruned in PrunePortsAndRemoveCandidates.
1044         ports_to_prune.push_back(&data);
1045       } else {
1046         data.Prune();
1047       }
1048     }
1049   }
1050 
1051   if (!ports_to_prune.empty()) {
1052     RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1053                      << " low-priority TURN ports";
1054     PrunePortsAndRemoveCandidates(ports_to_prune);
1055   }
1056   return pruned;
1057 }
1058 
PruneAllPorts()1059 void BasicPortAllocatorSession::PruneAllPorts() {
1060   RTC_DCHECK_RUN_ON(network_thread_);
1061   for (PortData& data : ports_) {
1062     data.Prune();
1063   }
1064 }
1065 
OnPortComplete(Port * port)1066 void BasicPortAllocatorSession::OnPortComplete(Port* port) {
1067   RTC_DCHECK_RUN_ON(network_thread_);
1068   RTC_LOG(LS_INFO) << port->ToString()
1069                    << ": Port completed gathering candidates.";
1070   PortData* data = FindPort(port);
1071   RTC_DCHECK(data != NULL);
1072 
1073   // Ignore any late signals.
1074   if (!data->inprogress()) {
1075     return;
1076   }
1077 
1078   // Moving to COMPLETE state.
1079   data->set_state(PortData::STATE_COMPLETE);
1080   // Send candidate allocation complete signal if this was the last port.
1081   MaybeSignalCandidatesAllocationDone();
1082 }
1083 
OnPortError(Port * port)1084 void BasicPortAllocatorSession::OnPortError(Port* port) {
1085   RTC_DCHECK_RUN_ON(network_thread_);
1086   RTC_LOG(LS_INFO) << port->ToString()
1087                    << ": Port encountered error while gathering candidates.";
1088   PortData* data = FindPort(port);
1089   RTC_DCHECK(data != NULL);
1090   // We might have already given up on this port and stopped it.
1091   if (!data->inprogress()) {
1092     return;
1093   }
1094 
1095   // SignalAddressError is currently sent from StunPort/TurnPort.
1096   // But this signal itself is generic.
1097   data->set_state(PortData::STATE_ERROR);
1098   // Send candidate allocation complete signal if this was the last port.
1099   MaybeSignalCandidatesAllocationDone();
1100 }
1101 
CheckCandidateFilter(const Candidate & c) const1102 bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
1103   RTC_DCHECK_RUN_ON(network_thread_);
1104 
1105   return IsAllowedByCandidateFilter(c, candidate_filter_);
1106 }
1107 
CandidatePairable(const Candidate & c,const Port * port) const1108 bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1109                                                   const Port* port) const {
1110   RTC_DCHECK_RUN_ON(network_thread_);
1111 
1112   bool candidate_signalable = CheckCandidateFilter(c);
1113 
1114   // When device enumeration is disabled (to prevent non-default IP addresses
1115   // from leaking), we ping from some local candidates even though we don't
1116   // signal them. However, if host candidates are also disabled (for example, to
1117   // prevent even default IP addresses from leaking), we still don't want to
1118   // ping from them, even if device enumeration is disabled.  Thus, we check for
1119   // both device enumeration and host candidates being disabled.
1120   bool network_enumeration_disabled = c.address().IsAnyIP();
1121   bool can_ping_from_candidate =
1122       (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1123   bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1124 
1125   return candidate_signalable ||
1126          (network_enumeration_disabled && can_ping_from_candidate &&
1127           !host_candidates_disabled);
1128 }
1129 
OnPortAllocationComplete(AllocationSequence * seq)1130 void BasicPortAllocatorSession::OnPortAllocationComplete(
1131     AllocationSequence* seq) {
1132   RTC_DCHECK_RUN_ON(network_thread_);
1133   // Send candidate allocation complete signal if all ports are done.
1134   MaybeSignalCandidatesAllocationDone();
1135 }
1136 
MaybeSignalCandidatesAllocationDone()1137 void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
1138   RTC_DCHECK_RUN_ON(network_thread_);
1139   if (CandidatesAllocationDone()) {
1140     if (pooled()) {
1141       RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
1142     } else {
1143       RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1144                        << ":" << component() << ":" << generation();
1145     }
1146     for (const auto& event : candidate_error_events_) {
1147       SignalCandidateError(this, event);
1148     }
1149     candidate_error_events_.clear();
1150     SignalCandidatesAllocationDone(this);
1151   }
1152 }
1153 
OnPortDestroyed(PortInterface * port)1154 void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
1155   RTC_DCHECK_RUN_ON(network_thread_);
1156   for (std::vector<PortData>::iterator iter = ports_.begin();
1157        iter != ports_.end(); ++iter) {
1158     if (port == iter->port()) {
1159       ports_.erase(iter);
1160       RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
1161                        << static_cast<int>(ports_.size()) << " remaining)";
1162       return;
1163     }
1164   }
1165   RTC_NOTREACHED();
1166 }
1167 
FindPort(Port * port)1168 BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1169     Port* port) {
1170   RTC_DCHECK_RUN_ON(network_thread_);
1171   for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1172        ++it) {
1173     if (it->port() == port) {
1174       return &*it;
1175     }
1176   }
1177   return NULL;
1178 }
1179 
1180 std::vector<BasicPortAllocatorSession::PortData*>
GetUnprunedPorts(const std::vector<rtc::Network * > & networks)1181 BasicPortAllocatorSession::GetUnprunedPorts(
1182     const std::vector<rtc::Network*>& networks) {
1183   RTC_DCHECK_RUN_ON(network_thread_);
1184   std::vector<PortData*> unpruned_ports;
1185   for (PortData& port : ports_) {
1186     if (!port.pruned() &&
1187         absl::c_linear_search(networks, port.sequence()->network())) {
1188       unpruned_ports.push_back(&port);
1189     }
1190   }
1191   return unpruned_ports;
1192 }
1193 
PrunePortsAndRemoveCandidates(const std::vector<PortData * > & port_data_list)1194 void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1195     const std::vector<PortData*>& port_data_list) {
1196   RTC_DCHECK_RUN_ON(network_thread_);
1197   std::vector<PortInterface*> pruned_ports;
1198   std::vector<Candidate> removed_candidates;
1199   for (PortData* data : port_data_list) {
1200     // Prune the port so that it may be destroyed.
1201     data->Prune();
1202     pruned_ports.push_back(data->port());
1203     if (data->has_pairable_candidate()) {
1204       GetCandidatesFromPort(*data, &removed_candidates);
1205       // Mark the port as having no pairable candidates so that its candidates
1206       // won't be removed multiple times.
1207       data->set_has_pairable_candidate(false);
1208     }
1209   }
1210   if (!pruned_ports.empty()) {
1211     SignalPortsPruned(this, pruned_ports);
1212   }
1213   if (!removed_candidates.empty()) {
1214     RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1215                      << " candidates";
1216     SignalCandidatesRemoved(this, removed_candidates);
1217   }
1218 }
1219 
1220 // AllocationSequence
1221 
AllocationSequence(BasicPortAllocatorSession * session,rtc::Network * network,PortConfiguration * config,uint32_t flags)1222 AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1223                                        rtc::Network* network,
1224                                        PortConfiguration* config,
1225                                        uint32_t flags)
1226     : session_(session),
1227       network_(network),
1228       config_(config),
1229       state_(kInit),
1230       flags_(flags),
1231       udp_socket_(),
1232       udp_port_(NULL),
1233       phase_(0) {}
1234 
Init()1235 void AllocationSequence::Init() {
1236   if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1237     udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1238         rtc::SocketAddress(network_->GetBestIP(), 0),
1239         session_->allocator()->min_port(), session_->allocator()->max_port()));
1240     if (udp_socket_) {
1241       udp_socket_->SignalReadPacket.connect(this,
1242                                             &AllocationSequence::OnReadPacket);
1243     }
1244     // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1245     // are next available options to setup a communication channel.
1246   }
1247 }
1248 
Clear()1249 void AllocationSequence::Clear() {
1250   udp_port_ = NULL;
1251   relay_ports_.clear();
1252 }
1253 
OnNetworkFailed()1254 void AllocationSequence::OnNetworkFailed() {
1255   RTC_DCHECK(!network_failed_);
1256   network_failed_ = true;
1257   // Stop the allocation sequence if its network failed.
1258   Stop();
1259 }
1260 
~AllocationSequence()1261 AllocationSequence::~AllocationSequence() {
1262   session_->network_thread()->Clear(this);
1263 }
1264 
DisableEquivalentPhases(rtc::Network * network,PortConfiguration * config,uint32_t * flags)1265 void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
1266                                                  PortConfiguration* config,
1267                                                  uint32_t* flags) {
1268   if (network_failed_) {
1269     // If the network of this allocation sequence has ever become failed,
1270     // it won't be equivalent to the new network.
1271     return;
1272   }
1273 
1274   if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
1275     // Different network setup; nothing is equivalent.
1276     return;
1277   }
1278 
1279   // Else turn off the stuff that we've already got covered.
1280 
1281   // Every config implicitly specifies local, so turn that off right away if we
1282   // already have a port of the corresponding type. Look for a port that
1283   // matches this AllocationSequence's network, is the right protocol, and
1284   // hasn't encountered an error.
1285   // TODO(deadbeef): This doesn't take into account that there may be another
1286   // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1287   // This can happen if, say, there's a network change event right before an
1288   // application-triggered ICE restart. Hopefully this problem will just go
1289   // away if we get rid of the gathering "phases" though, which is planned.
1290   //
1291   //
1292   // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1293   // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1294   // to disable the gathering of these candidates just becaue of an existing
1295   // Port over PROTO_UDP, namely a TurnPort over UDP.
1296   if (absl::c_any_of(session_->ports_,
1297                      [this](const BasicPortAllocatorSession::PortData& p) {
1298                        return !p.pruned() && p.port()->Network() == network_ &&
1299                               p.port()->GetProtocol() == PROTO_UDP &&
1300                               p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
1301                      })) {
1302     *flags |= PORTALLOCATOR_DISABLE_UDP;
1303   }
1304   // Similarly we need to check both the protocol used by an existing Port and
1305   // its type.
1306   if (absl::c_any_of(session_->ports_,
1307                      [this](const BasicPortAllocatorSession::PortData& p) {
1308                        return !p.pruned() && p.port()->Network() == network_ &&
1309                               p.port()->GetProtocol() == PROTO_TCP &&
1310                               p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
1311                      })) {
1312     *flags |= PORTALLOCATOR_DISABLE_TCP;
1313   }
1314 
1315   if (config_ && config) {
1316     // We need to regather srflx candidates if either of the following
1317     // conditions occurs:
1318     //  1. The STUN servers are different from the previous gathering.
1319     //  2. We will regather host candidates, hence possibly inducing new NAT
1320     //     bindings.
1321     if (config_->StunServers() == config->StunServers() &&
1322         (*flags & PORTALLOCATOR_DISABLE_UDP)) {
1323       // Already got this STUN servers covered.
1324       *flags |= PORTALLOCATOR_DISABLE_STUN;
1325     }
1326     if (!config_->relays.empty()) {
1327       // Already got relays covered.
1328       // NOTE: This will even skip a _different_ set of relay servers if we
1329       // were to be given one, but that never happens in our codebase. Should
1330       // probably get rid of the list in PortConfiguration and just keep a
1331       // single relay server in each one.
1332       *flags |= PORTALLOCATOR_DISABLE_RELAY;
1333     }
1334   }
1335 }
1336 
Start()1337 void AllocationSequence::Start() {
1338   state_ = kRunning;
1339   session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
1340   // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1341   // called next time, we enable all phases if the best IP has since changed.
1342   previous_best_ip_ = network_->GetBestIP();
1343 }
1344 
Stop()1345 void AllocationSequence::Stop() {
1346   // If the port is completed, don't set it to stopped.
1347   if (state_ == kRunning) {
1348     state_ = kStopped;
1349     session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1350   }
1351 }
1352 
OnMessage(rtc::Message * msg)1353 void AllocationSequence::OnMessage(rtc::Message* msg) {
1354   RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1355   RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
1356 
1357   const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
1358 
1359   // Perform all of the phases in the current step.
1360   RTC_LOG(LS_INFO) << network_->ToString()
1361                    << ": Allocation Phase=" << PHASE_NAMES[phase_];
1362 
1363   switch (phase_) {
1364     case PHASE_UDP:
1365       CreateUDPPorts();
1366       CreateStunPorts();
1367       break;
1368 
1369     case PHASE_RELAY:
1370       CreateRelayPorts();
1371       break;
1372 
1373     case PHASE_TCP:
1374       CreateTCPPorts();
1375       state_ = kCompleted;
1376       break;
1377 
1378     default:
1379       RTC_NOTREACHED();
1380   }
1381 
1382   if (state() == kRunning) {
1383     ++phase_;
1384     session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1385                                             session_->allocator()->step_delay(),
1386                                             this, MSG_ALLOCATION_PHASE);
1387   } else {
1388     // If all phases in AllocationSequence are completed, no allocation
1389     // steps needed further. Canceling  pending signal.
1390     session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1391     SignalPortAllocationComplete(this);
1392   }
1393 }
1394 
CreateUDPPorts()1395 void AllocationSequence::CreateUDPPorts() {
1396   if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1397     RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1398     return;
1399   }
1400 
1401   // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1402   // is enabled completely.
1403   std::unique_ptr<UDPPort> port;
1404   bool emit_local_candidate_for_anyaddress =
1405       !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
1406   if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
1407     port = UDPPort::Create(
1408         session_->network_thread(), session_->socket_factory(), network_,
1409         udp_socket_.get(), session_->username(), session_->password(),
1410         session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1411         session_->allocator()->stun_candidate_keepalive_interval());
1412   } else {
1413     port = UDPPort::Create(
1414         session_->network_thread(), session_->socket_factory(), network_,
1415         session_->allocator()->min_port(), session_->allocator()->max_port(),
1416         session_->username(), session_->password(),
1417         session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1418         session_->allocator()->stun_candidate_keepalive_interval());
1419   }
1420 
1421   if (port) {
1422     // If shared socket is enabled, STUN candidate will be allocated by the
1423     // UDPPort.
1424     if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1425       udp_port_ = port.get();
1426       port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1427 
1428       // If STUN is not disabled, setting stun server address to port.
1429       if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1430         if (config_ && !config_->StunServers().empty()) {
1431           RTC_LOG(LS_INFO)
1432               << "AllocationSequence: UDPPort will be handling the "
1433                  "STUN candidate generation.";
1434           port->set_server_addresses(config_->StunServers());
1435         }
1436       }
1437     }
1438 
1439     session_->AddAllocatedPort(port.release(), this, true);
1440   }
1441 }
1442 
CreateTCPPorts()1443 void AllocationSequence::CreateTCPPorts() {
1444   if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1445     RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1446     return;
1447   }
1448 
1449   std::unique_ptr<Port> port = TCPPort::Create(
1450       session_->network_thread(), session_->socket_factory(), network_,
1451       session_->allocator()->min_port(), session_->allocator()->max_port(),
1452       session_->username(), session_->password(),
1453       session_->allocator()->allow_tcp_listen());
1454   if (port) {
1455     session_->AddAllocatedPort(port.release(), this, true);
1456     // Since TCPPort is not created using shared socket, |port| will not be
1457     // added to the dequeue.
1458   }
1459 }
1460 
CreateStunPorts()1461 void AllocationSequence::CreateStunPorts() {
1462   if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1463     RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1464     return;
1465   }
1466 
1467   if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1468     return;
1469   }
1470 
1471   if (!(config_ && !config_->StunServers().empty())) {
1472     RTC_LOG(LS_WARNING)
1473         << "AllocationSequence: No STUN server configured, skipping.";
1474     return;
1475   }
1476 
1477   std::unique_ptr<StunPort> port = StunPort::Create(
1478       session_->network_thread(), session_->socket_factory(), network_,
1479       session_->allocator()->min_port(), session_->allocator()->max_port(),
1480       session_->username(), session_->password(), config_->StunServers(),
1481       session_->allocator()->origin(),
1482       session_->allocator()->stun_candidate_keepalive_interval());
1483   if (port) {
1484     session_->AddAllocatedPort(port.release(), this, true);
1485     // Since StunPort is not created using shared socket, |port| will not be
1486     // added to the dequeue.
1487   }
1488 }
1489 
CreateRelayPorts()1490 void AllocationSequence::CreateRelayPorts() {
1491   if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1492     RTC_LOG(LS_VERBOSE)
1493         << "AllocationSequence: Relay ports disabled, skipping.";
1494     return;
1495   }
1496 
1497   // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1498   // ought to have a relay list for them here.
1499   RTC_DCHECK(config_);
1500   RTC_DCHECK(!config_->relays.empty());
1501   if (!(config_ && !config_->relays.empty())) {
1502     RTC_LOG(LS_WARNING)
1503         << "AllocationSequence: No relay server configured, skipping.";
1504     return;
1505   }
1506 
1507   for (RelayServerConfig& relay : config_->relays) {
1508     CreateTurnPort(relay);
1509   }
1510 }
1511 
CreateTurnPort(const RelayServerConfig & config)1512 void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1513   PortList::const_iterator relay_port;
1514   for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1515        ++relay_port) {
1516     // Skip UDP connections to relay servers if it's disallowed.
1517     if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1518         relay_port->proto == PROTO_UDP) {
1519       continue;
1520     }
1521 
1522     // Do not create a port if the server address family is known and does
1523     // not match the local IP address family.
1524     int server_ip_family = relay_port->address.ipaddr().family();
1525     int local_ip_family = network_->GetBestIP().family();
1526     if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1527       RTC_LOG(LS_INFO)
1528           << "Server and local address families are not compatible. "
1529              "Server address: "
1530           << relay_port->address.ipaddr().ToSensitiveString()
1531           << " Local address: " << network_->GetBestIP().ToSensitiveString();
1532       continue;
1533     }
1534 
1535     CreateRelayPortArgs args;
1536     args.network_thread = session_->network_thread();
1537     args.socket_factory = session_->socket_factory();
1538     args.network = network_;
1539     args.username = session_->username();
1540     args.password = session_->password();
1541     args.server_address = &(*relay_port);
1542     args.config = &config;
1543     args.origin = session_->allocator()->origin();
1544     args.turn_customizer = session_->allocator()->turn_customizer();
1545 
1546     std::unique_ptr<cricket::Port> port;
1547     // Shared socket mode must be enabled only for UDP based ports. Hence
1548     // don't pass shared socket for ports which will create TCP sockets.
1549     // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1550     // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1551     if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
1552         relay_port->proto == PROTO_UDP && udp_socket_) {
1553       port = session_->allocator()->relay_port_factory()->Create(
1554           args, udp_socket_.get());
1555 
1556       if (!port) {
1557         RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1558                             << args.server_address->address.ToSensitiveString();
1559         continue;
1560       }
1561 
1562       relay_ports_.push_back(port.get());
1563       // Listen to the port destroyed signal, to allow AllocationSequence to
1564       // remove entrt from it's map.
1565       port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1566     } else {
1567       port = session_->allocator()->relay_port_factory()->Create(
1568           args, session_->allocator()->min_port(),
1569           session_->allocator()->max_port());
1570 
1571       if (!port) {
1572         RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1573                             << args.server_address->address.ToSensitiveString();
1574         continue;
1575       }
1576     }
1577     RTC_DCHECK(port != NULL);
1578     session_->AddAllocatedPort(port.release(), this, true);
1579   }
1580 }
1581 
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const int64_t & packet_time_us)1582 void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1583                                       const char* data,
1584                                       size_t size,
1585                                       const rtc::SocketAddress& remote_addr,
1586                                       const int64_t& packet_time_us) {
1587   RTC_DCHECK(socket == udp_socket_.get());
1588 
1589   bool turn_port_found = false;
1590 
1591   // Try to find the TurnPort that matches the remote address. Note that the
1592   // message could be a STUN binding response if the TURN server is also used as
1593   // a STUN server. We don't want to parse every message here to check if it is
1594   // a STUN binding response, so we pass the message to TurnPort regardless of
1595   // the message type. The TurnPort will just ignore the message since it will
1596   // not find any request by transaction ID.
1597   for (auto* port : relay_ports_) {
1598     if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
1599       if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1600                                      packet_time_us)) {
1601         return;
1602       }
1603       turn_port_found = true;
1604     }
1605   }
1606 
1607   if (udp_port_) {
1608     const ServerAddresses& stun_servers = udp_port_->server_addresses();
1609 
1610     // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1611     // the TURN server is also a STUN server.
1612     if (!turn_port_found ||
1613         stun_servers.find(remote_addr) != stun_servers.end()) {
1614       RTC_DCHECK(udp_port_->SharedSocket());
1615       udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1616                                       packet_time_us);
1617     }
1618   }
1619 }
1620 
OnPortDestroyed(PortInterface * port)1621 void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1622   if (udp_port_ == port) {
1623     udp_port_ = NULL;
1624     return;
1625   }
1626 
1627   auto it = absl::c_find(relay_ports_, port);
1628   if (it != relay_ports_.end()) {
1629     relay_ports_.erase(it);
1630   } else {
1631     RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1632     RTC_NOTREACHED();
1633   }
1634 }
1635 
1636 // PortConfiguration
PortConfiguration(const rtc::SocketAddress & stun_address,const std::string & username,const std::string & password)1637 PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1638                                      const std::string& username,
1639                                      const std::string& password)
1640     : stun_address(stun_address), username(username), password(password) {
1641   if (!stun_address.IsNil())
1642     stun_servers.insert(stun_address);
1643 }
1644 
PortConfiguration(const ServerAddresses & stun_servers,const std::string & username,const std::string & password)1645 PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1646                                      const std::string& username,
1647                                      const std::string& password)
1648     : stun_servers(stun_servers), username(username), password(password) {
1649   if (!stun_servers.empty())
1650     stun_address = *(stun_servers.begin());
1651   // Note that this won't change once the config is initialized.
1652   use_turn_server_as_stun_server_disabled =
1653       webrtc::field_trial::IsDisabled("WebRTC-UseTurnServerAsStunServer");
1654 }
1655 
1656 PortConfiguration::~PortConfiguration() = default;
1657 
StunServers()1658 ServerAddresses PortConfiguration::StunServers() {
1659   if (!stun_address.IsNil() &&
1660       stun_servers.find(stun_address) == stun_servers.end()) {
1661     stun_servers.insert(stun_address);
1662   }
1663 
1664   if (!stun_servers.empty() && use_turn_server_as_stun_server_disabled) {
1665     return stun_servers;
1666   }
1667 
1668   // Every UDP TURN server should also be used as a STUN server if
1669   // use_turn_server_as_stun_server is not disabled or the stun servers are
1670   // empty.
1671   ServerAddresses turn_servers = GetRelayServerAddresses(PROTO_UDP);
1672   for (const rtc::SocketAddress& turn_server : turn_servers) {
1673     if (stun_servers.find(turn_server) == stun_servers.end()) {
1674       stun_servers.insert(turn_server);
1675     }
1676   }
1677   return stun_servers;
1678 }
1679 
AddRelay(const RelayServerConfig & config)1680 void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1681   relays.push_back(config);
1682 }
1683 
SupportsProtocol(const RelayServerConfig & relay,ProtocolType type) const1684 bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1685                                          ProtocolType type) const {
1686   PortList::const_iterator relay_port;
1687   for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1688        ++relay_port) {
1689     if (relay_port->proto == type)
1690       return true;
1691   }
1692   return false;
1693 }
1694 
SupportsProtocol(ProtocolType type) const1695 bool PortConfiguration::SupportsProtocol(ProtocolType type) const {
1696   for (size_t i = 0; i < relays.size(); ++i) {
1697     if (SupportsProtocol(relays[i], type))
1698       return true;
1699   }
1700   return false;
1701 }
1702 
GetRelayServerAddresses(ProtocolType type) const1703 ServerAddresses PortConfiguration::GetRelayServerAddresses(
1704     ProtocolType type) const {
1705   ServerAddresses servers;
1706   for (size_t i = 0; i < relays.size(); ++i) {
1707     if (SupportsProtocol(relays[i], type)) {
1708       servers.insert(relays[i].ports.front().address);
1709     }
1710   }
1711   return servers;
1712 }
1713 
1714 }  // namespace cricket
1715