blob: 14cf1ae43ed3d8072a1697acd8a81617d3e4c115 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "p2p/client/basicportallocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
Qingsi Wang10a0e512018-05-16 13:37:03 -070014#include <functional>
Steve Anton6c38cc72017-11-29 10:25:58 -080015#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <string>
17#include <vector>
18
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/umametrics.h"
20#include "p2p/base/basicpacketsocketfactory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "p2p/base/port.h"
22#include "p2p/base/relayport.h"
23#include "p2p/base/stunport.h"
24#include "p2p/base/tcpport.h"
25#include "p2p/base/turnport.h"
26#include "p2p/base/udpport.h"
27#include "rtc_base/checks.h"
28#include "rtc_base/helpers.h"
29#include "rtc_base/logging.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000030
31using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33namespace {
34
35enum {
36 MSG_CONFIG_START,
37 MSG_CONFIG_READY,
38 MSG_ALLOCATE,
39 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000040 MSG_SEQUENCEOBJECTS_CREATED,
41 MSG_CONFIG_STOP,
42};
43
44const int PHASE_UDP = 0;
45const int PHASE_RELAY = 1;
46const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000047
deadbeef1c5e6d02017-09-15 17:46:56 -070048const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049
zhihuang696f8ca2017-06-27 15:11:24 -070050// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070051int GetProtocolPriority(cricket::ProtocolType protocol) {
52 switch (protocol) {
53 case cricket::PROTO_UDP:
54 return 2;
55 case cricket::PROTO_TCP:
56 return 1;
57 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070058 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070059 return 0;
60 default:
nisseeb4ca4e2017-01-12 02:24:27 -080061 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070062 return 0;
63 }
64}
65// Gets address family priority: IPv6 > IPv4 > Unspecified.
66int GetAddressFamilyPriority(int ip_family) {
67 switch (ip_family) {
68 case AF_INET6:
69 return 2;
70 case AF_INET:
71 return 1;
72 default:
nisseeb4ca4e2017-01-12 02:24:27 -080073 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070074 return 0;
75 }
76}
77
78// Returns positive if a is better, negative if b is better, and 0 otherwise.
79int ComparePort(const cricket::Port* a, const cricket::Port* b) {
80 int a_protocol = GetProtocolPriority(a->GetProtocol());
81 int b_protocol = GetProtocolPriority(b->GetProtocol());
82 int cmp_protocol = a_protocol - b_protocol;
83 if (cmp_protocol != 0) {
84 return cmp_protocol;
85 }
86
87 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
88 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
89 return a_family - b_family;
90}
91
Qingsi Wang10a0e512018-05-16 13:37:03 -070092struct NetworkFilter {
93 using Predicate = std::function<bool(rtc::Network*)>;
94 NetworkFilter(Predicate pred, const std::string& description)
95 : pred(pred), description(description) {}
96 Predicate pred;
97 const std::string description;
98};
99
100using NetworkList = rtc::NetworkManager::NetworkList;
101void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
102 auto start_to_remove =
103 std::remove_if(networks->begin(), networks->end(), filter.pred);
104 if (start_to_remove == networks->end()) {
105 return;
106 }
107 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
108 for (auto it = start_to_remove; it != networks->end(); ++it) {
109 RTC_LOG(INFO) << (*it)->ToString();
110 }
111 networks->erase(start_to_remove, networks->end());
112}
113
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114} // namespace
115
116namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200117const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700118 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
119 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120
121// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200122BasicPortAllocator::BasicPortAllocator(
123 rtc::NetworkManager* network_manager,
124 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100125 webrtc::TurnCustomizer* customizer,
126 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700127 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100128 InitRelayPortFactory(relay_port_factory);
129 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800130 RTC_DCHECK(network_manager_ != nullptr);
131 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200132 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
133 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134 Construct();
135}
136
Yves Gerey665174f2018-06-19 15:03:05 +0200137BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700138 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100139 InitRelayPortFactory(nullptr);
140 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800141 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 Construct();
143}
144
Yves Gerey665174f2018-06-19 15:03:05 +0200145BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
146 rtc::PacketSocketFactory* socket_factory,
147 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700148 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100149 InitRelayPortFactory(nullptr);
150 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800151 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200152 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
153 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 Construct();
155}
156
157BasicPortAllocator::BasicPortAllocator(
158 rtc::NetworkManager* network_manager,
159 const ServerAddresses& stun_servers,
160 const rtc::SocketAddress& relay_address_udp,
161 const rtc::SocketAddress& relay_address_tcp,
162 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700163 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100164 InitRelayPortFactory(nullptr);
165 RTC_DCHECK(relay_port_factory_ != nullptr);
166 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700167 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800169 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800171 }
172 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800174 }
175 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800177 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178
deadbeef653b8e02015-11-11 12:55:10 -0800179 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700180 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800181 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182
Jonas Orelandbdcee282017-10-10 14:01:40 +0200183 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 Construct();
185}
186
187void BasicPortAllocator::Construct() {
188 allow_tcp_listen_ = true;
189}
190
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700191void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
192 IceRegatheringReason reason) {
193 if (!metrics_observer()) {
194 return;
195 }
196 // If the session has not been taken by an active channel, do not report the
197 // metric.
198 for (auto& allocator_session : pooled_sessions()) {
199 if (allocator_session.get() == session) {
200 return;
201 }
202 }
203
204 metrics_observer()->IncrementEnumCounter(
205 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
206 static_cast<int>(IceRegatheringReason::MAX_VALUE));
207}
208
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700210 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800211 // Our created port allocator sessions depend on us, so destroy our remaining
212 // pooled sessions before anything else.
213 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214}
215
Steve Anton7995d8c2017-10-30 16:23:38 -0700216void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
217 // TODO(phoglund): implement support for other types than loopback.
218 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
219 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700220 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700221 network_ignore_mask_ = network_ignore_mask;
222}
223
deadbeefc5d0d952015-07-16 10:22:21 -0700224PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200225 const std::string& content_name,
226 int component,
227 const std::string& ice_ufrag,
228 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700229 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700230 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000231 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700232 session->SignalIceRegathering.connect(this,
233 &BasicPortAllocator::OnIceRegathering);
234 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235}
236
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700237void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700238 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700239 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
240 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700241 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200242 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700243}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000244
Jonas Oreland202994c2017-12-18 12:10:43 +0100245void BasicPortAllocator::InitRelayPortFactory(
246 RelayPortFactoryInterface* relay_port_factory) {
247 if (relay_port_factory != nullptr) {
248 relay_port_factory_ = relay_port_factory;
249 } else {
250 default_relay_port_factory_.reset(new TurnPortFactory());
251 relay_port_factory_ = default_relay_port_factory_.get();
252 }
253}
254
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255// BasicPortAllocatorSession
256BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700257 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 const std::string& content_name,
259 int component,
260 const std::string& ice_ufrag,
261 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700262 : PortAllocatorSession(content_name,
263 component,
264 ice_ufrag,
265 ice_pwd,
266 allocator->flags()),
267 allocator_(allocator),
268 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 socket_factory_(allocator->socket_factory()),
270 allocation_started_(false),
271 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700272 allocation_sequences_created_(false),
273 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274 allocator_->network_manager()->SignalNetworksChanged.connect(
275 this, &BasicPortAllocatorSession::OnNetworksChanged);
276 allocator_->network_manager()->StartUpdating();
277}
278
279BasicPortAllocatorSession::~BasicPortAllocatorSession() {
280 allocator_->network_manager()->StopUpdating();
281 if (network_thread_ != NULL)
282 network_thread_->Clear(this);
283
Peter Boström0c4e06b2015-10-07 12:23:21 +0200284 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 // AllocationSequence should clear it's map entry for turn ports before
286 // ports are destroyed.
287 sequences_[i]->Clear();
288 }
289
290 std::vector<PortData>::iterator it;
291 for (it = ports_.begin(); it != ports_.end(); it++)
292 delete it->port();
293
Peter Boström0c4e06b2015-10-07 12:23:21 +0200294 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 delete configs_[i];
296
Peter Boström0c4e06b2015-10-07 12:23:21 +0200297 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000298 delete sequences_[i];
299}
300
Steve Anton7995d8c2017-10-30 16:23:38 -0700301BasicPortAllocator* BasicPortAllocatorSession::allocator() {
302 return allocator_;
303}
304
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700305void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
306 if (filter == candidate_filter_) {
307 return;
308 }
309 // We assume the filter will only change from "ALL" to something else.
310 RTC_DCHECK(candidate_filter_ == CF_ALL);
311 candidate_filter_ = filter;
312 for (PortData& port : ports_) {
313 if (!port.has_pairable_candidate()) {
314 continue;
315 }
316 const auto& candidates = port.port()->Candidates();
317 // Setting a filter may cause a ready port to become non-ready
318 // if it no longer has any pairable candidates.
319 if (!std::any_of(candidates.begin(), candidates.end(),
320 [this, &port](const Candidate& candidate) {
321 return CandidatePairable(candidate, port.port());
322 })) {
323 port.set_has_pairable_candidate(false);
324 }
325 }
326}
327
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328void BasicPortAllocatorSession::StartGettingPorts() {
329 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700330 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331 if (!socket_factory_) {
332 owned_socket_factory_.reset(
333 new rtc::BasicPacketSocketFactory(network_thread_));
334 socket_factory_ = owned_socket_factory_.get();
335 }
336
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700337 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700338
Mirko Bonadei675513b2017-11-09 11:09:25 +0100339 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
340 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000341}
342
343void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800344 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700345 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700346 // Note: this must be called after ClearGettingPorts because both may set the
347 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700348 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700349}
350
351void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800352 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700354 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700356 }
deadbeefb60a8192016-08-24 15:15:00 -0700357 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700358 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700359}
360
Steve Anton7995d8c2017-10-30 16:23:38 -0700361bool BasicPortAllocatorSession::IsGettingPorts() {
362 return state_ == SessionState::GATHERING;
363}
364
365bool BasicPortAllocatorSession::IsCleared() const {
366 return state_ == SessionState::CLEARED;
367}
368
369bool BasicPortAllocatorSession::IsStopped() const {
370 return state_ == SessionState::STOPPED;
371}
372
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700373std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
374 std::vector<rtc::Network*> networks = GetNetworks();
375
376 // A network interface may have both IPv4 and IPv6 networks. Only if
377 // neither of the networks has any connections, the network interface
378 // is considered failed and need to be regathered on.
379 std::set<std::string> networks_with_connection;
380 for (const PortData& data : ports_) {
381 Port* port = data.port();
382 if (!port->connections().empty()) {
383 networks_with_connection.insert(port->Network()->name());
384 }
385 }
386
387 networks.erase(
388 std::remove_if(networks.begin(), networks.end(),
389 [networks_with_connection](rtc::Network* network) {
390 // If a network does not have any connection, it is
391 // considered failed.
392 return networks_with_connection.find(network->name()) !=
393 networks_with_connection.end();
394 }),
395 networks.end());
396 return networks;
397}
398
399void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
400 // Find the list of networks that have no connection.
401 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
402 if (failed_networks.empty()) {
403 return;
404 }
405
Mirko Bonadei675513b2017-11-09 11:09:25 +0100406 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700407
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700408 // Mark a sequence as "network failed" if its network is in the list of failed
409 // networks, so that it won't be considered as equivalent when the session
410 // regathers ports and candidates.
411 for (AllocationSequence* sequence : sequences_) {
412 if (!sequence->network_failed() &&
413 std::find(failed_networks.begin(), failed_networks.end(),
414 sequence->network()) != failed_networks.end()) {
415 sequence->set_network_failed();
416 }
417 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700418
419 bool disable_equivalent_phases = true;
420 Regather(failed_networks, disable_equivalent_phases,
421 IceRegatheringReason::NETWORK_FAILURE);
422}
423
424void BasicPortAllocatorSession::RegatherOnAllNetworks() {
425 std::vector<rtc::Network*> networks = GetNetworks();
426 if (networks.empty()) {
427 return;
428 }
429
Mirko Bonadei675513b2017-11-09 11:09:25 +0100430 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700431
432 // We expect to generate candidates that are equivalent to what we have now.
433 // Force DoAllocate to generate them instead of skipping.
434 bool disable_equivalent_phases = false;
435 Regather(networks, disable_equivalent_phases,
436 IceRegatheringReason::OCCASIONAL_REFRESH);
437}
438
439void BasicPortAllocatorSession::Regather(
440 const std::vector<rtc::Network*>& networks,
441 bool disable_equivalent_phases,
442 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700443 // Remove ports from being used locally and send signaling to remove
444 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700445 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700446 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100447 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700448 PrunePortsAndRemoveCandidates(ports_to_prune);
449 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700450
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700451 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700452 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700453
Steve Anton300bf8e2017-07-14 10:13:10 -0700454 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700455 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456}
457
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800458void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200459 const absl::optional<int>& stun_keepalive_interval) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800460 auto ports = ReadyPorts();
461 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800462 // The port type and protocol can be used to identify different subclasses
463 // of Port in the current implementation. Note that a TCPPort has the type
464 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
465 if (port->Type() == STUN_PORT_TYPE ||
466 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800467 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
468 stun_keepalive_interval);
469 }
470 }
471}
472
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700473std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
474 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700475 for (const PortData& data : ports_) {
476 if (data.ready()) {
477 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700478 }
479 }
480 return ret;
481}
482
483std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
484 std::vector<Candidate> candidates;
485 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700486 if (!data.ready()) {
487 continue;
488 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700489 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700490 }
491 return candidates;
492}
493
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700494void BasicPortAllocatorSession::GetCandidatesFromPort(
495 const PortData& data,
496 std::vector<Candidate>* candidates) const {
497 RTC_CHECK(candidates != nullptr);
498 for (const Candidate& candidate : data.port()->Candidates()) {
499 if (!CheckCandidateFilter(candidate)) {
500 continue;
501 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700502 candidates->push_back(SanitizeRelatedAddress(candidate));
503 }
504}
505
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700506Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
507 const Candidate& c) const {
508 Candidate copy = c;
509 // If adapter enumeration is disabled or host candidates are disabled,
510 // clear the raddr of STUN candidates to avoid local address leakage.
511 bool filter_stun_related_address =
512 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
513 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
514 !(candidate_filter_ & CF_HOST);
515 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
516 // to avoid reflexive address leakage.
517 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
518 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
519 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
520 copy.set_related_address(
521 rtc::EmptySocketAddressWithFamily(copy.address().family()));
522 }
523 return copy;
524}
525
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700526bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
527 // Done only if all required AllocationSequence objects
528 // are created.
529 if (!allocation_sequences_created_) {
530 return false;
531 }
532
533 // Check that all port allocation sequences are complete (not running).
534 if (std::any_of(sequences_.begin(), sequences_.end(),
535 [](const AllocationSequence* sequence) {
536 return sequence->state() == AllocationSequence::kRunning;
537 })) {
538 return false;
539 }
540
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700541 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700542 // expected candidates. Session will trigger candidates allocation complete
543 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700544 return std::none_of(ports_.begin(), ports_.end(),
545 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700546}
547
Yves Gerey665174f2018-06-19 15:03:05 +0200548void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200550 case MSG_CONFIG_START:
551 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
552 GetPortConfigurations();
553 break;
554 case MSG_CONFIG_READY:
555 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
556 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
557 break;
558 case MSG_ALLOCATE:
559 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
560 OnAllocate();
561 break;
562 case MSG_SEQUENCEOBJECTS_CREATED:
563 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
564 OnAllocationSequenceObjectsCreated();
565 break;
566 case MSG_CONFIG_STOP:
567 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
568 OnConfigStop();
569 break;
570 default:
571 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572 }
573}
574
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700575void BasicPortAllocatorSession::UpdateIceParametersInternal() {
576 for (PortData& port : ports_) {
577 port.port()->set_content_name(content_name());
578 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
579 }
580}
581
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582void BasicPortAllocatorSession::GetPortConfigurations() {
Yves Gerey665174f2018-06-19 15:03:05 +0200583 PortConfiguration* config =
584 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000585
deadbeef653b8e02015-11-11 12:55:10 -0800586 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
587 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000588 }
589 ConfigReady(config);
590}
591
592void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700593 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000594}
595
596// Adds a configuration to the list.
597void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800598 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000599 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800600 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000601
602 AllocatePorts();
603}
604
605void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800606 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000607
608 // If any of the allocated ports have not completed the candidates allocation,
609 // mark those as error. Since session doesn't need any new candidates
610 // at this stage of the allocation, it's safe to discard any new candidates.
611 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200612 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
613 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700614 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000615 // Updating port state to error, which didn't finish allocating candidates
616 // yet.
617 it->set_error();
618 send_signal = true;
619 }
620 }
621
622 // Did we stop any running sequences?
623 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
624 it != sequences_.end() && !send_signal; ++it) {
625 if ((*it)->state() == AllocationSequence::kStopped) {
626 send_signal = true;
627 }
628 }
629
630 // If we stopped anything that was running, send a done signal now.
631 if (send_signal) {
632 MaybeSignalCandidatesAllocationDone();
633 }
634}
635
636void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800637 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700638 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639}
640
641void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700642 if (network_manager_started_ && !IsStopped()) {
643 bool disable_equivalent_phases = true;
644 DoAllocate(disable_equivalent_phases);
645 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646
647 allocation_started_ = true;
648}
649
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700650std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
651 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700652 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800653 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700654 // If the network permission state is BLOCKED, we just act as if the flag has
655 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700656 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700657 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700658 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
659 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000660 // If the adapter enumeration is disabled, we'll just bind to any address
661 // instead of specific NIC. This is to ensure the same routing for http
662 // traffic by OS is also used here to avoid any local or public IP leakage
663 // during stun process.
664 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700665 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000666 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700667 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800668 // If network enumeration fails, use the ANY address as a fallback, so we
669 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700670 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
671 // set, we'll use ANY address candidates either way.
672 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800673 network_manager->GetAnyAddressNetworks(&networks);
674 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000675 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100676 // Filter out link-local networks if needed.
677 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700678 NetworkFilter link_local_filter(
679 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
680 "link-local");
681 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100682 }
deadbeef3427f532017-07-26 16:09:33 -0700683 // Do some more filtering, depending on the network ignore mask and "disable
684 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700685 NetworkFilter ignored_filter(
686 [this](rtc::Network* network) {
687 return allocator_->network_ignore_mask() & network->type();
688 },
689 "ignored");
690 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700691 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
692 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700693 for (rtc::Network* network : networks) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800694 // Don't determine the lowest cost from a link-local network.
695 // On iOS, a device connected to the computer will get a link-local
696 // network for communicating with the computer, however this network can't
697 // be used to connect to a peer outside the network.
698 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
699 continue;
700 }
honghaiz60347052016-05-31 18:29:12 -0700701 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
702 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700703 NetworkFilter costly_filter(
704 [lowest_cost](rtc::Network* network) {
705 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
706 },
707 "costly");
708 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700709 }
deadbeef3427f532017-07-26 16:09:33 -0700710 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
711 // default, it's 5), remove networks to ensure that limit is satisfied.
712 //
713 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
714 // networks, we could try to choose a set that's "most likely to work". It's
715 // hard to define what that means though; it's not just "lowest cost".
716 // Alternatively, we could just focus on making our ICE pinging logic smarter
717 // such that this filtering isn't necessary in the first place.
718 int ipv6_networks = 0;
719 for (auto it = networks.begin(); it != networks.end();) {
720 if ((*it)->prefix().family() == AF_INET6) {
721 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
722 it = networks.erase(it);
723 continue;
724 } else {
725 ++ipv6_networks;
726 }
727 }
728 ++it;
729 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700730 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700731}
732
733// For each network, see if we have a sequence that covers it already. If not,
734// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700735void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700736 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700737 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG(LS_WARNING)
740 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000741 done_signal_needed = true;
742 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100743 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700744 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200745 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200746 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000747 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
748 // If all the ports are disabled we should just fire the allocation
749 // done event and return.
750 done_signal_needed = true;
751 break;
752 }
753
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000754 if (!config || config->relays.empty()) {
755 // No relay ports specified in this config.
756 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
757 }
758
759 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000760 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761 // Skip IPv6 networks unless the flag's been set.
762 continue;
763 }
764
zhihuangb09b3f92017-03-07 14:40:51 -0800765 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
766 networks[i]->GetBestIP().family() == AF_INET6 &&
767 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
768 // Skip IPv6 Wi-Fi networks unless the flag's been set.
769 continue;
770 }
771
Steve Anton300bf8e2017-07-14 10:13:10 -0700772 if (disable_equivalent) {
773 // Disable phases that would only create ports equivalent to
774 // ones that we have already made.
775 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000776
Steve Anton300bf8e2017-07-14 10:13:10 -0700777 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
778 // New AllocationSequence would have nothing to do, so don't make it.
779 continue;
780 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000781 }
782
783 AllocationSequence* sequence =
784 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000785 sequence->SignalPortAllocationComplete.connect(
786 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700787 sequence->Init();
788 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700790 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791 }
792 }
793 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700794 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000795 }
796}
797
798void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700799 std::vector<rtc::Network*> networks = GetNetworks();
800 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700801 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700802 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700803 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700804 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700805 std::find(networks.begin(), networks.end(), sequence->network()) ==
806 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700807 sequence->OnNetworkFailed();
808 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700809 }
810 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700811 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
812 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100813 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
814 << " ports because their networks were gone";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700815 PrunePortsAndRemoveCandidates(ports_to_prune);
816 }
honghaiz8c404fa2015-09-28 07:59:43 -0700817
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700818 if (allocation_started_ && !IsStopped()) {
819 if (network_manager_started_) {
820 // If the network manager has started, it must be regathering.
821 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
822 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700823 bool disable_equivalent_phases = true;
824 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700825 }
826
Honghai Zhang5048f572016-08-23 15:47:33 -0700827 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100828 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700829 network_manager_started_ = true;
830 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831}
832
833void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200834 rtc::Network* network,
835 PortConfiguration* config,
836 uint32_t* flags) {
837 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200838 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200839 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840 sequences_[i]->DisableEquivalentPhases(network, config, flags);
841 }
842}
843
844void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200845 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 bool prepare_address) {
847 if (!port)
848 return;
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700852 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700854 if (allocator_->proxy().type != rtc::PROXY_NONE)
855 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700856 port->set_send_retransmit_count_attribute(
857 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000858
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859 PortData data(port, seq);
860 ports_.push_back(data);
861
862 port->SignalCandidateReady.connect(
863 this, &BasicPortAllocatorSession::OnCandidateReady);
864 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200865 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200867 &BasicPortAllocatorSession::OnPortDestroyed);
868 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
869 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870
871 if (prepare_address)
872 port->PrepareAddress();
873}
874
875void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
876 allocation_sequences_created_ = true;
877 // Send candidate allocation complete signal if we have no sequences.
878 MaybeSignalCandidatesAllocationDone();
879}
880
Yves Gerey665174f2018-06-19 15:03:05 +0200881void BasicPortAllocatorSession::OnCandidateReady(Port* port,
882 const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800883 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800885 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200886 RTC_LOG(LS_INFO) << port->ToString()
887 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700889 // already done with gathering.
890 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700892 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700893 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700894 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700895
danilchapf4e8cf02016-06-30 01:55:03 -0700896 // Mark that the port has a pairable candidate, either because we have a
897 // usable candidate from the port, or simply because the port is bound to the
898 // any address and therefore has no host candidate. This will trigger the port
899 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700900 // checks. If port has already been marked as having a pairable candidate,
901 // do nothing here.
902 // Note: We should check whether any candidates may become ready after this
903 // because there we will check whether the candidate is generated by the ready
904 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700905 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700906 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700907 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700908
909 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700910 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700911 }
912 // If the current port is not pruned yet, SignalPortReady.
913 if (!data->pruned()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200914 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700915 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700916 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700917 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700918 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700919
deadbeef1c5e6d02017-09-15 17:46:56 -0700920 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700921 std::vector<Candidate> candidates;
922 candidates.push_back(SanitizeRelatedAddress(c));
923 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700924 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100925 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700926 }
927
928 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700929 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700930 MaybeSignalCandidatesAllocationDone();
931 }
932}
933
934Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
935 const std::string& network_name) const {
936 Port* best_turn_port = nullptr;
937 for (const PortData& data : ports_) {
938 if (data.port()->Network()->name() == network_name &&
939 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
940 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
941 best_turn_port = data.port();
942 }
943 }
944 return best_turn_port;
945}
946
947bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700948 // Note: We determine the same network based only on their network names. So
949 // if an IPv4 address and an IPv6 address have the same network name, they
950 // are considered the same network here.
951 const std::string& network_name = newly_pairable_turn_port->Network()->name();
952 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
953 // |port| is already in the list of ports, so the best port cannot be nullptr.
954 RTC_CHECK(best_turn_port != nullptr);
955
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700956 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700957 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700958 for (PortData& data : ports_) {
959 if (data.port()->Network()->name() == network_name &&
960 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
961 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700962 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700963 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700964 // These ports will be pruned in PrunePortsAndRemoveCandidates.
965 ports_to_prune.push_back(&data);
966 } else {
967 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700968 }
969 }
970 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700971
972 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100973 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
974 << " low-priority TURN ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700975 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700976 }
977 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000978}
979
Honghai Zhanga74363c2016-07-28 18:06:15 -0700980void BasicPortAllocatorSession::PruneAllPorts() {
981 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700982 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700983 }
984}
985
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800987 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200988 RTC_LOG(LS_INFO) << port->ToString()
989 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000990 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800991 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000992
993 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700994 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000995 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700996 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000997
998 // Moving to COMPLETE state.
999 data->set_complete();
1000 // Send candidate allocation complete signal if this was the last port.
1001 MaybeSignalCandidatesAllocationDone();
1002}
1003
1004void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001005 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001006 RTC_LOG(LS_INFO) << port->ToString()
1007 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001008 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -08001009 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001011 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001012 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001013 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001014
1015 // SignalAddressError is currently sent from StunPort/TurnPort.
1016 // But this signal itself is generic.
1017 data->set_error();
1018 // Send candidate allocation complete signal if this was the last port.
1019 MaybeSignalCandidatesAllocationDone();
1020}
1021
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001022bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001023 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001024
1025 // When binding to any address, before sending packets out, the getsockname
1026 // returns all 0s, but after sending packets, it'll be the NIC used to
1027 // send. All 0s is not a valid ICE candidate address and should be filtered
1028 // out.
1029 if (c.address().IsAnyIP()) {
1030 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001031 }
1032
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001033 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001034 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001035 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001036 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001037 } else if (c.type() == LOCAL_PORT_TYPE) {
1038 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1039 // We allow host candidates if the filter allows server-reflexive
1040 // candidates and the candidate is a public IP. Because we don't generate
1041 // server-reflexive candidates if they have the same IP as the host
1042 // candidate (i.e. when the host candidate is a public IP), filtering to
1043 // only server-reflexive candidates won't work right when the host
1044 // candidates have public IPs.
1045 return true;
1046 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001048 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001049 }
1050 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001051}
1052
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001053bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1054 const Port* port) const {
1055 bool candidate_signalable = CheckCandidateFilter(c);
1056
1057 // When device enumeration is disabled (to prevent non-default IP addresses
1058 // from leaking), we ping from some local candidates even though we don't
1059 // signal them. However, if host candidates are also disabled (for example, to
1060 // prevent even default IP addresses from leaking), we still don't want to
1061 // ping from them, even if device enumeration is disabled. Thus, we check for
1062 // both device enumeration and host candidates being disabled.
1063 bool network_enumeration_disabled = c.address().IsAnyIP();
1064 bool can_ping_from_candidate =
1065 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1066 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1067
1068 return candidate_signalable ||
1069 (network_enumeration_disabled && can_ping_from_candidate &&
1070 !host_candidates_disabled);
1071}
1072
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001073void BasicPortAllocatorSession::OnPortAllocationComplete(
1074 AllocationSequence* seq) {
1075 // Send candidate allocation complete signal if all ports are done.
1076 MaybeSignalCandidatesAllocationDone();
1077}
1078
1079void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001080 if (CandidatesAllocationDone()) {
1081 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001082 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001083 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001084 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1085 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001086 }
1087 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001088 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001089}
1090
Yves Gerey665174f2018-06-19 15:03:05 +02001091void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001092 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093 for (std::vector<PortData>::iterator iter = ports_.begin();
1094 iter != ports_.end(); ++iter) {
1095 if (port == iter->port()) {
1096 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001097 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001098 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001099 return;
1100 }
1101 }
nissec80e7412017-01-11 05:56:46 -08001102 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001103}
1104
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001105BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1106 Port* port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001107 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1108 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109 if (it->port() == port) {
1110 return &*it;
1111 }
1112 }
1113 return NULL;
1114}
1115
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001116std::vector<BasicPortAllocatorSession::PortData*>
1117BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001118 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001119 std::vector<PortData*> unpruned_ports;
1120 for (PortData& port : ports_) {
1121 if (!port.pruned() &&
1122 std::find(networks.begin(), networks.end(),
1123 port.sequence()->network()) != networks.end()) {
1124 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001125 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001126 }
1127 return unpruned_ports;
1128}
1129
1130void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1131 const std::vector<PortData*>& port_data_list) {
1132 std::vector<PortInterface*> pruned_ports;
1133 std::vector<Candidate> removed_candidates;
1134 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001135 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001136 data->Prune();
1137 pruned_ports.push_back(data->port());
1138 if (data->has_pairable_candidate()) {
1139 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001140 // Mark the port as having no pairable candidates so that its candidates
1141 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001142 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001143 }
1144 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001145 if (!pruned_ports.empty()) {
1146 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001147 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001148 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001149 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1150 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001151 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001152 }
1153}
1154
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001155// AllocationSequence
1156
1157AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1158 rtc::Network* network,
1159 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001160 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001161 : session_(session),
1162 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001163 config_(config),
1164 state_(kInit),
1165 flags_(flags),
1166 udp_socket_(),
1167 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001168 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169
Honghai Zhang5048f572016-08-23 15:47:33 -07001170void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001171 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1172 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001173 rtc::SocketAddress(network_->GetBestIP(), 0),
1174 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001175 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001176 udp_socket_->SignalReadPacket.connect(this,
1177 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 }
1179 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1180 // are next available options to setup a communication channel.
1181 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001182}
1183
1184void AllocationSequence::Clear() {
1185 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001186 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187}
1188
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001189void AllocationSequence::OnNetworkFailed() {
1190 RTC_DCHECK(!network_failed_);
1191 network_failed_ = true;
1192 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001193 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001194}
1195
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001196AllocationSequence::~AllocationSequence() {
1197 session_->network_thread()->Clear(this);
1198}
1199
1200void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001201 PortConfiguration* config,
1202 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001203 if (network_failed_) {
1204 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001205 // it won't be equivalent to the new network.
1206 return;
1207 }
1208
deadbeef5c3c1042017-08-04 15:01:57 -07001209 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001210 // Different network setup; nothing is equivalent.
1211 return;
1212 }
1213
1214 // Else turn off the stuff that we've already got covered.
1215
deadbeef1c46a352017-09-27 11:24:05 -07001216 // Every config implicitly specifies local, so turn that off right away if we
1217 // already have a port of the corresponding type. Look for a port that
1218 // matches this AllocationSequence's network, is the right protocol, and
1219 // hasn't encountered an error.
1220 // TODO(deadbeef): This doesn't take into account that there may be another
1221 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1222 // This can happen if, say, there's a network change event right before an
1223 // application-triggered ICE restart. Hopefully this problem will just go
1224 // away if we get rid of the gathering "phases" though, which is planned.
1225 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1226 [this](const BasicPortAllocatorSession::PortData& p) {
1227 return p.port()->Network() == network_ &&
1228 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1229 })) {
1230 *flags |= PORTALLOCATOR_DISABLE_UDP;
1231 }
1232 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1233 [this](const BasicPortAllocatorSession::PortData& p) {
1234 return p.port()->Network() == network_ &&
1235 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1236 })) {
1237 *flags |= PORTALLOCATOR_DISABLE_TCP;
1238 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001239
1240 if (config_ && config) {
1241 if (config_->StunServers() == config->StunServers()) {
1242 // Already got this STUN servers covered.
1243 *flags |= PORTALLOCATOR_DISABLE_STUN;
1244 }
1245 if (!config_->relays.empty()) {
1246 // Already got relays covered.
1247 // NOTE: This will even skip a _different_ set of relay servers if we
1248 // were to be given one, but that never happens in our codebase. Should
1249 // probably get rid of the list in PortConfiguration and just keep a
1250 // single relay server in each one.
1251 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1252 }
1253 }
1254}
1255
1256void AllocationSequence::Start() {
1257 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001258 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001259 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1260 // called next time, we enable all phases if the best IP has since changed.
1261 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001262}
1263
1264void AllocationSequence::Stop() {
1265 // If the port is completed, don't set it to stopped.
1266 if (state_ == kRunning) {
1267 state_ = kStopped;
1268 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1269 }
1270}
1271
1272void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001273 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1274 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001275
deadbeef1c5e6d02017-09-15 17:46:56 -07001276 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277
1278 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001279 RTC_LOG(LS_INFO) << network_->ToString()
1280 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001281
1282 switch (phase_) {
1283 case PHASE_UDP:
1284 CreateUDPPorts();
1285 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001286 break;
1287
1288 case PHASE_RELAY:
1289 CreateRelayPorts();
1290 break;
1291
1292 case PHASE_TCP:
1293 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001294 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001295 break;
1296
1297 default:
nissec80e7412017-01-11 05:56:46 -08001298 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001299 }
1300
1301 if (state() == kRunning) {
1302 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001303 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1304 session_->allocator()->step_delay(),
1305 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306 } else {
1307 // If all phases in AllocationSequence are completed, no allocation
1308 // steps needed further. Canceling pending signal.
1309 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1310 SignalPortAllocationComplete(this);
1311 }
1312}
1313
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314void AllocationSequence::CreateUDPPorts() {
1315 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001316 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317 return;
1318 }
1319
1320 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1321 // is enabled completely.
1322 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001323 bool emit_local_candidate_for_anyaddress =
1324 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001326 port = UDPPort::Create(
1327 session_->network_thread(), session_->socket_factory(), network_,
1328 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001329 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1330 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001331 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001332 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001333 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001334 session_->allocator()->min_port(), session_->allocator()->max_port(),
1335 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001336 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1337 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001338 }
1339
1340 if (port) {
1341 // If shared socket is enabled, STUN candidate will be allocated by the
1342 // UDPPort.
1343 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1344 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001345 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346
1347 // If STUN is not disabled, setting stun server address to port.
1348 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001349 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001350 RTC_LOG(LS_INFO)
1351 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001352 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001353 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001354 }
1355 }
1356 }
1357
1358 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001359 }
1360}
1361
1362void AllocationSequence::CreateTCPPorts() {
1363 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001364 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001365 return;
1366 }
1367
deadbeef5c3c1042017-08-04 15:01:57 -07001368 Port* port = TCPPort::Create(
1369 session_->network_thread(), session_->socket_factory(), network_,
1370 session_->allocator()->min_port(), session_->allocator()->max_port(),
1371 session_->username(), session_->password(),
1372 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001373 if (port) {
1374 session_->AddAllocatedPort(port, this, true);
1375 // Since TCPPort is not created using shared socket, |port| will not be
1376 // added to the dequeue.
1377 }
1378}
1379
1380void AllocationSequence::CreateStunPorts() {
1381 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001382 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001383 return;
1384 }
1385
1386 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1387 return;
1388 }
1389
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001391 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001392 << "AllocationSequence: No STUN server configured, skipping.";
1393 return;
1394 }
1395
deadbeef5c3c1042017-08-04 15:01:57 -07001396 StunPort* port = StunPort::Create(
1397 session_->network_thread(), session_->socket_factory(), network_,
1398 session_->allocator()->min_port(), session_->allocator()->max_port(),
1399 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001400 session_->allocator()->origin(),
1401 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001402 if (port) {
1403 session_->AddAllocatedPort(port, this, true);
1404 // Since StunPort is not created using shared socket, |port| will not be
1405 // added to the dequeue.
1406 }
1407}
1408
1409void AllocationSequence::CreateRelayPorts() {
1410 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001411 RTC_LOG(LS_VERBOSE)
1412 << "AllocationSequence: Relay ports disabled, skipping.";
1413 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001414 }
1415
1416 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1417 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001418 RTC_DCHECK(config_);
1419 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001420 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001421 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 << "AllocationSequence: No relay server configured, skipping.";
1423 return;
1424 }
1425
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001426 for (RelayServerConfig& relay : config_->relays) {
1427 if (relay.type == RELAY_GTURN) {
1428 CreateGturnPort(relay);
1429 } else if (relay.type == RELAY_TURN) {
1430 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001431 } else {
nissec80e7412017-01-11 05:56:46 -08001432 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001433 }
1434 }
1435}
1436
1437void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1438 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001439 RelayPort* port = RelayPort::Create(
1440 session_->network_thread(), session_->socket_factory(), network_,
1441 session_->allocator()->min_port(), session_->allocator()->max_port(),
1442 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001443 if (port) {
1444 // Since RelayPort is not created using shared socket, |port| will not be
1445 // added to the dequeue.
1446 // Note: We must add the allocated port before we add addresses because
1447 // the latter will create candidates that need name and preference
1448 // settings. However, we also can't prepare the address (normally
1449 // done by AddAllocatedPort) until we have these addresses. So we
1450 // wait to do that until below.
1451 session_->AddAllocatedPort(port, this, false);
1452
1453 // Add the addresses of this protocol.
1454 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001455 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001456 ++relay_port) {
1457 port->AddServerAddress(*relay_port);
1458 port->AddExternalAddress(*relay_port);
1459 }
1460 // Start fetching an address for this port.
1461 port->PrepareAddress();
1462 }
1463}
1464
1465void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1466 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001467 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1468 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001469 // Skip UDP connections to relay servers if it's disallowed.
1470 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1471 relay_port->proto == PROTO_UDP) {
1472 continue;
1473 }
1474
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001475 // Do not create a port if the server address family is known and does
1476 // not match the local IP address family.
1477 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001478 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001479 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001480 RTC_LOG(LS_INFO)
1481 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001482 "Server address: "
1483 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001484 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001485 continue;
1486 }
1487
Jonas Oreland202994c2017-12-18 12:10:43 +01001488 CreateRelayPortArgs args;
1489 args.network_thread = session_->network_thread();
1490 args.socket_factory = session_->socket_factory();
1491 args.network = network_;
1492 args.username = session_->username();
1493 args.password = session_->password();
1494 args.server_address = &(*relay_port);
1495 args.config = &config;
1496 args.origin = session_->allocator()->origin();
1497 args.turn_customizer = session_->allocator()->turn_customizer();
1498
1499 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001500 // Shared socket mode must be enabled only for UDP based ports. Hence
1501 // don't pass shared socket for ports which will create TCP sockets.
1502 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1503 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1504 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001505 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001506 port = session_->allocator()->relay_port_factory()->Create(
1507 args, udp_socket_.get());
1508
1509 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001510 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1511 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001512 continue;
1513 }
1514
1515 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001516 // Listen to the port destroyed signal, to allow AllocationSequence to
1517 // remove entrt from it's map.
1518 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1519 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001520 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001521 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001522 session_->allocator()->max_port());
1523
1524 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001525 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1526 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001527 continue;
1528 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001529 }
nisseede5da42017-01-12 05:15:36 -08001530 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001531 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001532 }
1533}
1534
Yves Gerey665174f2018-06-19 15:03:05 +02001535void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1536 const char* data,
1537 size_t size,
1538 const rtc::SocketAddress& remote_addr,
1539 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001540 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001541
1542 bool turn_port_found = false;
1543
1544 // Try to find the TurnPort that matches the remote address. Note that the
1545 // message could be a STUN binding response if the TURN server is also used as
1546 // a STUN server. We don't want to parse every message here to check if it is
1547 // a STUN binding response, so we pass the message to TurnPort regardless of
1548 // the message type. The TurnPort will just ignore the message since it will
1549 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001550 for (auto* port : relay_ports_) {
1551 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001552 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1553 packet_time)) {
1554 return;
1555 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001556 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001557 }
1558 }
1559
1560 if (udp_port_) {
1561 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1562
1563 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1564 // the TURN server is also a STUN server.
1565 if (!turn_port_found ||
1566 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001567 RTC_DCHECK(udp_port_->SharedSocket());
1568 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1569 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001570 }
1571 }
1572}
1573
1574void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1575 if (udp_port_ == port) {
1576 udp_port_ = NULL;
1577 return;
1578 }
1579
Jonas Oreland202994c2017-12-18 12:10:43 +01001580 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1581 if (it != relay_ports_.end()) {
1582 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001583 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001584 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001585 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001586 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001587}
1588
1589// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001590PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1591 const std::string& username,
1592 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001593 : stun_address(stun_address), username(username), password(password) {
1594 if (!stun_address.IsNil())
1595 stun_servers.insert(stun_address);
1596}
1597
1598PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1599 const std::string& username,
1600 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001601 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001602 if (!stun_servers.empty())
1603 stun_address = *(stun_servers.begin());
1604}
1605
Steve Anton7995d8c2017-10-30 16:23:38 -07001606PortConfiguration::~PortConfiguration() = default;
1607
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001608ServerAddresses PortConfiguration::StunServers() {
1609 if (!stun_address.IsNil() &&
1610 stun_servers.find(stun_address) == stun_servers.end()) {
1611 stun_servers.insert(stun_address);
1612 }
deadbeefc5d0d952015-07-16 10:22:21 -07001613 // Every UDP TURN server should also be used as a STUN server.
1614 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1615 for (const rtc::SocketAddress& turn_server : turn_servers) {
1616 if (stun_servers.find(turn_server) == stun_servers.end()) {
1617 stun_servers.insert(turn_server);
1618 }
1619 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001620 return stun_servers;
1621}
1622
1623void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1624 relays.push_back(config);
1625}
1626
Yves Gerey665174f2018-06-19 15:03:05 +02001627bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1628 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001629 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001630 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1631 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001632 if (relay_port->proto == type)
1633 return true;
1634 }
1635 return false;
1636}
1637
1638bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1639 ProtocolType type) const {
1640 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001641 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001642 return true;
1643 }
1644 return false;
1645}
1646
1647ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001648 RelayType turn_type,
1649 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001650 ServerAddresses servers;
1651 for (size_t i = 0; i < relays.size(); ++i) {
1652 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1653 servers.insert(relays[i].ports.front().address);
1654 }
1655 }
1656 return servers;
1657}
1658
1659} // namespace cricket