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