blob: 01acf42cdd7501ae431904d6fa8325ffb14c6989 [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>
Steve Anton6c38cc72017-11-29 10:25:58 -080014#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000015#include <string>
16#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/umametrics.h"
19#include "p2p/base/basicpacketsocketfactory.h"
20#include "p2p/base/common.h"
21#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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092} // namespace
93
94namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020095const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070096 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
97 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098
99// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200100BasicPortAllocator::BasicPortAllocator(
101 rtc::NetworkManager* network_manager,
102 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100103 webrtc::TurnCustomizer* customizer,
104 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700105 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100106 InitRelayPortFactory(relay_port_factory);
107 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800108 RTC_DCHECK(network_manager_ != nullptr);
109 RTC_DCHECK(socket_factory_ != nullptr);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200110 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(),
111 0, false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000112 Construct();
113}
114
Jonas Oreland202994c2017-12-18 12:10:43 +0100115BasicPortAllocator::BasicPortAllocator(
116 rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700117 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100118 InitRelayPortFactory(nullptr);
119 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800120 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000121 Construct();
122}
123
Jonas Oreland202994c2017-12-18 12:10:43 +0100124BasicPortAllocator::BasicPortAllocator(
125 rtc::NetworkManager* network_manager,
126 rtc::PacketSocketFactory* socket_factory,
127 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700128 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100129 InitRelayPortFactory(nullptr);
130 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800131 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200132 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
133 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134 Construct();
135}
136
137BasicPortAllocator::BasicPortAllocator(
138 rtc::NetworkManager* network_manager,
139 const ServerAddresses& stun_servers,
140 const rtc::SocketAddress& relay_address_udp,
141 const rtc::SocketAddress& relay_address_tcp,
142 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700143 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100144 InitRelayPortFactory(nullptr);
145 RTC_DCHECK(relay_port_factory_ != nullptr);
146 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700147 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800149 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800151 }
152 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800154 }
155 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800157 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000158
deadbeef653b8e02015-11-11 12:55:10 -0800159 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700160 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800161 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162
Jonas Orelandbdcee282017-10-10 14:01:40 +0200163 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 Construct();
165}
166
167void BasicPortAllocator::Construct() {
168 allow_tcp_listen_ = true;
169}
170
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700171void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
172 IceRegatheringReason reason) {
173 if (!metrics_observer()) {
174 return;
175 }
176 // If the session has not been taken by an active channel, do not report the
177 // metric.
178 for (auto& allocator_session : pooled_sessions()) {
179 if (allocator_session.get() == session) {
180 return;
181 }
182 }
183
184 metrics_observer()->IncrementEnumCounter(
185 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
186 static_cast<int>(IceRegatheringReason::MAX_VALUE));
187}
188
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800190 // Our created port allocator sessions depend on us, so destroy our remaining
191 // pooled sessions before anything else.
192 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193}
194
Steve Anton7995d8c2017-10-30 16:23:38 -0700195void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
196 // TODO(phoglund): implement support for other types than loopback.
197 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
198 // Then remove set_network_ignore_list from NetworkManager.
199 network_ignore_mask_ = network_ignore_mask;
200}
201
deadbeefc5d0d952015-07-16 10:22:21 -0700202PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 const std::string& content_name, int component,
204 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700205 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700207 session->SignalIceRegathering.connect(this,
208 &BasicPortAllocator::OnIceRegathering);
209 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
213 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
214 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700215 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200216 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218
Jonas Oreland202994c2017-12-18 12:10:43 +0100219void BasicPortAllocator::InitRelayPortFactory(
220 RelayPortFactoryInterface* relay_port_factory) {
221 if (relay_port_factory != nullptr) {
222 relay_port_factory_ = relay_port_factory;
223 } else {
224 default_relay_port_factory_.reset(new TurnPortFactory());
225 relay_port_factory_ = default_relay_port_factory_.get();
226 }
227}
228
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229// BasicPortAllocatorSession
230BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700231 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232 const std::string& content_name,
233 int component,
234 const std::string& ice_ufrag,
235 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700236 : PortAllocatorSession(content_name,
237 component,
238 ice_ufrag,
239 ice_pwd,
240 allocator->flags()),
241 allocator_(allocator),
242 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000243 socket_factory_(allocator->socket_factory()),
244 allocation_started_(false),
245 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700246 allocation_sequences_created_(false),
247 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000248 allocator_->network_manager()->SignalNetworksChanged.connect(
249 this, &BasicPortAllocatorSession::OnNetworksChanged);
250 allocator_->network_manager()->StartUpdating();
251}
252
253BasicPortAllocatorSession::~BasicPortAllocatorSession() {
254 allocator_->network_manager()->StopUpdating();
255 if (network_thread_ != NULL)
256 network_thread_->Clear(this);
257
Peter Boström0c4e06b2015-10-07 12:23:21 +0200258 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259 // AllocationSequence should clear it's map entry for turn ports before
260 // ports are destroyed.
261 sequences_[i]->Clear();
262 }
263
264 std::vector<PortData>::iterator it;
265 for (it = ports_.begin(); it != ports_.end(); it++)
266 delete it->port();
267
Peter Boström0c4e06b2015-10-07 12:23:21 +0200268 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000269 delete configs_[i];
270
Peter Boström0c4e06b2015-10-07 12:23:21 +0200271 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000272 delete sequences_[i];
273}
274
Steve Anton7995d8c2017-10-30 16:23:38 -0700275BasicPortAllocator* BasicPortAllocatorSession::allocator() {
276 return allocator_;
277}
278
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700279void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
280 if (filter == candidate_filter_) {
281 return;
282 }
283 // We assume the filter will only change from "ALL" to something else.
284 RTC_DCHECK(candidate_filter_ == CF_ALL);
285 candidate_filter_ = filter;
286 for (PortData& port : ports_) {
287 if (!port.has_pairable_candidate()) {
288 continue;
289 }
290 const auto& candidates = port.port()->Candidates();
291 // Setting a filter may cause a ready port to become non-ready
292 // if it no longer has any pairable candidates.
293 if (!std::any_of(candidates.begin(), candidates.end(),
294 [this, &port](const Candidate& candidate) {
295 return CandidatePairable(candidate, port.port());
296 })) {
297 port.set_has_pairable_candidate(false);
298 }
299 }
300}
301
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302void BasicPortAllocatorSession::StartGettingPorts() {
303 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700304 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 if (!socket_factory_) {
306 owned_socket_factory_.reset(
307 new rtc::BasicPacketSocketFactory(network_thread_));
308 socket_factory_ = owned_socket_factory_.get();
309 }
310
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700311 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700312
Mirko Bonadei675513b2017-11-09 11:09:25 +0100313 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
314 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000315}
316
317void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800318 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700319 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700320 // Note: this must be called after ClearGettingPorts because both may set the
321 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700322 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700323}
324
325void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800326 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700328 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000329 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700330 }
deadbeefb60a8192016-08-24 15:15:00 -0700331 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700332 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700333}
334
Steve Anton7995d8c2017-10-30 16:23:38 -0700335bool BasicPortAllocatorSession::IsGettingPorts() {
336 return state_ == SessionState::GATHERING;
337}
338
339bool BasicPortAllocatorSession::IsCleared() const {
340 return state_ == SessionState::CLEARED;
341}
342
343bool BasicPortAllocatorSession::IsStopped() const {
344 return state_ == SessionState::STOPPED;
345}
346
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700347std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
348 std::vector<rtc::Network*> networks = GetNetworks();
349
350 // A network interface may have both IPv4 and IPv6 networks. Only if
351 // neither of the networks has any connections, the network interface
352 // is considered failed and need to be regathered on.
353 std::set<std::string> networks_with_connection;
354 for (const PortData& data : ports_) {
355 Port* port = data.port();
356 if (!port->connections().empty()) {
357 networks_with_connection.insert(port->Network()->name());
358 }
359 }
360
361 networks.erase(
362 std::remove_if(networks.begin(), networks.end(),
363 [networks_with_connection](rtc::Network* network) {
364 // If a network does not have any connection, it is
365 // considered failed.
366 return networks_with_connection.find(network->name()) !=
367 networks_with_connection.end();
368 }),
369 networks.end());
370 return networks;
371}
372
373void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
374 // Find the list of networks that have no connection.
375 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
376 if (failed_networks.empty()) {
377 return;
378 }
379
Mirko Bonadei675513b2017-11-09 11:09:25 +0100380 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700381
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700382 // Mark a sequence as "network failed" if its network is in the list of failed
383 // networks, so that it won't be considered as equivalent when the session
384 // regathers ports and candidates.
385 for (AllocationSequence* sequence : sequences_) {
386 if (!sequence->network_failed() &&
387 std::find(failed_networks.begin(), failed_networks.end(),
388 sequence->network()) != failed_networks.end()) {
389 sequence->set_network_failed();
390 }
391 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700392
393 bool disable_equivalent_phases = true;
394 Regather(failed_networks, disable_equivalent_phases,
395 IceRegatheringReason::NETWORK_FAILURE);
396}
397
398void BasicPortAllocatorSession::RegatherOnAllNetworks() {
399 std::vector<rtc::Network*> networks = GetNetworks();
400 if (networks.empty()) {
401 return;
402 }
403
Mirko Bonadei675513b2017-11-09 11:09:25 +0100404 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700405
406 // We expect to generate candidates that are equivalent to what we have now.
407 // Force DoAllocate to generate them instead of skipping.
408 bool disable_equivalent_phases = false;
409 Regather(networks, disable_equivalent_phases,
410 IceRegatheringReason::OCCASIONAL_REFRESH);
411}
412
413void BasicPortAllocatorSession::Regather(
414 const std::vector<rtc::Network*>& networks,
415 bool disable_equivalent_phases,
416 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700417 // Remove ports from being used locally and send signaling to remove
418 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700419 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700420 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100421 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700422 PrunePortsAndRemoveCandidates(ports_to_prune);
423 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700424
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700425 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700426 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700427
Steve Anton300bf8e2017-07-14 10:13:10 -0700428 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700429 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430}
431
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800432void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
433 const rtc::Optional<int>& stun_keepalive_interval) {
434 auto ports = ReadyPorts();
435 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800436 // The port type and protocol can be used to identify different subclasses
437 // of Port in the current implementation. Note that a TCPPort has the type
438 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
439 if (port->Type() == STUN_PORT_TYPE ||
440 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800441 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
442 stun_keepalive_interval);
443 }
444 }
445}
446
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700447std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
448 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700449 for (const PortData& data : ports_) {
450 if (data.ready()) {
451 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700452 }
453 }
454 return ret;
455}
456
457std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
458 std::vector<Candidate> candidates;
459 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700460 if (!data.ready()) {
461 continue;
462 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700463 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700464 }
465 return candidates;
466}
467
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700468void BasicPortAllocatorSession::GetCandidatesFromPort(
469 const PortData& data,
470 std::vector<Candidate>* candidates) const {
471 RTC_CHECK(candidates != nullptr);
472 for (const Candidate& candidate : data.port()->Candidates()) {
473 if (!CheckCandidateFilter(candidate)) {
474 continue;
475 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700476 candidates->push_back(SanitizeRelatedAddress(candidate));
477 }
478}
479
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700480Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
481 const Candidate& c) const {
482 Candidate copy = c;
483 // If adapter enumeration is disabled or host candidates are disabled,
484 // clear the raddr of STUN candidates to avoid local address leakage.
485 bool filter_stun_related_address =
486 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
487 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
488 !(candidate_filter_ & CF_HOST);
489 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
490 // to avoid reflexive address leakage.
491 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
492 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
493 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
494 copy.set_related_address(
495 rtc::EmptySocketAddressWithFamily(copy.address().family()));
496 }
497 return copy;
498}
499
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700500bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
501 // Done only if all required AllocationSequence objects
502 // are created.
503 if (!allocation_sequences_created_) {
504 return false;
505 }
506
507 // Check that all port allocation sequences are complete (not running).
508 if (std::any_of(sequences_.begin(), sequences_.end(),
509 [](const AllocationSequence* sequence) {
510 return sequence->state() == AllocationSequence::kRunning;
511 })) {
512 return false;
513 }
514
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700515 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700516 // expected candidates. Session will trigger candidates allocation complete
517 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700518 return std::none_of(ports_.begin(), ports_.end(),
519 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700520}
521
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000522void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
523 switch (message->message_id) {
524 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800525 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000526 GetPortConfigurations();
527 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000528 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800529 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
531 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800533 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000534 OnAllocate();
535 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800537 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000538 OnAllocationSequenceObjectsCreated();
539 break;
540 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800541 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000542 OnConfigStop();
543 break;
544 default:
nissec80e7412017-01-11 05:56:46 -0800545 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000546 }
547}
548
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700549void BasicPortAllocatorSession::UpdateIceParametersInternal() {
550 for (PortData& port : ports_) {
551 port.port()->set_content_name(content_name());
552 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
553 }
554}
555
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556void BasicPortAllocatorSession::GetPortConfigurations() {
557 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
558 username(),
559 password());
560
deadbeef653b8e02015-11-11 12:55:10 -0800561 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
562 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563 }
564 ConfigReady(config);
565}
566
567void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700568 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569}
570
571// Adds a configuration to the list.
572void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800573 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000574 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800575 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000576
577 AllocatePorts();
578}
579
580void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800581 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582
583 // If any of the allocated ports have not completed the candidates allocation,
584 // mark those as error. Since session doesn't need any new candidates
585 // at this stage of the allocation, it's safe to discard any new candidates.
586 bool send_signal = false;
587 for (std::vector<PortData>::iterator it = ports_.begin();
588 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700589 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 // Updating port state to error, which didn't finish allocating candidates
591 // yet.
592 it->set_error();
593 send_signal = true;
594 }
595 }
596
597 // Did we stop any running sequences?
598 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
599 it != sequences_.end() && !send_signal; ++it) {
600 if ((*it)->state() == AllocationSequence::kStopped) {
601 send_signal = true;
602 }
603 }
604
605 // If we stopped anything that was running, send a done signal now.
606 if (send_signal) {
607 MaybeSignalCandidatesAllocationDone();
608 }
609}
610
611void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800612 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700613 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614}
615
616void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700617 if (network_manager_started_ && !IsStopped()) {
618 bool disable_equivalent_phases = true;
619 DoAllocate(disable_equivalent_phases);
620 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621
622 allocation_started_ = true;
623}
624
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700625std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
626 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700627 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800628 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700629 // If the network permission state is BLOCKED, we just act as if the flag has
630 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700631 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700632 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700633 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
634 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000635 // If the adapter enumeration is disabled, we'll just bind to any address
636 // instead of specific NIC. This is to ensure the same routing for http
637 // traffic by OS is also used here to avoid any local or public IP leakage
638 // during stun process.
639 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700640 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000641 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700642 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800643 // If network enumeration fails, use the ANY address as a fallback, so we
644 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700645 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
646 // set, we'll use ANY address candidates either way.
647 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800648 network_manager->GetAnyAddressNetworks(&networks);
649 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000650 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100651 // Filter out link-local networks if needed.
652 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
653 networks.erase(std::remove_if(networks.begin(), networks.end(),
654 [](rtc::Network* network) {
655 return IPIsLinkLocal(network->prefix());
656 }),
657 networks.end());
658 }
deadbeef3427f532017-07-26 16:09:33 -0700659 // Do some more filtering, depending on the network ignore mask and "disable
660 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700661 networks.erase(std::remove_if(networks.begin(), networks.end(),
662 [this](rtc::Network* network) {
663 return allocator_->network_ignore_mask() &
664 network->type();
665 }),
666 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700667 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
668 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700669 for (rtc::Network* network : networks) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800670 // Don't determine the lowest cost from a link-local network.
671 // On iOS, a device connected to the computer will get a link-local
672 // network for communicating with the computer, however this network can't
673 // be used to connect to a peer outside the network.
674 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
675 continue;
676 }
honghaiz60347052016-05-31 18:29:12 -0700677 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
678 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700679 networks.erase(std::remove_if(networks.begin(), networks.end(),
680 [lowest_cost](rtc::Network* network) {
681 return network->GetCost() >
682 lowest_cost + rtc::kNetworkCostLow;
683 }),
684 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700685 }
deadbeef3427f532017-07-26 16:09:33 -0700686 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
687 // default, it's 5), remove networks to ensure that limit is satisfied.
688 //
689 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
690 // networks, we could try to choose a set that's "most likely to work". It's
691 // hard to define what that means though; it's not just "lowest cost".
692 // Alternatively, we could just focus on making our ICE pinging logic smarter
693 // such that this filtering isn't necessary in the first place.
694 int ipv6_networks = 0;
695 for (auto it = networks.begin(); it != networks.end();) {
696 if ((*it)->prefix().family() == AF_INET6) {
697 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
698 it = networks.erase(it);
699 continue;
700 } else {
701 ++ipv6_networks;
702 }
703 }
704 ++it;
705 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700706 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700707}
708
709// For each network, see if we have a sequence that covers it already. If not,
710// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700711void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700712 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700713 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000714 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100715 RTC_LOG(LS_WARNING)
716 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000717 done_signal_needed = true;
718 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100719 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700720 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200721 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200722 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
724 // If all the ports are disabled we should just fire the allocation
725 // done event and return.
726 done_signal_needed = true;
727 break;
728 }
729
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000730 if (!config || config->relays.empty()) {
731 // No relay ports specified in this config.
732 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
733 }
734
735 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737 // Skip IPv6 networks unless the flag's been set.
738 continue;
739 }
740
zhihuangb09b3f92017-03-07 14:40:51 -0800741 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
742 networks[i]->GetBestIP().family() == AF_INET6 &&
743 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
744 // Skip IPv6 Wi-Fi networks unless the flag's been set.
745 continue;
746 }
747
Steve Anton300bf8e2017-07-14 10:13:10 -0700748 if (disable_equivalent) {
749 // Disable phases that would only create ports equivalent to
750 // ones that we have already made.
751 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752
Steve Anton300bf8e2017-07-14 10:13:10 -0700753 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
754 // New AllocationSequence would have nothing to do, so don't make it.
755 continue;
756 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 }
758
759 AllocationSequence* sequence =
760 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761 sequence->SignalPortAllocationComplete.connect(
762 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700763 sequence->Init();
764 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000765 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700766 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000767 }
768 }
769 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700770 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771 }
772}
773
774void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700775 std::vector<rtc::Network*> networks = GetNetworks();
776 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700777 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700778 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700779 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700780 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700781 std::find(networks.begin(), networks.end(), sequence->network()) ==
782 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700783 sequence->OnNetworkFailed();
784 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700785 }
786 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700787 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
788 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
790 << " ports because their networks were gone";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700791 PrunePortsAndRemoveCandidates(ports_to_prune);
792 }
honghaiz8c404fa2015-09-28 07:59:43 -0700793
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700794 if (allocation_started_ && !IsStopped()) {
795 if (network_manager_started_) {
796 // If the network manager has started, it must be regathering.
797 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
798 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700799 bool disable_equivalent_phases = true;
800 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700801 }
802
Honghai Zhang5048f572016-08-23 15:47:33 -0700803 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100804 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700805 network_manager_started_ = true;
806 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000807}
808
809void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200810 rtc::Network* network,
811 PortConfiguration* config,
812 uint32_t* flags) {
813 for (uint32_t i = 0; i < sequences_.size() &&
814 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
815 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000816 sequences_[i]->DisableEquivalentPhases(network, config, flags);
817 }
818}
819
820void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
821 AllocationSequence * seq,
822 bool prepare_address) {
823 if (!port)
824 return;
825
Mirko Bonadei675513b2017-11-09 11:09:25 +0100826 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700828 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000829 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700830 if (allocator_->proxy().type != rtc::PROXY_NONE)
831 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700832 port->set_send_retransmit_count_attribute(
833 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 PortData data(port, seq);
836 ports_.push_back(data);
837
838 port->SignalCandidateReady.connect(
839 this, &BasicPortAllocatorSession::OnCandidateReady);
840 port->SignalPortComplete.connect(this,
841 &BasicPortAllocatorSession::OnPortComplete);
842 port->SignalDestroyed.connect(this,
843 &BasicPortAllocatorSession::OnPortDestroyed);
844 port->SignalPortError.connect(
845 this, &BasicPortAllocatorSession::OnPortError);
846 LOG_J(LS_INFO, port) << "Added port to allocator";
847
848 if (prepare_address)
849 port->PrepareAddress();
850}
851
852void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
853 allocation_sequences_created_ = true;
854 // Send candidate allocation complete signal if we have no sequences.
855 MaybeSignalCandidatesAllocationDone();
856}
857
858void BasicPortAllocatorSession::OnCandidateReady(
859 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800860 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000861 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800862 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700863 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700865 // already done with gathering.
866 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100867 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700868 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700869 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700870 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700871
danilchapf4e8cf02016-06-30 01:55:03 -0700872 // Mark that the port has a pairable candidate, either because we have a
873 // usable candidate from the port, or simply because the port is bound to the
874 // any address and therefore has no host candidate. This will trigger the port
875 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700876 // checks. If port has already been marked as having a pairable candidate,
877 // do nothing here.
878 // Note: We should check whether any candidates may become ready after this
879 // because there we will check whether the candidate is generated by the ready
880 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700881 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700882 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700883 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700884
885 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700886 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700887 }
888 // If the current port is not pruned yet, SignalPortReady.
889 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700890 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700891 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700892 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700893 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700894 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700895
deadbeef1c5e6d02017-09-15 17:46:56 -0700896 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700897 std::vector<Candidate> candidates;
898 candidates.push_back(SanitizeRelatedAddress(c));
899 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700900 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100901 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700902 }
903
904 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700905 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700906 MaybeSignalCandidatesAllocationDone();
907 }
908}
909
910Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
911 const std::string& network_name) const {
912 Port* best_turn_port = nullptr;
913 for (const PortData& data : ports_) {
914 if (data.port()->Network()->name() == network_name &&
915 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
916 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
917 best_turn_port = data.port();
918 }
919 }
920 return best_turn_port;
921}
922
923bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700924 // Note: We determine the same network based only on their network names. So
925 // if an IPv4 address and an IPv6 address have the same network name, they
926 // are considered the same network here.
927 const std::string& network_name = newly_pairable_turn_port->Network()->name();
928 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
929 // |port| is already in the list of ports, so the best port cannot be nullptr.
930 RTC_CHECK(best_turn_port != nullptr);
931
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700932 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700933 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700934 for (PortData& data : ports_) {
935 if (data.port()->Network()->name() == network_name &&
936 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
937 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700938 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700939 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700940 // These ports will be pruned in PrunePortsAndRemoveCandidates.
941 ports_to_prune.push_back(&data);
942 } else {
943 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700944 }
945 }
946 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700947
948 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100949 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
950 << " low-priority TURN ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700951 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700952 }
953 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000954}
955
Honghai Zhanga74363c2016-07-28 18:06:15 -0700956void BasicPortAllocatorSession::PruneAllPorts() {
957 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700958 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700959 }
960}
961
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800963 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700964 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000965 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800966 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967
968 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700969 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700971 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000972
973 // Moving to COMPLETE state.
974 data->set_complete();
975 // Send candidate allocation complete signal if this was the last port.
976 MaybeSignalCandidatesAllocationDone();
977}
978
979void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800980 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700981 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000982 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800983 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000984 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700985 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700987 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988
989 // SignalAddressError is currently sent from StunPort/TurnPort.
990 // But this signal itself is generic.
991 data->set_error();
992 // Send candidate allocation complete signal if this was the last port.
993 MaybeSignalCandidatesAllocationDone();
994}
995
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700996bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700997 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000998
999 // When binding to any address, before sending packets out, the getsockname
1000 // returns all 0s, but after sending packets, it'll be the NIC used to
1001 // send. All 0s is not a valid ICE candidate address and should be filtered
1002 // out.
1003 if (c.address().IsAnyIP()) {
1004 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001005 }
1006
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001007 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001008 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001009 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001010 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001011 } else if (c.type() == LOCAL_PORT_TYPE) {
1012 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1013 // We allow host candidates if the filter allows server-reflexive
1014 // candidates and the candidate is a public IP. Because we don't generate
1015 // server-reflexive candidates if they have the same IP as the host
1016 // candidate (i.e. when the host candidate is a public IP), filtering to
1017 // only server-reflexive candidates won't work right when the host
1018 // candidates have public IPs.
1019 return true;
1020 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001021
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001022 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001023 }
1024 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001025}
1026
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001027bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1028 const Port* port) const {
1029 bool candidate_signalable = CheckCandidateFilter(c);
1030
1031 // When device enumeration is disabled (to prevent non-default IP addresses
1032 // from leaking), we ping from some local candidates even though we don't
1033 // signal them. However, if host candidates are also disabled (for example, to
1034 // prevent even default IP addresses from leaking), we still don't want to
1035 // ping from them, even if device enumeration is disabled. Thus, we check for
1036 // both device enumeration and host candidates being disabled.
1037 bool network_enumeration_disabled = c.address().IsAnyIP();
1038 bool can_ping_from_candidate =
1039 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1040 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1041
1042 return candidate_signalable ||
1043 (network_enumeration_disabled && can_ping_from_candidate &&
1044 !host_candidates_disabled);
1045}
1046
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047void BasicPortAllocatorSession::OnPortAllocationComplete(
1048 AllocationSequence* seq) {
1049 // Send candidate allocation complete signal if all ports are done.
1050 MaybeSignalCandidatesAllocationDone();
1051}
1052
1053void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001054 if (CandidatesAllocationDone()) {
1055 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001056 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001057 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001058 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1059 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001060 }
1061 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001062 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001063}
1064
1065void BasicPortAllocatorSession::OnPortDestroyed(
1066 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001067 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001068 for (std::vector<PortData>::iterator iter = ports_.begin();
1069 iter != ports_.end(); ++iter) {
1070 if (port == iter->port()) {
1071 ports_.erase(iter);
1072 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1073 << static_cast<int>(ports_.size()) << " remaining)";
1074 return;
1075 }
1076 }
nissec80e7412017-01-11 05:56:46 -08001077 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001078}
1079
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1081 Port* port) {
1082 for (std::vector<PortData>::iterator it = ports_.begin();
1083 it != ports_.end(); ++it) {
1084 if (it->port() == port) {
1085 return &*it;
1086 }
1087 }
1088 return NULL;
1089}
1090
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001091std::vector<BasicPortAllocatorSession::PortData*>
1092BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001093 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001094 std::vector<PortData*> unpruned_ports;
1095 for (PortData& port : ports_) {
1096 if (!port.pruned() &&
1097 std::find(networks.begin(), networks.end(),
1098 port.sequence()->network()) != networks.end()) {
1099 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001100 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001101 }
1102 return unpruned_ports;
1103}
1104
1105void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1106 const std::vector<PortData*>& port_data_list) {
1107 std::vector<PortInterface*> pruned_ports;
1108 std::vector<Candidate> removed_candidates;
1109 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001110 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001111 data->Prune();
1112 pruned_ports.push_back(data->port());
1113 if (data->has_pairable_candidate()) {
1114 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001115 // Mark the port as having no pairable candidates so that its candidates
1116 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001117 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001118 }
1119 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001120 if (!pruned_ports.empty()) {
1121 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001122 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001123 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001124 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1125 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001126 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001127 }
1128}
1129
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001130// AllocationSequence
1131
1132AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1133 rtc::Network* network,
1134 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001135 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001136 : session_(session),
1137 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001138 config_(config),
1139 state_(kInit),
1140 flags_(flags),
1141 udp_socket_(),
1142 udp_port_(NULL),
1143 phase_(0) {
1144}
1145
Honghai Zhang5048f572016-08-23 15:47:33 -07001146void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001147 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1148 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001149 rtc::SocketAddress(network_->GetBestIP(), 0),
1150 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001151 if (udp_socket_) {
1152 udp_socket_->SignalReadPacket.connect(
1153 this, &AllocationSequence::OnReadPacket);
1154 }
1155 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1156 // are next available options to setup a communication channel.
1157 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001158}
1159
1160void AllocationSequence::Clear() {
1161 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001162 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001163}
1164
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001165void AllocationSequence::OnNetworkFailed() {
1166 RTC_DCHECK(!network_failed_);
1167 network_failed_ = true;
1168 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001169 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001170}
1171
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001172AllocationSequence::~AllocationSequence() {
1173 session_->network_thread()->Clear(this);
1174}
1175
1176void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001177 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001178 if (network_failed_) {
1179 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001180 // it won't be equivalent to the new network.
1181 return;
1182 }
1183
deadbeef5c3c1042017-08-04 15:01:57 -07001184 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001185 // Different network setup; nothing is equivalent.
1186 return;
1187 }
1188
1189 // Else turn off the stuff that we've already got covered.
1190
deadbeef1c46a352017-09-27 11:24:05 -07001191 // Every config implicitly specifies local, so turn that off right away if we
1192 // already have a port of the corresponding type. Look for a port that
1193 // matches this AllocationSequence's network, is the right protocol, and
1194 // hasn't encountered an error.
1195 // TODO(deadbeef): This doesn't take into account that there may be another
1196 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1197 // This can happen if, say, there's a network change event right before an
1198 // application-triggered ICE restart. Hopefully this problem will just go
1199 // away if we get rid of the gathering "phases" though, which is planned.
1200 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1201 [this](const BasicPortAllocatorSession::PortData& p) {
1202 return p.port()->Network() == network_ &&
1203 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1204 })) {
1205 *flags |= PORTALLOCATOR_DISABLE_UDP;
1206 }
1207 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1208 [this](const BasicPortAllocatorSession::PortData& p) {
1209 return p.port()->Network() == network_ &&
1210 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1211 })) {
1212 *flags |= PORTALLOCATOR_DISABLE_TCP;
1213 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001214
1215 if (config_ && config) {
1216 if (config_->StunServers() == config->StunServers()) {
1217 // Already got this STUN servers covered.
1218 *flags |= PORTALLOCATOR_DISABLE_STUN;
1219 }
1220 if (!config_->relays.empty()) {
1221 // Already got relays covered.
1222 // NOTE: This will even skip a _different_ set of relay servers if we
1223 // were to be given one, but that never happens in our codebase. Should
1224 // probably get rid of the list in PortConfiguration and just keep a
1225 // single relay server in each one.
1226 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1227 }
1228 }
1229}
1230
1231void AllocationSequence::Start() {
1232 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001233 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001234 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1235 // called next time, we enable all phases if the best IP has since changed.
1236 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237}
1238
1239void AllocationSequence::Stop() {
1240 // If the port is completed, don't set it to stopped.
1241 if (state_ == kRunning) {
1242 state_ = kStopped;
1243 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1244 }
1245}
1246
1247void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001248 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1249 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001250
deadbeef1c5e6d02017-09-15 17:46:56 -07001251 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001252
1253 // Perform all of the phases in the current step.
1254 LOG_J(LS_INFO, network_) << "Allocation Phase="
1255 << PHASE_NAMES[phase_];
1256
1257 switch (phase_) {
1258 case PHASE_UDP:
1259 CreateUDPPorts();
1260 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001261 break;
1262
1263 case PHASE_RELAY:
1264 CreateRelayPorts();
1265 break;
1266
1267 case PHASE_TCP:
1268 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001269 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270 break;
1271
1272 default:
nissec80e7412017-01-11 05:56:46 -08001273 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001274 }
1275
1276 if (state() == kRunning) {
1277 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001278 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1279 session_->allocator()->step_delay(),
1280 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001281 } else {
1282 // If all phases in AllocationSequence are completed, no allocation
1283 // steps needed further. Canceling pending signal.
1284 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1285 SignalPortAllocationComplete(this);
1286 }
1287}
1288
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001289void AllocationSequence::CreateUDPPorts() {
1290 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001291 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001292 return;
1293 }
1294
1295 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1296 // is enabled completely.
1297 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001298 bool emit_local_candidate_for_anyaddress =
1299 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001300 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001301 port = UDPPort::Create(
1302 session_->network_thread(), session_->socket_factory(), network_,
1303 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001304 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1305 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001307 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001308 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001309 session_->allocator()->min_port(), session_->allocator()->max_port(),
1310 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001311 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1312 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313 }
1314
1315 if (port) {
1316 // If shared socket is enabled, STUN candidate will be allocated by the
1317 // UDPPort.
1318 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1319 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001320 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001321
1322 // If STUN is not disabled, setting stun server address to port.
1323 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001324 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001325 RTC_LOG(LS_INFO)
1326 << "AllocationSequence: UDPPort will be handling the "
1327 << "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001328 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001329 }
1330 }
1331 }
1332
1333 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001334 }
1335}
1336
1337void AllocationSequence::CreateTCPPorts() {
1338 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001339 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001340 return;
1341 }
1342
deadbeef5c3c1042017-08-04 15:01:57 -07001343 Port* port = TCPPort::Create(
1344 session_->network_thread(), session_->socket_factory(), network_,
1345 session_->allocator()->min_port(), session_->allocator()->max_port(),
1346 session_->username(), session_->password(),
1347 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001348 if (port) {
1349 session_->AddAllocatedPort(port, this, true);
1350 // Since TCPPort is not created using shared socket, |port| will not be
1351 // added to the dequeue.
1352 }
1353}
1354
1355void AllocationSequence::CreateStunPorts() {
1356 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001357 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001358 return;
1359 }
1360
1361 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1362 return;
1363 }
1364
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001365 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001366 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001367 << "AllocationSequence: No STUN server configured, skipping.";
1368 return;
1369 }
1370
deadbeef5c3c1042017-08-04 15:01:57 -07001371 StunPort* port = StunPort::Create(
1372 session_->network_thread(), session_->socket_factory(), network_,
1373 session_->allocator()->min_port(), session_->allocator()->max_port(),
1374 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001375 session_->allocator()->origin(),
1376 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001377 if (port) {
1378 session_->AddAllocatedPort(port, this, true);
1379 // Since StunPort is not created using shared socket, |port| will not be
1380 // added to the dequeue.
1381 }
1382}
1383
1384void AllocationSequence::CreateRelayPorts() {
1385 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001386 RTC_LOG(LS_VERBOSE)
1387 << "AllocationSequence: Relay ports disabled, skipping.";
1388 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001389 }
1390
1391 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1392 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001393 RTC_DCHECK(config_);
1394 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001395 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001396 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397 << "AllocationSequence: No relay server configured, skipping.";
1398 return;
1399 }
1400
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001401 for (RelayServerConfig& relay : config_->relays) {
1402 if (relay.type == RELAY_GTURN) {
1403 CreateGturnPort(relay);
1404 } else if (relay.type == RELAY_TURN) {
1405 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 } else {
nissec80e7412017-01-11 05:56:46 -08001407 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001408 }
1409 }
1410}
1411
1412void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1413 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001414 RelayPort* port = RelayPort::Create(
1415 session_->network_thread(), session_->socket_factory(), network_,
1416 session_->allocator()->min_port(), session_->allocator()->max_port(),
1417 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001418 if (port) {
1419 // Since RelayPort is not created using shared socket, |port| will not be
1420 // added to the dequeue.
1421 // Note: We must add the allocated port before we add addresses because
1422 // the latter will create candidates that need name and preference
1423 // settings. However, we also can't prepare the address (normally
1424 // done by AddAllocatedPort) until we have these addresses. So we
1425 // wait to do that until below.
1426 session_->AddAllocatedPort(port, this, false);
1427
1428 // Add the addresses of this protocol.
1429 PortList::const_iterator relay_port;
1430 for (relay_port = config.ports.begin();
1431 relay_port != config.ports.end();
1432 ++relay_port) {
1433 port->AddServerAddress(*relay_port);
1434 port->AddExternalAddress(*relay_port);
1435 }
1436 // Start fetching an address for this port.
1437 port->PrepareAddress();
1438 }
1439}
1440
1441void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1442 PortList::const_iterator relay_port;
1443 for (relay_port = config.ports.begin();
1444 relay_port != config.ports.end(); ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001445 // Skip UDP connections to relay servers if it's disallowed.
1446 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1447 relay_port->proto == PROTO_UDP) {
1448 continue;
1449 }
1450
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001451 // Do not create a port if the server address family is known and does
1452 // not match the local IP address family.
1453 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001454 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001455 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001456 RTC_LOG(LS_INFO)
1457 << "Server and local address families are not compatible. "
1458 << "Server address: " << relay_port->address.ipaddr().ToString()
1459 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001460 continue;
1461 }
1462
Jonas Oreland202994c2017-12-18 12:10:43 +01001463 CreateRelayPortArgs args;
1464 args.network_thread = session_->network_thread();
1465 args.socket_factory = session_->socket_factory();
1466 args.network = network_;
1467 args.username = session_->username();
1468 args.password = session_->password();
1469 args.server_address = &(*relay_port);
1470 args.config = &config;
1471 args.origin = session_->allocator()->origin();
1472 args.turn_customizer = session_->allocator()->turn_customizer();
1473
1474 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001475 // Shared socket mode must be enabled only for UDP based ports. Hence
1476 // don't pass shared socket for ports which will create TCP sockets.
1477 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1478 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1479 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001480 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001481 port = session_->allocator()->relay_port_factory()->Create(
1482 args, udp_socket_.get());
1483
1484 if (!port) {
1485 RTC_LOG(LS_WARNING)
1486 << "Failed to create relay port with "
1487 << args.server_address->address.ToString();
1488 continue;
1489 }
1490
1491 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492 // Listen to the port destroyed signal, to allow AllocationSequence to
1493 // remove entrt from it's map.
1494 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1495 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001496 port = session_->allocator()->relay_port_factory()->Create(
1497 args,
1498 session_->allocator()->min_port(),
1499 session_->allocator()->max_port());
1500
1501 if (!port) {
1502 RTC_LOG(LS_WARNING)
1503 << "Failed to create relay port with "
1504 << args.server_address->address.ToString();
1505 continue;
1506 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001507 }
nisseede5da42017-01-12 05:15:36 -08001508 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001509 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001510 }
1511}
1512
1513void AllocationSequence::OnReadPacket(
1514 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1515 const rtc::SocketAddress& remote_addr,
1516 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001517 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001518
1519 bool turn_port_found = false;
1520
1521 // Try to find the TurnPort that matches the remote address. Note that the
1522 // message could be a STUN binding response if the TURN server is also used as
1523 // a STUN server. We don't want to parse every message here to check if it is
1524 // a STUN binding response, so we pass the message to TurnPort regardless of
1525 // the message type. The TurnPort will just ignore the message since it will
1526 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001527 for (auto* port : relay_ports_) {
1528 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001529 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1530 packet_time)) {
1531 return;
1532 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001533 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001534 }
1535 }
1536
1537 if (udp_port_) {
1538 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1539
1540 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1541 // the TURN server is also a STUN server.
1542 if (!turn_port_found ||
1543 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001544 RTC_DCHECK(udp_port_->SharedSocket());
1545 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1546 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001547 }
1548 }
1549}
1550
1551void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1552 if (udp_port_ == port) {
1553 udp_port_ = NULL;
1554 return;
1555 }
1556
Jonas Oreland202994c2017-12-18 12:10:43 +01001557 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1558 if (it != relay_ports_.end()) {
1559 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001560 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001561 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001562 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001563 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001564}
1565
1566// PortConfiguration
1567PortConfiguration::PortConfiguration(
1568 const rtc::SocketAddress& stun_address,
1569 const std::string& username,
1570 const std::string& password)
1571 : stun_address(stun_address), username(username), password(password) {
1572 if (!stun_address.IsNil())
1573 stun_servers.insert(stun_address);
1574}
1575
1576PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1577 const std::string& username,
1578 const std::string& password)
1579 : stun_servers(stun_servers),
1580 username(username),
1581 password(password) {
1582 if (!stun_servers.empty())
1583 stun_address = *(stun_servers.begin());
1584}
1585
Steve Anton7995d8c2017-10-30 16:23:38 -07001586PortConfiguration::~PortConfiguration() = default;
1587
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001588ServerAddresses PortConfiguration::StunServers() {
1589 if (!stun_address.IsNil() &&
1590 stun_servers.find(stun_address) == stun_servers.end()) {
1591 stun_servers.insert(stun_address);
1592 }
deadbeefc5d0d952015-07-16 10:22:21 -07001593 // Every UDP TURN server should also be used as a STUN server.
1594 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1595 for (const rtc::SocketAddress& turn_server : turn_servers) {
1596 if (stun_servers.find(turn_server) == stun_servers.end()) {
1597 stun_servers.insert(turn_server);
1598 }
1599 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001600 return stun_servers;
1601}
1602
1603void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1604 relays.push_back(config);
1605}
1606
1607bool PortConfiguration::SupportsProtocol(
1608 const RelayServerConfig& relay, ProtocolType type) const {
1609 PortList::const_iterator relay_port;
1610 for (relay_port = relay.ports.begin();
1611 relay_port != relay.ports.end();
1612 ++relay_port) {
1613 if (relay_port->proto == type)
1614 return true;
1615 }
1616 return false;
1617}
1618
1619bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1620 ProtocolType type) const {
1621 for (size_t i = 0; i < relays.size(); ++i) {
1622 if (relays[i].type == turn_type &&
1623 SupportsProtocol(relays[i], type))
1624 return true;
1625 }
1626 return false;
1627}
1628
1629ServerAddresses PortConfiguration::GetRelayServerAddresses(
1630 RelayType turn_type, ProtocolType type) const {
1631 ServerAddresses servers;
1632 for (size_t i = 0; i < relays.size(); ++i) {
1633 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1634 servers.insert(relays[i].ports.front().address);
1635 }
1636 }
1637 return servers;
1638}
1639
1640} // namespace cricket