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::__anon544c0a2e0111::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->SubscribePortDestroyed(
904 [this](PortInterface* port) { OnPortDestroyed(port); });
905
906 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
907 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
908
909 if (prepare_address)
910 port->PrepareAddress();
911 }
912
OnAllocationSequenceObjectsCreated()913 void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
914 RTC_DCHECK_RUN_ON(network_thread_);
915 allocation_sequences_created_ = true;
916 // Send candidate allocation complete signal if we have no sequences.
917 MaybeSignalCandidatesAllocationDone();
918 }
919
OnCandidateReady(Port * port,const Candidate & c)920 void BasicPortAllocatorSession::OnCandidateReady(Port* port,
921 const Candidate& c) {
922 RTC_DCHECK_RUN_ON(network_thread_);
923 PortData* data = FindPort(port);
924 RTC_DCHECK(data != NULL);
925 RTC_LOG(LS_INFO) << port->ToString()
926 << ": Gathered candidate: " << c.ToSensitiveString();
927 // Discarding any candidate signal if port allocation status is
928 // already done with gathering.
929 if (!data->inprogress()) {
930 RTC_LOG(LS_WARNING)
931 << "Discarding candidate because port is already done gathering.";
932 return;
933 }
934
935 // Mark that the port has a pairable candidate, either because we have a
936 // usable candidate from the port, or simply because the port is bound to the
937 // any address and therefore has no host candidate. This will trigger the port
938 // to start creating candidate pairs (connections) and issue connectivity
939 // checks. If port has already been marked as having a pairable candidate,
940 // do nothing here.
941 // Note: We should check whether any candidates may become ready after this
942 // because there we will check whether the candidate is generated by the ready
943 // ports, which may include this port.
944 bool pruned = false;
945 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
946 data->set_has_pairable_candidate(true);
947
948 if (port->Type() == RELAY_PORT_TYPE) {
949 if (turn_port_prune_policy_ == webrtc::KEEP_FIRST_READY) {
950 pruned = PruneNewlyPairableTurnPort(data);
951 } else if (turn_port_prune_policy_ == webrtc::PRUNE_BASED_ON_PRIORITY) {
952 pruned = PruneTurnPorts(port);
953 }
954 }
955
956 // If the current port is not pruned yet, SignalPortReady.
957 if (!data->pruned()) {
958 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
959 SignalPortReady(this, port);
960 port->KeepAliveUntilPruned();
961 }
962 }
963
964 if (data->ready() && CheckCandidateFilter(c)) {
965 std::vector<Candidate> candidates;
966 candidates.push_back(allocator_->SanitizeCandidate(c));
967 SignalCandidatesReady(this, candidates);
968 } else {
969 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
970 }
971
972 // If we have pruned any port, maybe need to signal port allocation done.
973 if (pruned) {
974 MaybeSignalCandidatesAllocationDone();
975 }
976 }
977
OnCandidateError(Port * port,const IceCandidateErrorEvent & event)978 void BasicPortAllocatorSession::OnCandidateError(
979 Port* port,
980 const IceCandidateErrorEvent& event) {
981 RTC_DCHECK_RUN_ON(network_thread_);
982 RTC_DCHECK(FindPort(port));
983 if (event.address.empty()) {
984 candidate_error_events_.push_back(event);
985 } else {
986 SignalCandidateError(this, event);
987 }
988 }
989
GetBestTurnPortForNetwork(const std::string & network_name) const990 Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
991 const std::string& network_name) const {
992 RTC_DCHECK_RUN_ON(network_thread_);
993 Port* best_turn_port = nullptr;
994 for (const PortData& data : ports_) {
995 if (data.port()->Network()->name() == network_name &&
996 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
997 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
998 best_turn_port = data.port();
999 }
1000 }
1001 return best_turn_port;
1002 }
1003
PruneNewlyPairableTurnPort(PortData * newly_pairable_port_data)1004 bool BasicPortAllocatorSession::PruneNewlyPairableTurnPort(
1005 PortData* newly_pairable_port_data) {
1006 RTC_DCHECK_RUN_ON(network_thread_);
1007 RTC_DCHECK(newly_pairable_port_data->port()->Type() == RELAY_PORT_TYPE);
1008 // If an existing turn port is ready on the same network, prune the newly
1009 // pairable port.
1010 const std::string& network_name =
1011 newly_pairable_port_data->port()->Network()->name();
1012
1013 for (PortData& data : ports_) {
1014 if (data.port()->Network()->name() == network_name &&
1015 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1016 &data != newly_pairable_port_data) {
1017 RTC_LOG(LS_INFO) << "Port pruned: "
1018 << newly_pairable_port_data->port()->ToString();
1019 newly_pairable_port_data->Prune();
1020 return true;
1021 }
1022 }
1023 return false;
1024 }
1025
PruneTurnPorts(Port * newly_pairable_turn_port)1026 bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
1027 RTC_DCHECK_RUN_ON(network_thread_);
1028 // Note: We determine the same network based only on their network names. So
1029 // if an IPv4 address and an IPv6 address have the same network name, they
1030 // are considered the same network here.
1031 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1032 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1033 // |port| is already in the list of ports, so the best port cannot be nullptr.
1034 RTC_CHECK(best_turn_port != nullptr);
1035
1036 bool pruned = false;
1037 std::vector<PortData*> ports_to_prune;
1038 for (PortData& data : ports_) {
1039 if (data.port()->Network()->name() == network_name &&
1040 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1041 ComparePort(data.port(), best_turn_port) < 0) {
1042 pruned = true;
1043 if (data.port() != newly_pairable_turn_port) {
1044 // These ports will be pruned in PrunePortsAndRemoveCandidates.
1045 ports_to_prune.push_back(&data);
1046 } else {
1047 data.Prune();
1048 }
1049 }
1050 }
1051
1052 if (!ports_to_prune.empty()) {
1053 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1054 << " low-priority TURN ports";
1055 PrunePortsAndRemoveCandidates(ports_to_prune);
1056 }
1057 return pruned;
1058 }
1059
PruneAllPorts()1060 void BasicPortAllocatorSession::PruneAllPorts() {
1061 RTC_DCHECK_RUN_ON(network_thread_);
1062 for (PortData& data : ports_) {
1063 data.Prune();
1064 }
1065 }
1066
OnPortComplete(Port * port)1067 void BasicPortAllocatorSession::OnPortComplete(Port* port) {
1068 RTC_DCHECK_RUN_ON(network_thread_);
1069 RTC_LOG(LS_INFO) << port->ToString()
1070 << ": Port completed gathering candidates.";
1071 PortData* data = FindPort(port);
1072 RTC_DCHECK(data != NULL);
1073
1074 // Ignore any late signals.
1075 if (!data->inprogress()) {
1076 return;
1077 }
1078
1079 // Moving to COMPLETE state.
1080 data->set_state(PortData::STATE_COMPLETE);
1081 // Send candidate allocation complete signal if this was the last port.
1082 MaybeSignalCandidatesAllocationDone();
1083 }
1084
OnPortError(Port * port)1085 void BasicPortAllocatorSession::OnPortError(Port* port) {
1086 RTC_DCHECK_RUN_ON(network_thread_);
1087 RTC_LOG(LS_INFO) << port->ToString()
1088 << ": Port encountered error while gathering candidates.";
1089 PortData* data = FindPort(port);
1090 RTC_DCHECK(data != NULL);
1091 // We might have already given up on this port and stopped it.
1092 if (!data->inprogress()) {
1093 return;
1094 }
1095
1096 // SignalAddressError is currently sent from StunPort/TurnPort.
1097 // But this signal itself is generic.
1098 data->set_state(PortData::STATE_ERROR);
1099 // Send candidate allocation complete signal if this was the last port.
1100 MaybeSignalCandidatesAllocationDone();
1101 }
1102
CheckCandidateFilter(const Candidate & c) const1103 bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
1104 RTC_DCHECK_RUN_ON(network_thread_);
1105
1106 return IsAllowedByCandidateFilter(c, candidate_filter_);
1107 }
1108
CandidatePairable(const Candidate & c,const Port * port) const1109 bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1110 const Port* port) const {
1111 RTC_DCHECK_RUN_ON(network_thread_);
1112
1113 bool candidate_signalable = CheckCandidateFilter(c);
1114
1115 // When device enumeration is disabled (to prevent non-default IP addresses
1116 // from leaking), we ping from some local candidates even though we don't
1117 // signal them. However, if host candidates are also disabled (for example, to
1118 // prevent even default IP addresses from leaking), we still don't want to
1119 // ping from them, even if device enumeration is disabled. Thus, we check for
1120 // both device enumeration and host candidates being disabled.
1121 bool network_enumeration_disabled = c.address().IsAnyIP();
1122 bool can_ping_from_candidate =
1123 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1124 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1125
1126 return candidate_signalable ||
1127 (network_enumeration_disabled && can_ping_from_candidate &&
1128 !host_candidates_disabled);
1129 }
1130
OnPortAllocationComplete(AllocationSequence * seq)1131 void BasicPortAllocatorSession::OnPortAllocationComplete(
1132 AllocationSequence* seq) {
1133 RTC_DCHECK_RUN_ON(network_thread_);
1134 // Send candidate allocation complete signal if all ports are done.
1135 MaybeSignalCandidatesAllocationDone();
1136 }
1137
MaybeSignalCandidatesAllocationDone()1138 void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
1139 RTC_DCHECK_RUN_ON(network_thread_);
1140 if (CandidatesAllocationDone()) {
1141 if (pooled()) {
1142 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
1143 } else {
1144 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1145 << ":" << component() << ":" << generation();
1146 }
1147 for (const auto& event : candidate_error_events_) {
1148 SignalCandidateError(this, event);
1149 }
1150 candidate_error_events_.clear();
1151 SignalCandidatesAllocationDone(this);
1152 }
1153 }
1154
OnPortDestroyed(PortInterface * port)1155 void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
1156 RTC_DCHECK_RUN_ON(network_thread_);
1157 for (std::vector<PortData>::iterator iter = ports_.begin();
1158 iter != ports_.end(); ++iter) {
1159 if (port == iter->port()) {
1160 ports_.erase(iter);
1161 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
1162 << static_cast<int>(ports_.size()) << " remaining)";
1163 return;
1164 }
1165 }
1166 RTC_NOTREACHED();
1167 }
1168
FindPort(Port * port)1169 BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1170 Port* port) {
1171 RTC_DCHECK_RUN_ON(network_thread_);
1172 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1173 ++it) {
1174 if (it->port() == port) {
1175 return &*it;
1176 }
1177 }
1178 return NULL;
1179 }
1180
1181 std::vector<BasicPortAllocatorSession::PortData*>
GetUnprunedPorts(const std::vector<rtc::Network * > & networks)1182 BasicPortAllocatorSession::GetUnprunedPorts(
1183 const std::vector<rtc::Network*>& networks) {
1184 RTC_DCHECK_RUN_ON(network_thread_);
1185 std::vector<PortData*> unpruned_ports;
1186 for (PortData& port : ports_) {
1187 if (!port.pruned() &&
1188 absl::c_linear_search(networks, port.sequence()->network())) {
1189 unpruned_ports.push_back(&port);
1190 }
1191 }
1192 return unpruned_ports;
1193 }
1194
PrunePortsAndRemoveCandidates(const std::vector<PortData * > & port_data_list)1195 void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1196 const std::vector<PortData*>& port_data_list) {
1197 RTC_DCHECK_RUN_ON(network_thread_);
1198 std::vector<PortInterface*> pruned_ports;
1199 std::vector<Candidate> removed_candidates;
1200 for (PortData* data : port_data_list) {
1201 // Prune the port so that it may be destroyed.
1202 data->Prune();
1203 pruned_ports.push_back(data->port());
1204 if (data->has_pairable_candidate()) {
1205 GetCandidatesFromPort(*data, &removed_candidates);
1206 // Mark the port as having no pairable candidates so that its candidates
1207 // won't be removed multiple times.
1208 data->set_has_pairable_candidate(false);
1209 }
1210 }
1211 if (!pruned_ports.empty()) {
1212 SignalPortsPruned(this, pruned_ports);
1213 }
1214 if (!removed_candidates.empty()) {
1215 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1216 << " candidates";
1217 SignalCandidatesRemoved(this, removed_candidates);
1218 }
1219 }
1220
1221 // AllocationSequence
1222
AllocationSequence(BasicPortAllocatorSession * session,rtc::Network * network,PortConfiguration * config,uint32_t flags)1223 AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1224 rtc::Network* network,
1225 PortConfiguration* config,
1226 uint32_t flags)
1227 : session_(session),
1228 network_(network),
1229 config_(config),
1230 state_(kInit),
1231 flags_(flags),
1232 udp_socket_(),
1233 udp_port_(NULL),
1234 phase_(0) {}
1235
Init()1236 void AllocationSequence::Init() {
1237 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1238 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1239 rtc::SocketAddress(network_->GetBestIP(), 0),
1240 session_->allocator()->min_port(), session_->allocator()->max_port()));
1241 if (udp_socket_) {
1242 udp_socket_->SignalReadPacket.connect(this,
1243 &AllocationSequence::OnReadPacket);
1244 }
1245 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1246 // are next available options to setup a communication channel.
1247 }
1248 }
1249
Clear()1250 void AllocationSequence::Clear() {
1251 udp_port_ = NULL;
1252 relay_ports_.clear();
1253 }
1254
OnNetworkFailed()1255 void AllocationSequence::OnNetworkFailed() {
1256 RTC_DCHECK(!network_failed_);
1257 network_failed_ = true;
1258 // Stop the allocation sequence if its network failed.
1259 Stop();
1260 }
1261
~AllocationSequence()1262 AllocationSequence::~AllocationSequence() {
1263 session_->network_thread()->Clear(this);
1264 }
1265
DisableEquivalentPhases(rtc::Network * network,PortConfiguration * config,uint32_t * flags)1266 void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
1267 PortConfiguration* config,
1268 uint32_t* flags) {
1269 if (network_failed_) {
1270 // If the network of this allocation sequence has ever become failed,
1271 // it won't be equivalent to the new network.
1272 return;
1273 }
1274
1275 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
1276 // Different network setup; nothing is equivalent.
1277 return;
1278 }
1279
1280 // Else turn off the stuff that we've already got covered.
1281
1282 // Every config implicitly specifies local, so turn that off right away if we
1283 // already have a port of the corresponding type. Look for a port that
1284 // matches this AllocationSequence's network, is the right protocol, and
1285 // hasn't encountered an error.
1286 // TODO(deadbeef): This doesn't take into account that there may be another
1287 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1288 // This can happen if, say, there's a network change event right before an
1289 // application-triggered ICE restart. Hopefully this problem will just go
1290 // away if we get rid of the gathering "phases" though, which is planned.
1291 //
1292 //
1293 // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1294 // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1295 // to disable the gathering of these candidates just becaue of an existing
1296 // Port over PROTO_UDP, namely a TurnPort over UDP.
1297 if (absl::c_any_of(session_->ports_,
1298 [this](const BasicPortAllocatorSession::PortData& p) {
1299 return !p.pruned() && p.port()->Network() == network_ &&
1300 p.port()->GetProtocol() == PROTO_UDP &&
1301 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
1302 })) {
1303 *flags |= PORTALLOCATOR_DISABLE_UDP;
1304 }
1305 // Similarly we need to check both the protocol used by an existing Port and
1306 // its type.
1307 if (absl::c_any_of(session_->ports_,
1308 [this](const BasicPortAllocatorSession::PortData& p) {
1309 return !p.pruned() && p.port()->Network() == network_ &&
1310 p.port()->GetProtocol() == PROTO_TCP &&
1311 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
1312 })) {
1313 *flags |= PORTALLOCATOR_DISABLE_TCP;
1314 }
1315
1316 if (config_ && config) {
1317 // We need to regather srflx candidates if either of the following
1318 // conditions occurs:
1319 // 1. The STUN servers are different from the previous gathering.
1320 // 2. We will regather host candidates, hence possibly inducing new NAT
1321 // bindings.
1322 if (config_->StunServers() == config->StunServers() &&
1323 (*flags & PORTALLOCATOR_DISABLE_UDP)) {
1324 // Already got this STUN servers covered.
1325 *flags |= PORTALLOCATOR_DISABLE_STUN;
1326 }
1327 if (!config_->relays.empty()) {
1328 // Already got relays covered.
1329 // NOTE: This will even skip a _different_ set of relay servers if we
1330 // were to be given one, but that never happens in our codebase. Should
1331 // probably get rid of the list in PortConfiguration and just keep a
1332 // single relay server in each one.
1333 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1334 }
1335 }
1336 }
1337
Start()1338 void AllocationSequence::Start() {
1339 state_ = kRunning;
1340 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
1341 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1342 // called next time, we enable all phases if the best IP has since changed.
1343 previous_best_ip_ = network_->GetBestIP();
1344 }
1345
Stop()1346 void AllocationSequence::Stop() {
1347 // If the port is completed, don't set it to stopped.
1348 if (state_ == kRunning) {
1349 state_ = kStopped;
1350 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1351 }
1352 }
1353
OnMessage(rtc::Message * msg)1354 void AllocationSequence::OnMessage(rtc::Message* msg) {
1355 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1356 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
1357
1358 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
1359
1360 // Perform all of the phases in the current step.
1361 RTC_LOG(LS_INFO) << network_->ToString()
1362 << ": Allocation Phase=" << PHASE_NAMES[phase_];
1363
1364 switch (phase_) {
1365 case PHASE_UDP:
1366 CreateUDPPorts();
1367 CreateStunPorts();
1368 break;
1369
1370 case PHASE_RELAY:
1371 CreateRelayPorts();
1372 break;
1373
1374 case PHASE_TCP:
1375 CreateTCPPorts();
1376 state_ = kCompleted;
1377 break;
1378
1379 default:
1380 RTC_NOTREACHED();
1381 }
1382
1383 if (state() == kRunning) {
1384 ++phase_;
1385 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1386 session_->allocator()->step_delay(),
1387 this, MSG_ALLOCATION_PHASE);
1388 } else {
1389 // If all phases in AllocationSequence are completed, no allocation
1390 // steps needed further. Canceling pending signal.
1391 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1392 SignalPortAllocationComplete(this);
1393 }
1394 }
1395
CreateUDPPorts()1396 void AllocationSequence::CreateUDPPorts() {
1397 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1398 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1399 return;
1400 }
1401
1402 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1403 // is enabled completely.
1404 std::unique_ptr<UDPPort> port;
1405 bool emit_local_candidate_for_anyaddress =
1406 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
1407 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
1408 port = UDPPort::Create(
1409 session_->network_thread(), session_->socket_factory(), network_,
1410 udp_socket_.get(), session_->username(), session_->password(),
1411 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1412 session_->allocator()->stun_candidate_keepalive_interval());
1413 } else {
1414 port = UDPPort::Create(
1415 session_->network_thread(), session_->socket_factory(), network_,
1416 session_->allocator()->min_port(), session_->allocator()->max_port(),
1417 session_->username(), session_->password(),
1418 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1419 session_->allocator()->stun_candidate_keepalive_interval());
1420 }
1421
1422 if (port) {
1423 // If shared socket is enabled, STUN candidate will be allocated by the
1424 // UDPPort.
1425 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1426 udp_port_ = port.get();
1427 port->SubscribePortDestroyed(
1428 [this](PortInterface* port) { OnPortDestroyed(port); });
1429
1430 // If STUN is not disabled, setting stun server address to port.
1431 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1432 if (config_ && !config_->StunServers().empty()) {
1433 RTC_LOG(LS_INFO)
1434 << "AllocationSequence: UDPPort will be handling the "
1435 "STUN candidate generation.";
1436 port->set_server_addresses(config_->StunServers());
1437 }
1438 }
1439 }
1440
1441 session_->AddAllocatedPort(port.release(), this, true);
1442 }
1443 }
1444
CreateTCPPorts()1445 void AllocationSequence::CreateTCPPorts() {
1446 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1447 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1448 return;
1449 }
1450
1451 std::unique_ptr<Port> port = TCPPort::Create(
1452 session_->network_thread(), session_->socket_factory(), network_,
1453 session_->allocator()->min_port(), session_->allocator()->max_port(),
1454 session_->username(), session_->password(),
1455 session_->allocator()->allow_tcp_listen());
1456 if (port) {
1457 session_->AddAllocatedPort(port.release(), this, true);
1458 // Since TCPPort is not created using shared socket, |port| will not be
1459 // added to the dequeue.
1460 }
1461 }
1462
CreateStunPorts()1463 void AllocationSequence::CreateStunPorts() {
1464 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1465 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1466 return;
1467 }
1468
1469 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1470 return;
1471 }
1472
1473 if (!(config_ && !config_->StunServers().empty())) {
1474 RTC_LOG(LS_WARNING)
1475 << "AllocationSequence: No STUN server configured, skipping.";
1476 return;
1477 }
1478
1479 std::unique_ptr<StunPort> port = StunPort::Create(
1480 session_->network_thread(), session_->socket_factory(), network_,
1481 session_->allocator()->min_port(), session_->allocator()->max_port(),
1482 session_->username(), session_->password(), config_->StunServers(),
1483 session_->allocator()->origin(),
1484 session_->allocator()->stun_candidate_keepalive_interval());
1485 if (port) {
1486 session_->AddAllocatedPort(port.release(), this, true);
1487 // Since StunPort is not created using shared socket, |port| will not be
1488 // added to the dequeue.
1489 }
1490 }
1491
CreateRelayPorts()1492 void AllocationSequence::CreateRelayPorts() {
1493 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1494 RTC_LOG(LS_VERBOSE)
1495 << "AllocationSequence: Relay ports disabled, skipping.";
1496 return;
1497 }
1498
1499 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1500 // ought to have a relay list for them here.
1501 RTC_DCHECK(config_);
1502 RTC_DCHECK(!config_->relays.empty());
1503 if (!(config_ && !config_->relays.empty())) {
1504 RTC_LOG(LS_WARNING)
1505 << "AllocationSequence: No relay server configured, skipping.";
1506 return;
1507 }
1508
1509 for (RelayServerConfig& relay : config_->relays) {
1510 CreateTurnPort(relay);
1511 }
1512 }
1513
CreateTurnPort(const RelayServerConfig & config)1514 void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1515 PortList::const_iterator relay_port;
1516 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1517 ++relay_port) {
1518 // Skip UDP connections to relay servers if it's disallowed.
1519 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1520 relay_port->proto == PROTO_UDP) {
1521 continue;
1522 }
1523
1524 // Do not create a port if the server address family is known and does
1525 // not match the local IP address family.
1526 int server_ip_family = relay_port->address.ipaddr().family();
1527 int local_ip_family = network_->GetBestIP().family();
1528 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1529 RTC_LOG(LS_INFO)
1530 << "Server and local address families are not compatible. "
1531 "Server address: "
1532 << relay_port->address.ipaddr().ToSensitiveString()
1533 << " Local address: " << network_->GetBestIP().ToSensitiveString();
1534 continue;
1535 }
1536
1537 CreateRelayPortArgs args;
1538 args.network_thread = session_->network_thread();
1539 args.socket_factory = session_->socket_factory();
1540 args.network = network_;
1541 args.username = session_->username();
1542 args.password = session_->password();
1543 args.server_address = &(*relay_port);
1544 args.config = &config;
1545 args.origin = session_->allocator()->origin();
1546 args.turn_customizer = session_->allocator()->turn_customizer();
1547
1548 std::unique_ptr<cricket::Port> port;
1549 // Shared socket mode must be enabled only for UDP based ports. Hence
1550 // don't pass shared socket for ports which will create TCP sockets.
1551 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1552 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1553 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
1554 relay_port->proto == PROTO_UDP && udp_socket_) {
1555 port = session_->allocator()->relay_port_factory()->Create(
1556 args, udp_socket_.get());
1557
1558 if (!port) {
1559 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1560 << args.server_address->address.ToSensitiveString();
1561 continue;
1562 }
1563
1564 relay_ports_.push_back(port.get());
1565 // Listen to the port destroyed signal, to allow AllocationSequence to
1566 // remove the entry from it's map.
1567 port->SubscribePortDestroyed(
1568 [this](PortInterface* port) { OnPortDestroyed(port); });
1569
1570 } else {
1571 port = session_->allocator()->relay_port_factory()->Create(
1572 args, session_->allocator()->min_port(),
1573 session_->allocator()->max_port());
1574
1575 if (!port) {
1576 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1577 << args.server_address->address.ToSensitiveString();
1578 continue;
1579 }
1580 }
1581 RTC_DCHECK(port != NULL);
1582 session_->AddAllocatedPort(port.release(), this, true);
1583 }
1584 }
1585
OnReadPacket(rtc::AsyncPacketSocket * socket,const char * data,size_t size,const rtc::SocketAddress & remote_addr,const int64_t & packet_time_us)1586 void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1587 const char* data,
1588 size_t size,
1589 const rtc::SocketAddress& remote_addr,
1590 const int64_t& packet_time_us) {
1591 RTC_DCHECK(socket == udp_socket_.get());
1592
1593 bool turn_port_found = false;
1594
1595 // Try to find the TurnPort that matches the remote address. Note that the
1596 // message could be a STUN binding response if the TURN server is also used as
1597 // a STUN server. We don't want to parse every message here to check if it is
1598 // a STUN binding response, so we pass the message to TurnPort regardless of
1599 // the message type. The TurnPort will just ignore the message since it will
1600 // not find any request by transaction ID.
1601 for (auto* port : relay_ports_) {
1602 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
1603 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1604 packet_time_us)) {
1605 return;
1606 }
1607 turn_port_found = true;
1608 }
1609 }
1610
1611 if (udp_port_) {
1612 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1613
1614 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1615 // the TURN server is also a STUN server.
1616 if (!turn_port_found ||
1617 stun_servers.find(remote_addr) != stun_servers.end()) {
1618 RTC_DCHECK(udp_port_->SharedSocket());
1619 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1620 packet_time_us);
1621 }
1622 }
1623 }
1624
OnPortDestroyed(PortInterface * port)1625 void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1626 if (udp_port_ == port) {
1627 udp_port_ = NULL;
1628 return;
1629 }
1630
1631 auto it = absl::c_find(relay_ports_, port);
1632 if (it != relay_ports_.end()) {
1633 relay_ports_.erase(it);
1634 } else {
1635 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1636 RTC_NOTREACHED();
1637 }
1638 }
1639
1640 // PortConfiguration
PortConfiguration(const rtc::SocketAddress & stun_address,const std::string & username,const std::string & password)1641 PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1642 const std::string& username,
1643 const std::string& password)
1644 : stun_address(stun_address), username(username), password(password) {
1645 if (!stun_address.IsNil())
1646 stun_servers.insert(stun_address);
1647 }
1648
PortConfiguration(const ServerAddresses & stun_servers,const std::string & username,const std::string & password)1649 PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1650 const std::string& username,
1651 const std::string& password)
1652 : stun_servers(stun_servers), username(username), password(password) {
1653 if (!stun_servers.empty())
1654 stun_address = *(stun_servers.begin());
1655 // Note that this won't change once the config is initialized.
1656 use_turn_server_as_stun_server_disabled =
1657 webrtc::field_trial::IsDisabled("WebRTC-UseTurnServerAsStunServer");
1658 }
1659
1660 PortConfiguration::~PortConfiguration() = default;
1661
StunServers()1662 ServerAddresses PortConfiguration::StunServers() {
1663 if (!stun_address.IsNil() &&
1664 stun_servers.find(stun_address) == stun_servers.end()) {
1665 stun_servers.insert(stun_address);
1666 }
1667
1668 if (!stun_servers.empty() && use_turn_server_as_stun_server_disabled) {
1669 return stun_servers;
1670 }
1671
1672 // Every UDP TURN server should also be used as a STUN server if
1673 // use_turn_server_as_stun_server is not disabled or the stun servers are
1674 // empty.
1675 ServerAddresses turn_servers = GetRelayServerAddresses(PROTO_UDP);
1676 for (const rtc::SocketAddress& turn_server : turn_servers) {
1677 if (stun_servers.find(turn_server) == stun_servers.end()) {
1678 stun_servers.insert(turn_server);
1679 }
1680 }
1681 return stun_servers;
1682 }
1683
AddRelay(const RelayServerConfig & config)1684 void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1685 relays.push_back(config);
1686 }
1687
SupportsProtocol(const RelayServerConfig & relay,ProtocolType type) const1688 bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1689 ProtocolType type) const {
1690 PortList::const_iterator relay_port;
1691 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1692 ++relay_port) {
1693 if (relay_port->proto == type)
1694 return true;
1695 }
1696 return false;
1697 }
1698
SupportsProtocol(ProtocolType type) const1699 bool PortConfiguration::SupportsProtocol(ProtocolType type) const {
1700 for (size_t i = 0; i < relays.size(); ++i) {
1701 if (SupportsProtocol(relays[i], type))
1702 return true;
1703 }
1704 return false;
1705 }
1706
GetRelayServerAddresses(ProtocolType type) const1707 ServerAddresses PortConfiguration::GetRelayServerAddresses(
1708 ProtocolType type) const {
1709 ServerAddresses servers;
1710 for (size_t i = 0; i < relays.size(); ++i) {
1711 if (SupportsProtocol(relays[i], type)) {
1712 servers.insert(relays[i].ports.front().address);
1713 }
1714 }
1715 return servers;
1716 }
1717
1718 } // namespace cricket
1719