blob: bca979beeceed37585b5b1bc4a1a32673917e8b8 [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);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200132 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(),
133 0, false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134 Construct();
135}
136
Jonas Oreland202994c2017-12-18 12:10:43 +0100137BasicPortAllocator::BasicPortAllocator(
138 rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700139 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100140 InitRelayPortFactory(nullptr);
141 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800142 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000143 Construct();
144}
145
Jonas Oreland202994c2017-12-18 12:10:43 +0100146BasicPortAllocator::BasicPortAllocator(
147 rtc::NetworkManager* network_manager,
148 rtc::PacketSocketFactory* socket_factory,
149 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700150 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100151 InitRelayPortFactory(nullptr);
152 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800153 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200154 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
155 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 Construct();
157}
158
159BasicPortAllocator::BasicPortAllocator(
160 rtc::NetworkManager* network_manager,
161 const ServerAddresses& stun_servers,
162 const rtc::SocketAddress& relay_address_udp,
163 const rtc::SocketAddress& relay_address_tcp,
164 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700165 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100166 InitRelayPortFactory(nullptr);
167 RTC_DCHECK(relay_port_factory_ != nullptr);
168 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700169 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800171 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800173 }
174 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800176 }
177 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800179 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000180
deadbeef653b8e02015-11-11 12:55:10 -0800181 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700182 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800183 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184
Jonas Orelandbdcee282017-10-10 14:01:40 +0200185 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000186 Construct();
187}
188
189void BasicPortAllocator::Construct() {
190 allow_tcp_listen_ = true;
191}
192
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700193void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
194 IceRegatheringReason reason) {
195 if (!metrics_observer()) {
196 return;
197 }
198 // If the session has not been taken by an active channel, do not report the
199 // metric.
200 for (auto& allocator_session : pooled_sessions()) {
201 if (allocator_session.get() == session) {
202 return;
203 }
204 }
205
206 metrics_observer()->IncrementEnumCounter(
207 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
208 static_cast<int>(IceRegatheringReason::MAX_VALUE));
209}
210
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700212 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800213 // Our created port allocator sessions depend on us, so destroy our remaining
214 // pooled sessions before anything else.
215 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216}
217
Steve Anton7995d8c2017-10-30 16:23:38 -0700218void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
219 // TODO(phoglund): implement support for other types than loopback.
220 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
221 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700222 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700223 network_ignore_mask_ = network_ignore_mask;
224}
225
deadbeefc5d0d952015-07-16 10:22:21 -0700226PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000227 const std::string& content_name, int component,
228 const std::string& ice_ufrag, 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(
459 const rtc::Optional<int>& stun_keepalive_interval) {
460 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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000548void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
549 switch (message->message_id) {
550 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800551 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 GetPortConfigurations();
553 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800555 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
557 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000558 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800559 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560 OnAllocate();
561 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000562 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800563 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000564 OnAllocationSequenceObjectsCreated();
565 break;
566 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800567 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568 OnConfigStop();
569 break;
570 default:
nissec80e7412017-01-11 05:56:46 -0800571 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() {
583 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
584 username(),
585 password());
586
deadbeef653b8e02015-11-11 12:55:10 -0800587 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
588 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589 }
590 ConfigReady(config);
591}
592
593void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700594 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595}
596
597// Adds a configuration to the list.
598void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800599 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000600 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800601 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602
603 AllocatePorts();
604}
605
606void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800607 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608
609 // If any of the allocated ports have not completed the candidates allocation,
610 // mark those as error. Since session doesn't need any new candidates
611 // at this stage of the allocation, it's safe to discard any new candidates.
612 bool send_signal = false;
613 for (std::vector<PortData>::iterator it = ports_.begin();
614 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700615 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000616 // Updating port state to error, which didn't finish allocating candidates
617 // yet.
618 it->set_error();
619 send_signal = true;
620 }
621 }
622
623 // Did we stop any running sequences?
624 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
625 it != sequences_.end() && !send_signal; ++it) {
626 if ((*it)->state() == AllocationSequence::kStopped) {
627 send_signal = true;
628 }
629 }
630
631 // If we stopped anything that was running, send a done signal now.
632 if (send_signal) {
633 MaybeSignalCandidatesAllocationDone();
634 }
635}
636
637void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800638 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700639 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640}
641
642void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700643 if (network_manager_started_ && !IsStopped()) {
644 bool disable_equivalent_phases = true;
645 DoAllocate(disable_equivalent_phases);
646 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000647
648 allocation_started_ = true;
649}
650
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700651std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
652 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700653 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800654 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700655 // If the network permission state is BLOCKED, we just act as if the flag has
656 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700657 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700658 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700659 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
660 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000661 // If the adapter enumeration is disabled, we'll just bind to any address
662 // instead of specific NIC. This is to ensure the same routing for http
663 // traffic by OS is also used here to avoid any local or public IP leakage
664 // during stun process.
665 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700666 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000667 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700668 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800669 // If network enumeration fails, use the ANY address as a fallback, so we
670 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700671 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
672 // set, we'll use ANY address candidates either way.
673 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800674 network_manager->GetAnyAddressNetworks(&networks);
675 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000676 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100677 // Filter out link-local networks if needed.
678 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700679 NetworkFilter link_local_filter(
680 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
681 "link-local");
682 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100683 }
deadbeef3427f532017-07-26 16:09:33 -0700684 // Do some more filtering, depending on the network ignore mask and "disable
685 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700686 NetworkFilter ignored_filter(
687 [this](rtc::Network* network) {
688 return allocator_->network_ignore_mask() & network->type();
689 },
690 "ignored");
691 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700692 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
693 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700694 for (rtc::Network* network : networks) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800695 // Don't determine the lowest cost from a link-local network.
696 // On iOS, a device connected to the computer will get a link-local
697 // network for communicating with the computer, however this network can't
698 // be used to connect to a peer outside the network.
699 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
700 continue;
701 }
honghaiz60347052016-05-31 18:29:12 -0700702 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
703 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700704 NetworkFilter costly_filter(
705 [lowest_cost](rtc::Network* network) {
706 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
707 },
708 "costly");
709 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700710 }
deadbeef3427f532017-07-26 16:09:33 -0700711 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
712 // default, it's 5), remove networks to ensure that limit is satisfied.
713 //
714 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
715 // networks, we could try to choose a set that's "most likely to work". It's
716 // hard to define what that means though; it's not just "lowest cost".
717 // Alternatively, we could just focus on making our ICE pinging logic smarter
718 // such that this filtering isn't necessary in the first place.
719 int ipv6_networks = 0;
720 for (auto it = networks.begin(); it != networks.end();) {
721 if ((*it)->prefix().family() == AF_INET6) {
722 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
723 it = networks.erase(it);
724 continue;
725 } else {
726 ++ipv6_networks;
727 }
728 }
729 ++it;
730 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700731 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700732}
733
734// For each network, see if we have a sequence that covers it already. If not,
735// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700736void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700737 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700738 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 RTC_LOG(LS_WARNING)
741 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742 done_signal_needed = true;
743 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100744 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700745 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200746 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200747 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
749 // If all the ports are disabled we should just fire the allocation
750 // done event and return.
751 done_signal_needed = true;
752 break;
753 }
754
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755 if (!config || config->relays.empty()) {
756 // No relay ports specified in this config.
757 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
758 }
759
760 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000762 // Skip IPv6 networks unless the flag's been set.
763 continue;
764 }
765
zhihuangb09b3f92017-03-07 14:40:51 -0800766 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
767 networks[i]->GetBestIP().family() == AF_INET6 &&
768 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
769 // Skip IPv6 Wi-Fi networks unless the flag's been set.
770 continue;
771 }
772
Steve Anton300bf8e2017-07-14 10:13:10 -0700773 if (disable_equivalent) {
774 // Disable phases that would only create ports equivalent to
775 // ones that we have already made.
776 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000777
Steve Anton300bf8e2017-07-14 10:13:10 -0700778 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
779 // New AllocationSequence would have nothing to do, so don't make it.
780 continue;
781 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782 }
783
784 AllocationSequence* sequence =
785 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786 sequence->SignalPortAllocationComplete.connect(
787 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700788 sequence->Init();
789 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000790 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700791 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792 }
793 }
794 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700795 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000796 }
797}
798
799void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700800 std::vector<rtc::Network*> networks = GetNetworks();
801 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700802 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700803 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700804 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700805 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700806 std::find(networks.begin(), networks.end(), sequence->network()) ==
807 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700808 sequence->OnNetworkFailed();
809 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700810 }
811 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700812 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
813 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100814 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
815 << " ports because their networks were gone";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700816 PrunePortsAndRemoveCandidates(ports_to_prune);
817 }
honghaiz8c404fa2015-09-28 07:59:43 -0700818
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700819 if (allocation_started_ && !IsStopped()) {
820 if (network_manager_started_) {
821 // If the network manager has started, it must be regathering.
822 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
823 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700824 bool disable_equivalent_phases = true;
825 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700826 }
827
Honghai Zhang5048f572016-08-23 15:47:33 -0700828 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100829 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700830 network_manager_started_ = true;
831 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832}
833
834void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200835 rtc::Network* network,
836 PortConfiguration* config,
837 uint32_t* flags) {
838 for (uint32_t i = 0; i < sequences_.size() &&
839 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
840 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 sequences_[i]->DisableEquivalentPhases(network, config, flags);
842 }
843}
844
845void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
846 AllocationSequence * seq,
847 bool prepare_address) {
848 if (!port)
849 return;
850
Mirko Bonadei675513b2017-11-09 11:09:25 +0100851 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700855 if (allocator_->proxy().type != rtc::PROXY_NONE)
856 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700857 port->set_send_retransmit_count_attribute(
858 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000860 PortData data(port, seq);
861 ports_.push_back(data);
862
863 port->SignalCandidateReady.connect(
864 this, &BasicPortAllocatorSession::OnCandidateReady);
865 port->SignalPortComplete.connect(this,
866 &BasicPortAllocatorSession::OnPortComplete);
867 port->SignalDestroyed.connect(this,
868 &BasicPortAllocatorSession::OnPortDestroyed);
869 port->SignalPortError.connect(
870 this, &BasicPortAllocatorSession::OnPortError);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200871 RTC_LOG(LS_INFO) << port->ToString()
872 << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000873
874 if (prepare_address)
875 port->PrepareAddress();
876}
877
878void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
879 allocation_sequences_created_ = true;
880 // Send candidate allocation complete signal if we have no sequences.
881 MaybeSignalCandidatesAllocationDone();
882}
883
884void BasicPortAllocatorSession::OnCandidateReady(
885 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800886 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800888 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200889 RTC_LOG(LS_INFO) << port->ToString()
890 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700892 // already done with gathering.
893 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700895 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700896 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700897 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700898
danilchapf4e8cf02016-06-30 01:55:03 -0700899 // Mark that the port has a pairable candidate, either because we have a
900 // usable candidate from the port, or simply because the port is bound to the
901 // any address and therefore has no host candidate. This will trigger the port
902 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700903 // checks. If port has already been marked as having a pairable candidate,
904 // do nothing here.
905 // Note: We should check whether any candidates may become ready after this
906 // because there we will check whether the candidate is generated by the ready
907 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700908 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700909 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700910 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700911
912 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700913 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700914 }
915 // If the current port is not pruned yet, SignalPortReady.
916 if (!data->pruned()) {
Jonas Olssond7d762d2018-03-28 09:47:51 +0200917 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700918 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700919 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700920 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700921 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700922
deadbeef1c5e6d02017-09-15 17:46:56 -0700923 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700924 std::vector<Candidate> candidates;
925 candidates.push_back(SanitizeRelatedAddress(c));
926 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700927 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100928 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700929 }
930
931 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700932 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700933 MaybeSignalCandidatesAllocationDone();
934 }
935}
936
937Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
938 const std::string& network_name) const {
939 Port* best_turn_port = nullptr;
940 for (const PortData& data : ports_) {
941 if (data.port()->Network()->name() == network_name &&
942 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
943 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
944 best_turn_port = data.port();
945 }
946 }
947 return best_turn_port;
948}
949
950bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700951 // Note: We determine the same network based only on their network names. So
952 // if an IPv4 address and an IPv6 address have the same network name, they
953 // are considered the same network here.
954 const std::string& network_name = newly_pairable_turn_port->Network()->name();
955 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
956 // |port| is already in the list of ports, so the best port cannot be nullptr.
957 RTC_CHECK(best_turn_port != nullptr);
958
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700959 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700960 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700961 for (PortData& data : ports_) {
962 if (data.port()->Network()->name() == network_name &&
963 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
964 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700965 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700966 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700967 // These ports will be pruned in PrunePortsAndRemoveCandidates.
968 ports_to_prune.push_back(&data);
969 } else {
970 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700971 }
972 }
973 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700974
975 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100976 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
977 << " low-priority TURN ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700978 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700979 }
980 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981}
982
Honghai Zhanga74363c2016-07-28 18:06:15 -0700983void BasicPortAllocatorSession::PruneAllPorts() {
984 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700985 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700986 }
987}
988
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000989void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800990 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200991 RTC_LOG(LS_INFO) << port->ToString()
992 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000993 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800994 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000995
996 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700997 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000998 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700999 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001000
1001 // Moving to COMPLETE state.
1002 data->set_complete();
1003 // Send candidate allocation complete signal if this was the last port.
1004 MaybeSignalCandidatesAllocationDone();
1005}
1006
1007void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001008 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001009 RTC_LOG(LS_INFO) << port->ToString()
1010 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001011 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -08001012 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001013 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001014 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001015 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001016 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001017
1018 // SignalAddressError is currently sent from StunPort/TurnPort.
1019 // But this signal itself is generic.
1020 data->set_error();
1021 // Send candidate allocation complete signal if this was the last port.
1022 MaybeSignalCandidatesAllocationDone();
1023}
1024
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001025bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001026 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001027
1028 // When binding to any address, before sending packets out, the getsockname
1029 // returns all 0s, but after sending packets, it'll be the NIC used to
1030 // send. All 0s is not a valid ICE candidate address and should be filtered
1031 // out.
1032 if (c.address().IsAnyIP()) {
1033 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001034 }
1035
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001036 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001037 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001038 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001039 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001040 } else if (c.type() == LOCAL_PORT_TYPE) {
1041 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1042 // We allow host candidates if the filter allows server-reflexive
1043 // candidates and the candidate is a public IP. Because we don't generate
1044 // server-reflexive candidates if they have the same IP as the host
1045 // candidate (i.e. when the host candidate is a public IP), filtering to
1046 // only server-reflexive candidates won't work right when the host
1047 // candidates have public IPs.
1048 return true;
1049 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001050
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001051 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001052 }
1053 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001054}
1055
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001056bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1057 const Port* port) const {
1058 bool candidate_signalable = CheckCandidateFilter(c);
1059
1060 // When device enumeration is disabled (to prevent non-default IP addresses
1061 // from leaking), we ping from some local candidates even though we don't
1062 // signal them. However, if host candidates are also disabled (for example, to
1063 // prevent even default IP addresses from leaking), we still don't want to
1064 // ping from them, even if device enumeration is disabled. Thus, we check for
1065 // both device enumeration and host candidates being disabled.
1066 bool network_enumeration_disabled = c.address().IsAnyIP();
1067 bool can_ping_from_candidate =
1068 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1069 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1070
1071 return candidate_signalable ||
1072 (network_enumeration_disabled && can_ping_from_candidate &&
1073 !host_candidates_disabled);
1074}
1075
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076void BasicPortAllocatorSession::OnPortAllocationComplete(
1077 AllocationSequence* seq) {
1078 // Send candidate allocation complete signal if all ports are done.
1079 MaybeSignalCandidatesAllocationDone();
1080}
1081
1082void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001083 if (CandidatesAllocationDone()) {
1084 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001085 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001086 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001087 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1088 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001089 }
1090 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001091 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001092}
1093
1094void BasicPortAllocatorSession::OnPortDestroyed(
1095 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001096 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 for (std::vector<PortData>::iterator iter = ports_.begin();
1098 iter != ports_.end(); ++iter) {
1099 if (port == iter->port()) {
1100 ports_.erase(iter);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001101 RTC_LOG(LS_INFO) << port->ToString()
1102 << ": Removed port from allocator ("
1103 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001104 return;
1105 }
1106 }
nissec80e7412017-01-11 05:56:46 -08001107 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108}
1109
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1111 Port* port) {
1112 for (std::vector<PortData>::iterator it = ports_.begin();
1113 it != ports_.end(); ++it) {
1114 if (it->port() == port) {
1115 return &*it;
1116 }
1117 }
1118 return NULL;
1119}
1120
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001121std::vector<BasicPortAllocatorSession::PortData*>
1122BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001123 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001124 std::vector<PortData*> unpruned_ports;
1125 for (PortData& port : ports_) {
1126 if (!port.pruned() &&
1127 std::find(networks.begin(), networks.end(),
1128 port.sequence()->network()) != networks.end()) {
1129 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001130 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001131 }
1132 return unpruned_ports;
1133}
1134
1135void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1136 const std::vector<PortData*>& port_data_list) {
1137 std::vector<PortInterface*> pruned_ports;
1138 std::vector<Candidate> removed_candidates;
1139 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001140 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001141 data->Prune();
1142 pruned_ports.push_back(data->port());
1143 if (data->has_pairable_candidate()) {
1144 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001145 // Mark the port as having no pairable candidates so that its candidates
1146 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001147 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001148 }
1149 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001150 if (!pruned_ports.empty()) {
1151 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001152 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001153 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001154 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1155 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001156 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001157 }
1158}
1159
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001160// AllocationSequence
1161
1162AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1163 rtc::Network* network,
1164 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001165 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001166 : session_(session),
1167 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 config_(config),
1169 state_(kInit),
1170 flags_(flags),
1171 udp_socket_(),
1172 udp_port_(NULL),
1173 phase_(0) {
1174}
1175
Honghai Zhang5048f572016-08-23 15:47:33 -07001176void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001177 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1178 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001179 rtc::SocketAddress(network_->GetBestIP(), 0),
1180 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001181 if (udp_socket_) {
1182 udp_socket_->SignalReadPacket.connect(
1183 this, &AllocationSequence::OnReadPacket);
1184 }
1185 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1186 // are next available options to setup a communication channel.
1187 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001188}
1189
1190void AllocationSequence::Clear() {
1191 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001192 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001193}
1194
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001195void AllocationSequence::OnNetworkFailed() {
1196 RTC_DCHECK(!network_failed_);
1197 network_failed_ = true;
1198 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001199 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001200}
1201
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001202AllocationSequence::~AllocationSequence() {
1203 session_->network_thread()->Clear(this);
1204}
1205
1206void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001207 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001208 if (network_failed_) {
1209 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001210 // it won't be equivalent to the new network.
1211 return;
1212 }
1213
deadbeef5c3c1042017-08-04 15:01:57 -07001214 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001215 // Different network setup; nothing is equivalent.
1216 return;
1217 }
1218
1219 // Else turn off the stuff that we've already got covered.
1220
deadbeef1c46a352017-09-27 11:24:05 -07001221 // Every config implicitly specifies local, so turn that off right away if we
1222 // already have a port of the corresponding type. Look for a port that
1223 // matches this AllocationSequence's network, is the right protocol, and
1224 // hasn't encountered an error.
1225 // TODO(deadbeef): This doesn't take into account that there may be another
1226 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1227 // This can happen if, say, there's a network change event right before an
1228 // application-triggered ICE restart. Hopefully this problem will just go
1229 // away if we get rid of the gathering "phases" though, which is planned.
1230 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1231 [this](const BasicPortAllocatorSession::PortData& p) {
1232 return p.port()->Network() == network_ &&
1233 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1234 })) {
1235 *flags |= PORTALLOCATOR_DISABLE_UDP;
1236 }
1237 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1238 [this](const BasicPortAllocatorSession::PortData& p) {
1239 return p.port()->Network() == network_ &&
1240 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1241 })) {
1242 *flags |= PORTALLOCATOR_DISABLE_TCP;
1243 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244
1245 if (config_ && config) {
1246 if (config_->StunServers() == config->StunServers()) {
1247 // Already got this STUN servers covered.
1248 *flags |= PORTALLOCATOR_DISABLE_STUN;
1249 }
1250 if (!config_->relays.empty()) {
1251 // Already got relays covered.
1252 // NOTE: This will even skip a _different_ set of relay servers if we
1253 // were to be given one, but that never happens in our codebase. Should
1254 // probably get rid of the list in PortConfiguration and just keep a
1255 // single relay server in each one.
1256 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1257 }
1258 }
1259}
1260
1261void AllocationSequence::Start() {
1262 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001263 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001264 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1265 // called next time, we enable all phases if the best IP has since changed.
1266 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001267}
1268
1269void AllocationSequence::Stop() {
1270 // If the port is completed, don't set it to stopped.
1271 if (state_ == kRunning) {
1272 state_ = kStopped;
1273 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1274 }
1275}
1276
1277void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001278 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1279 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001280
deadbeef1c5e6d02017-09-15 17:46:56 -07001281 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001282
1283 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001284 RTC_LOG(LS_INFO) << network_->ToString()
1285 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001286
1287 switch (phase_) {
1288 case PHASE_UDP:
1289 CreateUDPPorts();
1290 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001291 break;
1292
1293 case PHASE_RELAY:
1294 CreateRelayPorts();
1295 break;
1296
1297 case PHASE_TCP:
1298 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001299 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001300 break;
1301
1302 default:
nissec80e7412017-01-11 05:56:46 -08001303 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001304 }
1305
1306 if (state() == kRunning) {
1307 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001308 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1309 session_->allocator()->step_delay(),
1310 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001311 } else {
1312 // If all phases in AllocationSequence are completed, no allocation
1313 // steps needed further. Canceling pending signal.
1314 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1315 SignalPortAllocationComplete(this);
1316 }
1317}
1318
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001319void AllocationSequence::CreateUDPPorts() {
1320 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001321 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 return;
1323 }
1324
1325 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1326 // is enabled completely.
1327 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001328 bool emit_local_candidate_for_anyaddress =
1329 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001331 port = UDPPort::Create(
1332 session_->network_thread(), session_->socket_factory(), network_,
1333 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001334 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1335 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001337 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001338 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001339 session_->allocator()->min_port(), session_->allocator()->max_port(),
1340 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001341 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1342 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001343 }
1344
1345 if (port) {
1346 // If shared socket is enabled, STUN candidate will be allocated by the
1347 // UDPPort.
1348 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1349 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001350 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001351
1352 // If STUN is not disabled, setting stun server address to port.
1353 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001354 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001355 RTC_LOG(LS_INFO)
1356 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001357 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001358 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001359 }
1360 }
1361 }
1362
1363 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001364 }
1365}
1366
1367void AllocationSequence::CreateTCPPorts() {
1368 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001369 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370 return;
1371 }
1372
deadbeef5c3c1042017-08-04 15:01:57 -07001373 Port* port = TCPPort::Create(
1374 session_->network_thread(), session_->socket_factory(), network_,
1375 session_->allocator()->min_port(), session_->allocator()->max_port(),
1376 session_->username(), session_->password(),
1377 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378 if (port) {
1379 session_->AddAllocatedPort(port, this, true);
1380 // Since TCPPort is not created using shared socket, |port| will not be
1381 // added to the dequeue.
1382 }
1383}
1384
1385void AllocationSequence::CreateStunPorts() {
1386 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001387 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 return;
1389 }
1390
1391 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1392 return;
1393 }
1394
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001395 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001396 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397 << "AllocationSequence: No STUN server configured, skipping.";
1398 return;
1399 }
1400
deadbeef5c3c1042017-08-04 15:01:57 -07001401 StunPort* port = StunPort::Create(
1402 session_->network_thread(), session_->socket_factory(), network_,
1403 session_->allocator()->min_port(), session_->allocator()->max_port(),
1404 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001405 session_->allocator()->origin(),
1406 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001407 if (port) {
1408 session_->AddAllocatedPort(port, this, true);
1409 // Since StunPort is not created using shared socket, |port| will not be
1410 // added to the dequeue.
1411 }
1412}
1413
1414void AllocationSequence::CreateRelayPorts() {
1415 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001416 RTC_LOG(LS_VERBOSE)
1417 << "AllocationSequence: Relay ports disabled, skipping.";
1418 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001419 }
1420
1421 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1422 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001423 RTC_DCHECK(config_);
1424 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001425 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001426 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001427 << "AllocationSequence: No relay server configured, skipping.";
1428 return;
1429 }
1430
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001431 for (RelayServerConfig& relay : config_->relays) {
1432 if (relay.type == RELAY_GTURN) {
1433 CreateGturnPort(relay);
1434 } else if (relay.type == RELAY_TURN) {
1435 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001436 } else {
nissec80e7412017-01-11 05:56:46 -08001437 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001438 }
1439 }
1440}
1441
1442void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1443 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001444 RelayPort* port = RelayPort::Create(
1445 session_->network_thread(), session_->socket_factory(), network_,
1446 session_->allocator()->min_port(), session_->allocator()->max_port(),
1447 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001448 if (port) {
1449 // Since RelayPort is not created using shared socket, |port| will not be
1450 // added to the dequeue.
1451 // Note: We must add the allocated port before we add addresses because
1452 // the latter will create candidates that need name and preference
1453 // settings. However, we also can't prepare the address (normally
1454 // done by AddAllocatedPort) until we have these addresses. So we
1455 // wait to do that until below.
1456 session_->AddAllocatedPort(port, this, false);
1457
1458 // Add the addresses of this protocol.
1459 PortList::const_iterator relay_port;
1460 for (relay_port = config.ports.begin();
1461 relay_port != config.ports.end();
1462 ++relay_port) {
1463 port->AddServerAddress(*relay_port);
1464 port->AddExternalAddress(*relay_port);
1465 }
1466 // Start fetching an address for this port.
1467 port->PrepareAddress();
1468 }
1469}
1470
1471void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1472 PortList::const_iterator relay_port;
1473 for (relay_port = config.ports.begin();
1474 relay_port != config.ports.end(); ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001475 // Skip UDP connections to relay servers if it's disallowed.
1476 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1477 relay_port->proto == PROTO_UDP) {
1478 continue;
1479 }
1480
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001481 // Do not create a port if the server address family is known and does
1482 // not match the local IP address family.
1483 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001484 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001485 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001486 RTC_LOG(LS_INFO)
1487 << "Server and local address families are not compatible. "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001488 "Server address: " << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001489 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001490 continue;
1491 }
1492
Jonas Oreland202994c2017-12-18 12:10:43 +01001493 CreateRelayPortArgs args;
1494 args.network_thread = session_->network_thread();
1495 args.socket_factory = session_->socket_factory();
1496 args.network = network_;
1497 args.username = session_->username();
1498 args.password = session_->password();
1499 args.server_address = &(*relay_port);
1500 args.config = &config;
1501 args.origin = session_->allocator()->origin();
1502 args.turn_customizer = session_->allocator()->turn_customizer();
1503
1504 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001505 // Shared socket mode must be enabled only for UDP based ports. Hence
1506 // don't pass shared socket for ports which will create TCP sockets.
1507 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1508 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1509 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001510 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001511 port = session_->allocator()->relay_port_factory()->Create(
1512 args, udp_socket_.get());
1513
1514 if (!port) {
1515 RTC_LOG(LS_WARNING)
1516 << "Failed to create relay port with "
1517 << args.server_address->address.ToString();
1518 continue;
1519 }
1520
1521 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001522 // Listen to the port destroyed signal, to allow AllocationSequence to
1523 // remove entrt from it's map.
1524 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1525 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001526 port = session_->allocator()->relay_port_factory()->Create(
1527 args,
1528 session_->allocator()->min_port(),
1529 session_->allocator()->max_port());
1530
1531 if (!port) {
1532 RTC_LOG(LS_WARNING)
1533 << "Failed to create relay port with "
1534 << args.server_address->address.ToString();
1535 continue;
1536 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001537 }
nisseede5da42017-01-12 05:15:36 -08001538 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001539 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001540 }
1541}
1542
1543void AllocationSequence::OnReadPacket(
1544 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1545 const rtc::SocketAddress& remote_addr,
1546 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001547 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001548
1549 bool turn_port_found = false;
1550
1551 // Try to find the TurnPort that matches the remote address. Note that the
1552 // message could be a STUN binding response if the TURN server is also used as
1553 // a STUN server. We don't want to parse every message here to check if it is
1554 // a STUN binding response, so we pass the message to TurnPort regardless of
1555 // the message type. The TurnPort will just ignore the message since it will
1556 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001557 for (auto* port : relay_ports_) {
1558 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001559 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1560 packet_time)) {
1561 return;
1562 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001563 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001564 }
1565 }
1566
1567 if (udp_port_) {
1568 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1569
1570 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1571 // the TURN server is also a STUN server.
1572 if (!turn_port_found ||
1573 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001574 RTC_DCHECK(udp_port_->SharedSocket());
1575 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1576 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001577 }
1578 }
1579}
1580
1581void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1582 if (udp_port_ == port) {
1583 udp_port_ = NULL;
1584 return;
1585 }
1586
Jonas Oreland202994c2017-12-18 12:10:43 +01001587 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1588 if (it != relay_ports_.end()) {
1589 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001590 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001591 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001592 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001593 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001594}
1595
1596// PortConfiguration
1597PortConfiguration::PortConfiguration(
1598 const rtc::SocketAddress& stun_address,
1599 const std::string& username,
1600 const std::string& password)
1601 : stun_address(stun_address), username(username), password(password) {
1602 if (!stun_address.IsNil())
1603 stun_servers.insert(stun_address);
1604}
1605
1606PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1607 const std::string& username,
1608 const std::string& password)
1609 : stun_servers(stun_servers),
1610 username(username),
1611 password(password) {
1612 if (!stun_servers.empty())
1613 stun_address = *(stun_servers.begin());
1614}
1615
Steve Anton7995d8c2017-10-30 16:23:38 -07001616PortConfiguration::~PortConfiguration() = default;
1617
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001618ServerAddresses PortConfiguration::StunServers() {
1619 if (!stun_address.IsNil() &&
1620 stun_servers.find(stun_address) == stun_servers.end()) {
1621 stun_servers.insert(stun_address);
1622 }
deadbeefc5d0d952015-07-16 10:22:21 -07001623 // Every UDP TURN server should also be used as a STUN server.
1624 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1625 for (const rtc::SocketAddress& turn_server : turn_servers) {
1626 if (stun_servers.find(turn_server) == stun_servers.end()) {
1627 stun_servers.insert(turn_server);
1628 }
1629 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001630 return stun_servers;
1631}
1632
1633void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1634 relays.push_back(config);
1635}
1636
1637bool PortConfiguration::SupportsProtocol(
1638 const RelayServerConfig& relay, ProtocolType type) const {
1639 PortList::const_iterator relay_port;
1640 for (relay_port = relay.ports.begin();
1641 relay_port != relay.ports.end();
1642 ++relay_port) {
1643 if (relay_port->proto == type)
1644 return true;
1645 }
1646 return false;
1647}
1648
1649bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1650 ProtocolType type) const {
1651 for (size_t i = 0; i < relays.size(); ++i) {
1652 if (relays[i].type == turn_type &&
1653 SupportsProtocol(relays[i], type))
1654 return true;
1655 }
1656 return false;
1657}
1658
1659ServerAddresses PortConfiguration::GetRelayServerAddresses(
1660 RelayType turn_type, ProtocolType type) const {
1661 ServerAddresses servers;
1662 for (size_t i = 0; i < relays.size(); ++i) {
1663 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1664 servers.insert(relays[i].ports.front().address);
1665 }
1666 }
1667 return servers;
1668}
1669
1670} // namespace cricket