blob: 86cec8fb34141bf0e5208fc1c00435ca511beeda [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
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700432std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
433 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700434 for (const PortData& data : ports_) {
435 if (data.ready()) {
436 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700437 }
438 }
439 return ret;
440}
441
442std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
443 std::vector<Candidate> candidates;
444 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700445 if (!data.ready()) {
446 continue;
447 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700448 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700449 }
450 return candidates;
451}
452
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700453void BasicPortAllocatorSession::GetCandidatesFromPort(
454 const PortData& data,
455 std::vector<Candidate>* candidates) const {
456 RTC_CHECK(candidates != nullptr);
457 for (const Candidate& candidate : data.port()->Candidates()) {
458 if (!CheckCandidateFilter(candidate)) {
459 continue;
460 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700461 candidates->push_back(SanitizeRelatedAddress(candidate));
462 }
463}
464
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700465Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
466 const Candidate& c) const {
467 Candidate copy = c;
468 // If adapter enumeration is disabled or host candidates are disabled,
469 // clear the raddr of STUN candidates to avoid local address leakage.
470 bool filter_stun_related_address =
471 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
472 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
473 !(candidate_filter_ & CF_HOST);
474 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
475 // to avoid reflexive address leakage.
476 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
477 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
478 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
479 copy.set_related_address(
480 rtc::EmptySocketAddressWithFamily(copy.address().family()));
481 }
482 return copy;
483}
484
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700485bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
486 // Done only if all required AllocationSequence objects
487 // are created.
488 if (!allocation_sequences_created_) {
489 return false;
490 }
491
492 // Check that all port allocation sequences are complete (not running).
493 if (std::any_of(sequences_.begin(), sequences_.end(),
494 [](const AllocationSequence* sequence) {
495 return sequence->state() == AllocationSequence::kRunning;
496 })) {
497 return false;
498 }
499
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700500 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700501 // expected candidates. Session will trigger candidates allocation complete
502 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700503 return std::none_of(ports_.begin(), ports_.end(),
504 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700505}
506
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000507void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
508 switch (message->message_id) {
509 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800510 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000511 GetPortConfigurations();
512 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000513 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800514 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000515 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
516 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000517 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800518 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000519 OnAllocate();
520 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000521 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800522 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000523 OnAllocationSequenceObjectsCreated();
524 break;
525 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800526 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000527 OnConfigStop();
528 break;
529 default:
nissec80e7412017-01-11 05:56:46 -0800530 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000531 }
532}
533
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700534void BasicPortAllocatorSession::UpdateIceParametersInternal() {
535 for (PortData& port : ports_) {
536 port.port()->set_content_name(content_name());
537 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
538 }
539}
540
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000541void BasicPortAllocatorSession::GetPortConfigurations() {
542 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
543 username(),
544 password());
545
deadbeef653b8e02015-11-11 12:55:10 -0800546 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
547 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000548 }
549 ConfigReady(config);
550}
551
552void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700553 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554}
555
556// Adds a configuration to the list.
557void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800558 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800560 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000561
562 AllocatePorts();
563}
564
565void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800566 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567
568 // If any of the allocated ports have not completed the candidates allocation,
569 // mark those as error. Since session doesn't need any new candidates
570 // at this stage of the allocation, it's safe to discard any new candidates.
571 bool send_signal = false;
572 for (std::vector<PortData>::iterator it = ports_.begin();
573 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700574 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000575 // Updating port state to error, which didn't finish allocating candidates
576 // yet.
577 it->set_error();
578 send_signal = true;
579 }
580 }
581
582 // Did we stop any running sequences?
583 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
584 it != sequences_.end() && !send_signal; ++it) {
585 if ((*it)->state() == AllocationSequence::kStopped) {
586 send_signal = true;
587 }
588 }
589
590 // If we stopped anything that was running, send a done signal now.
591 if (send_signal) {
592 MaybeSignalCandidatesAllocationDone();
593 }
594}
595
596void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800597 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700598 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000599}
600
601void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700602 if (network_manager_started_ && !IsStopped()) {
603 bool disable_equivalent_phases = true;
604 DoAllocate(disable_equivalent_phases);
605 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000606
607 allocation_started_ = true;
608}
609
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700610std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
611 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700612 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800613 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700614 // If the network permission state is BLOCKED, we just act as if the flag has
615 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700616 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700617 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700618 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
619 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000620 // If the adapter enumeration is disabled, we'll just bind to any address
621 // instead of specific NIC. This is to ensure the same routing for http
622 // traffic by OS is also used here to avoid any local or public IP leakage
623 // during stun process.
624 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700625 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000626 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700627 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800628 // If network enumeration fails, use the ANY address as a fallback, so we
629 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700630 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
631 // set, we'll use ANY address candidates either way.
632 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800633 network_manager->GetAnyAddressNetworks(&networks);
634 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000635 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100636 // Filter out link-local networks if needed.
637 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
638 networks.erase(std::remove_if(networks.begin(), networks.end(),
639 [](rtc::Network* network) {
640 return IPIsLinkLocal(network->prefix());
641 }),
642 networks.end());
643 }
deadbeef3427f532017-07-26 16:09:33 -0700644 // Do some more filtering, depending on the network ignore mask and "disable
645 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700646 networks.erase(std::remove_if(networks.begin(), networks.end(),
647 [this](rtc::Network* network) {
648 return allocator_->network_ignore_mask() &
649 network->type();
650 }),
651 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700652 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
653 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700654 for (rtc::Network* network : networks) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800655 // Don't determine the lowest cost from a link-local network.
656 // On iOS, a device connected to the computer will get a link-local
657 // network for communicating with the computer, however this network can't
658 // be used to connect to a peer outside the network.
659 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
660 continue;
661 }
honghaiz60347052016-05-31 18:29:12 -0700662 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
663 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700664 networks.erase(std::remove_if(networks.begin(), networks.end(),
665 [lowest_cost](rtc::Network* network) {
666 return network->GetCost() >
667 lowest_cost + rtc::kNetworkCostLow;
668 }),
669 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700670 }
deadbeef3427f532017-07-26 16:09:33 -0700671 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
672 // default, it's 5), remove networks to ensure that limit is satisfied.
673 //
674 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
675 // networks, we could try to choose a set that's "most likely to work". It's
676 // hard to define what that means though; it's not just "lowest cost".
677 // Alternatively, we could just focus on making our ICE pinging logic smarter
678 // such that this filtering isn't necessary in the first place.
679 int ipv6_networks = 0;
680 for (auto it = networks.begin(); it != networks.end();) {
681 if ((*it)->prefix().family() == AF_INET6) {
682 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
683 it = networks.erase(it);
684 continue;
685 } else {
686 ++ipv6_networks;
687 }
688 }
689 ++it;
690 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700691 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700692}
693
694// For each network, see if we have a sequence that covers it already. If not,
695// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700696void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700697 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700698 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100700 RTC_LOG(LS_WARNING)
701 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702 done_signal_needed = true;
703 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100704 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700705 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200706 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200707 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
709 // If all the ports are disabled we should just fire the allocation
710 // done event and return.
711 done_signal_needed = true;
712 break;
713 }
714
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000715 if (!config || config->relays.empty()) {
716 // No relay ports specified in this config.
717 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
718 }
719
720 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722 // Skip IPv6 networks unless the flag's been set.
723 continue;
724 }
725
zhihuangb09b3f92017-03-07 14:40:51 -0800726 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
727 networks[i]->GetBestIP().family() == AF_INET6 &&
728 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
729 // Skip IPv6 Wi-Fi networks unless the flag's been set.
730 continue;
731 }
732
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 if (disable_equivalent) {
734 // Disable phases that would only create ports equivalent to
735 // ones that we have already made.
736 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737
Steve Anton300bf8e2017-07-14 10:13:10 -0700738 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
739 // New AllocationSequence would have nothing to do, so don't make it.
740 continue;
741 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742 }
743
744 AllocationSequence* sequence =
745 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000746 sequence->SignalPortAllocationComplete.connect(
747 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700748 sequence->Init();
749 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000750 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700751 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 }
753 }
754 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700755 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000756 }
757}
758
759void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700760 std::vector<rtc::Network*> networks = GetNetworks();
761 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700762 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700763 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700764 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700765 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700766 std::find(networks.begin(), networks.end(), sequence->network()) ==
767 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700768 sequence->OnNetworkFailed();
769 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700770 }
771 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700772 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
773 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100774 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
775 << " ports because their networks were gone";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700776 PrunePortsAndRemoveCandidates(ports_to_prune);
777 }
honghaiz8c404fa2015-09-28 07:59:43 -0700778
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700779 if (allocation_started_ && !IsStopped()) {
780 if (network_manager_started_) {
781 // If the network manager has started, it must be regathering.
782 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
783 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700784 bool disable_equivalent_phases = true;
785 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700786 }
787
Honghai Zhang5048f572016-08-23 15:47:33 -0700788 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700790 network_manager_started_ = true;
791 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792}
793
794void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200795 rtc::Network* network,
796 PortConfiguration* config,
797 uint32_t* flags) {
798 for (uint32_t i = 0; i < sequences_.size() &&
799 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
800 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 sequences_[i]->DisableEquivalentPhases(network, config, flags);
802 }
803}
804
805void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
806 AllocationSequence * seq,
807 bool prepare_address) {
808 if (!port)
809 return;
810
Mirko Bonadei675513b2017-11-09 11:09:25 +0100811 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700813 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000814 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700815 if (allocator_->proxy().type != rtc::PROXY_NONE)
816 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700817 port->set_send_retransmit_count_attribute(
818 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000820 PortData data(port, seq);
821 ports_.push_back(data);
822
823 port->SignalCandidateReady.connect(
824 this, &BasicPortAllocatorSession::OnCandidateReady);
825 port->SignalPortComplete.connect(this,
826 &BasicPortAllocatorSession::OnPortComplete);
827 port->SignalDestroyed.connect(this,
828 &BasicPortAllocatorSession::OnPortDestroyed);
829 port->SignalPortError.connect(
830 this, &BasicPortAllocatorSession::OnPortError);
831 LOG_J(LS_INFO, port) << "Added port to allocator";
832
833 if (prepare_address)
834 port->PrepareAddress();
835}
836
837void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
838 allocation_sequences_created_ = true;
839 // Send candidate allocation complete signal if we have no sequences.
840 MaybeSignalCandidatesAllocationDone();
841}
842
843void BasicPortAllocatorSession::OnCandidateReady(
844 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800845 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800847 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700848 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700850 // already done with gathering.
851 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100852 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700853 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700854 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700855 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700856
danilchapf4e8cf02016-06-30 01:55:03 -0700857 // Mark that the port has a pairable candidate, either because we have a
858 // usable candidate from the port, or simply because the port is bound to the
859 // any address and therefore has no host candidate. This will trigger the port
860 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700861 // checks. If port has already been marked as having a pairable candidate,
862 // do nothing here.
863 // Note: We should check whether any candidates may become ready after this
864 // because there we will check whether the candidate is generated by the ready
865 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700866 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700867 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700868 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700869
870 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700871 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700872 }
873 // If the current port is not pruned yet, SignalPortReady.
874 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700875 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700876 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700877 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700878 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700879 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700880
deadbeef1c5e6d02017-09-15 17:46:56 -0700881 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700882 std::vector<Candidate> candidates;
883 candidates.push_back(SanitizeRelatedAddress(c));
884 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700885 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100886 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700887 }
888
889 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700890 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700891 MaybeSignalCandidatesAllocationDone();
892 }
893}
894
895Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
896 const std::string& network_name) const {
897 Port* best_turn_port = nullptr;
898 for (const PortData& data : ports_) {
899 if (data.port()->Network()->name() == network_name &&
900 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
901 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
902 best_turn_port = data.port();
903 }
904 }
905 return best_turn_port;
906}
907
908bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700909 // Note: We determine the same network based only on their network names. So
910 // if an IPv4 address and an IPv6 address have the same network name, they
911 // are considered the same network here.
912 const std::string& network_name = newly_pairable_turn_port->Network()->name();
913 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
914 // |port| is already in the list of ports, so the best port cannot be nullptr.
915 RTC_CHECK(best_turn_port != nullptr);
916
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700917 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700918 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700919 for (PortData& data : ports_) {
920 if (data.port()->Network()->name() == network_name &&
921 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
922 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700923 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700924 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700925 // These ports will be pruned in PrunePortsAndRemoveCandidates.
926 ports_to_prune.push_back(&data);
927 } else {
928 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700929 }
930 }
931 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700932
933 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100934 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
935 << " low-priority TURN ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700936 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700937 }
938 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939}
940
Honghai Zhanga74363c2016-07-28 18:06:15 -0700941void BasicPortAllocatorSession::PruneAllPorts() {
942 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700943 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700944 }
945}
946
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800948 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700949 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000950 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800951 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952
953 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700954 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000955 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700956 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957
958 // Moving to COMPLETE state.
959 data->set_complete();
960 // Send candidate allocation complete signal if this was the last port.
961 MaybeSignalCandidatesAllocationDone();
962}
963
964void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800965 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700966 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800968 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000969 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700970 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700972 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973
974 // SignalAddressError is currently sent from StunPort/TurnPort.
975 // But this signal itself is generic.
976 data->set_error();
977 // Send candidate allocation complete signal if this was the last port.
978 MaybeSignalCandidatesAllocationDone();
979}
980
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700981bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700982 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000983
984 // When binding to any address, before sending packets out, the getsockname
985 // returns all 0s, but after sending packets, it'll be the NIC used to
986 // send. All 0s is not a valid ICE candidate address and should be filtered
987 // out.
988 if (c.address().IsAnyIP()) {
989 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000990 }
991
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000992 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000993 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000994 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000995 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000996 } else if (c.type() == LOCAL_PORT_TYPE) {
997 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
998 // We allow host candidates if the filter allows server-reflexive
999 // candidates and the candidate is a public IP. Because we don't generate
1000 // server-reflexive candidates if they have the same IP as the host
1001 // candidate (i.e. when the host candidate is a public IP), filtering to
1002 // only server-reflexive candidates won't work right when the host
1003 // candidates have public IPs.
1004 return true;
1005 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001007 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001008 }
1009 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010}
1011
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001012bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1013 const Port* port) const {
1014 bool candidate_signalable = CheckCandidateFilter(c);
1015
1016 // When device enumeration is disabled (to prevent non-default IP addresses
1017 // from leaking), we ping from some local candidates even though we don't
1018 // signal them. However, if host candidates are also disabled (for example, to
1019 // prevent even default IP addresses from leaking), we still don't want to
1020 // ping from them, even if device enumeration is disabled. Thus, we check for
1021 // both device enumeration and host candidates being disabled.
1022 bool network_enumeration_disabled = c.address().IsAnyIP();
1023 bool can_ping_from_candidate =
1024 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1025 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1026
1027 return candidate_signalable ||
1028 (network_enumeration_disabled && can_ping_from_candidate &&
1029 !host_candidates_disabled);
1030}
1031
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001032void BasicPortAllocatorSession::OnPortAllocationComplete(
1033 AllocationSequence* seq) {
1034 // Send candidate allocation complete signal if all ports are done.
1035 MaybeSignalCandidatesAllocationDone();
1036}
1037
1038void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001039 if (CandidatesAllocationDone()) {
1040 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001041 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001042 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001043 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1044 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001045 }
1046 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048}
1049
1050void BasicPortAllocatorSession::OnPortDestroyed(
1051 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001052 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001053 for (std::vector<PortData>::iterator iter = ports_.begin();
1054 iter != ports_.end(); ++iter) {
1055 if (port == iter->port()) {
1056 ports_.erase(iter);
1057 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1058 << static_cast<int>(ports_.size()) << " remaining)";
1059 return;
1060 }
1061 }
nissec80e7412017-01-11 05:56:46 -08001062 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001063}
1064
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001065BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1066 Port* port) {
1067 for (std::vector<PortData>::iterator it = ports_.begin();
1068 it != ports_.end(); ++it) {
1069 if (it->port() == port) {
1070 return &*it;
1071 }
1072 }
1073 return NULL;
1074}
1075
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001076std::vector<BasicPortAllocatorSession::PortData*>
1077BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001078 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001079 std::vector<PortData*> unpruned_ports;
1080 for (PortData& port : ports_) {
1081 if (!port.pruned() &&
1082 std::find(networks.begin(), networks.end(),
1083 port.sequence()->network()) != networks.end()) {
1084 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001085 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001086 }
1087 return unpruned_ports;
1088}
1089
1090void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1091 const std::vector<PortData*>& port_data_list) {
1092 std::vector<PortInterface*> pruned_ports;
1093 std::vector<Candidate> removed_candidates;
1094 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001095 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001096 data->Prune();
1097 pruned_ports.push_back(data->port());
1098 if (data->has_pairable_candidate()) {
1099 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001100 // Mark the port as having no pairable candidates so that its candidates
1101 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001102 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001103 }
1104 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001105 if (!pruned_ports.empty()) {
1106 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001107 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001108 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001109 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1110 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001111 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001112 }
1113}
1114
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001115// AllocationSequence
1116
1117AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1118 rtc::Network* network,
1119 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001120 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121 : session_(session),
1122 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001123 config_(config),
1124 state_(kInit),
1125 flags_(flags),
1126 udp_socket_(),
1127 udp_port_(NULL),
1128 phase_(0) {
1129}
1130
Honghai Zhang5048f572016-08-23 15:47:33 -07001131void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1133 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001134 rtc::SocketAddress(network_->GetBestIP(), 0),
1135 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001136 if (udp_socket_) {
1137 udp_socket_->SignalReadPacket.connect(
1138 this, &AllocationSequence::OnReadPacket);
1139 }
1140 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1141 // are next available options to setup a communication channel.
1142 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001143}
1144
1145void AllocationSequence::Clear() {
1146 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001147 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001148}
1149
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001150void AllocationSequence::OnNetworkFailed() {
1151 RTC_DCHECK(!network_failed_);
1152 network_failed_ = true;
1153 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001154 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001155}
1156
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001157AllocationSequence::~AllocationSequence() {
1158 session_->network_thread()->Clear(this);
1159}
1160
1161void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001162 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001163 if (network_failed_) {
1164 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001165 // it won't be equivalent to the new network.
1166 return;
1167 }
1168
deadbeef5c3c1042017-08-04 15:01:57 -07001169 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 // Different network setup; nothing is equivalent.
1171 return;
1172 }
1173
1174 // Else turn off the stuff that we've already got covered.
1175
deadbeef1c46a352017-09-27 11:24:05 -07001176 // Every config implicitly specifies local, so turn that off right away if we
1177 // already have a port of the corresponding type. Look for a port that
1178 // matches this AllocationSequence's network, is the right protocol, and
1179 // hasn't encountered an error.
1180 // TODO(deadbeef): This doesn't take into account that there may be another
1181 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1182 // This can happen if, say, there's a network change event right before an
1183 // application-triggered ICE restart. Hopefully this problem will just go
1184 // away if we get rid of the gathering "phases" though, which is planned.
1185 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1186 [this](const BasicPortAllocatorSession::PortData& p) {
1187 return p.port()->Network() == network_ &&
1188 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1189 })) {
1190 *flags |= PORTALLOCATOR_DISABLE_UDP;
1191 }
1192 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1193 [this](const BasicPortAllocatorSession::PortData& p) {
1194 return p.port()->Network() == network_ &&
1195 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1196 })) {
1197 *flags |= PORTALLOCATOR_DISABLE_TCP;
1198 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001199
1200 if (config_ && config) {
1201 if (config_->StunServers() == config->StunServers()) {
1202 // Already got this STUN servers covered.
1203 *flags |= PORTALLOCATOR_DISABLE_STUN;
1204 }
1205 if (!config_->relays.empty()) {
1206 // Already got relays covered.
1207 // NOTE: This will even skip a _different_ set of relay servers if we
1208 // were to be given one, but that never happens in our codebase. Should
1209 // probably get rid of the list in PortConfiguration and just keep a
1210 // single relay server in each one.
1211 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1212 }
1213 }
1214}
1215
1216void AllocationSequence::Start() {
1217 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001218 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001219 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1220 // called next time, we enable all phases if the best IP has since changed.
1221 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222}
1223
1224void AllocationSequence::Stop() {
1225 // If the port is completed, don't set it to stopped.
1226 if (state_ == kRunning) {
1227 state_ = kStopped;
1228 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1229 }
1230}
1231
1232void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001233 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1234 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001235
deadbeef1c5e6d02017-09-15 17:46:56 -07001236 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237
1238 // Perform all of the phases in the current step.
1239 LOG_J(LS_INFO, network_) << "Allocation Phase="
1240 << PHASE_NAMES[phase_];
1241
1242 switch (phase_) {
1243 case PHASE_UDP:
1244 CreateUDPPorts();
1245 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001246 break;
1247
1248 case PHASE_RELAY:
1249 CreateRelayPorts();
1250 break;
1251
1252 case PHASE_TCP:
1253 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001254 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001255 break;
1256
1257 default:
nissec80e7412017-01-11 05:56:46 -08001258 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 }
1260
1261 if (state() == kRunning) {
1262 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001263 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1264 session_->allocator()->step_delay(),
1265 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266 } else {
1267 // If all phases in AllocationSequence are completed, no allocation
1268 // steps needed further. Canceling pending signal.
1269 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1270 SignalPortAllocationComplete(this);
1271 }
1272}
1273
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001274void AllocationSequence::CreateUDPPorts() {
1275 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001276 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277 return;
1278 }
1279
1280 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1281 // is enabled completely.
1282 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001283 bool emit_local_candidate_for_anyaddress =
1284 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001285 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001286 port = UDPPort::Create(
1287 session_->network_thread(), session_->socket_factory(), network_,
1288 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001289 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001290 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001291 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001292 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001293 session_->allocator()->min_port(), session_->allocator()->max_port(),
1294 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001295 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001296 }
1297
1298 if (port) {
1299 // If shared socket is enabled, STUN candidate will be allocated by the
1300 // UDPPort.
1301 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1302 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001303 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001304
1305 // If STUN is not disabled, setting stun server address to port.
1306 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001308 RTC_LOG(LS_INFO)
1309 << "AllocationSequence: UDPPort will be handling the "
1310 << "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001311 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001312 }
1313 }
1314 }
1315
1316 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317 }
1318}
1319
1320void AllocationSequence::CreateTCPPorts() {
1321 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001322 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001323 return;
1324 }
1325
deadbeef5c3c1042017-08-04 15:01:57 -07001326 Port* port = TCPPort::Create(
1327 session_->network_thread(), session_->socket_factory(), network_,
1328 session_->allocator()->min_port(), session_->allocator()->max_port(),
1329 session_->username(), session_->password(),
1330 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001331 if (port) {
1332 session_->AddAllocatedPort(port, this, true);
1333 // Since TCPPort is not created using shared socket, |port| will not be
1334 // added to the dequeue.
1335 }
1336}
1337
1338void AllocationSequence::CreateStunPorts() {
1339 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001340 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001341 return;
1342 }
1343
1344 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1345 return;
1346 }
1347
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001348 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001349 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350 << "AllocationSequence: No STUN server configured, skipping.";
1351 return;
1352 }
1353
deadbeef5c3c1042017-08-04 15:01:57 -07001354 StunPort* port = StunPort::Create(
1355 session_->network_thread(), session_->socket_factory(), network_,
1356 session_->allocator()->min_port(), session_->allocator()->max_port(),
1357 session_->username(), session_->password(), config_->StunServers(),
1358 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001359 if (port) {
1360 session_->AddAllocatedPort(port, this, true);
1361 // Since StunPort is not created using shared socket, |port| will not be
1362 // added to the dequeue.
1363 }
1364}
1365
1366void AllocationSequence::CreateRelayPorts() {
1367 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001368 RTC_LOG(LS_VERBOSE)
1369 << "AllocationSequence: Relay ports disabled, skipping.";
1370 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001371 }
1372
1373 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1374 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001375 RTC_DCHECK(config_);
1376 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001377 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001378 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379 << "AllocationSequence: No relay server configured, skipping.";
1380 return;
1381 }
1382
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001383 for (RelayServerConfig& relay : config_->relays) {
1384 if (relay.type == RELAY_GTURN) {
1385 CreateGturnPort(relay);
1386 } else if (relay.type == RELAY_TURN) {
1387 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 } else {
nissec80e7412017-01-11 05:56:46 -08001389 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 }
1391 }
1392}
1393
1394void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1395 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001396 RelayPort* port = RelayPort::Create(
1397 session_->network_thread(), session_->socket_factory(), network_,
1398 session_->allocator()->min_port(), session_->allocator()->max_port(),
1399 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001400 if (port) {
1401 // Since RelayPort is not created using shared socket, |port| will not be
1402 // added to the dequeue.
1403 // Note: We must add the allocated port before we add addresses because
1404 // the latter will create candidates that need name and preference
1405 // settings. However, we also can't prepare the address (normally
1406 // done by AddAllocatedPort) until we have these addresses. So we
1407 // wait to do that until below.
1408 session_->AddAllocatedPort(port, this, false);
1409
1410 // Add the addresses of this protocol.
1411 PortList::const_iterator relay_port;
1412 for (relay_port = config.ports.begin();
1413 relay_port != config.ports.end();
1414 ++relay_port) {
1415 port->AddServerAddress(*relay_port);
1416 port->AddExternalAddress(*relay_port);
1417 }
1418 // Start fetching an address for this port.
1419 port->PrepareAddress();
1420 }
1421}
1422
1423void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1424 PortList::const_iterator relay_port;
1425 for (relay_port = config.ports.begin();
1426 relay_port != config.ports.end(); ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001427 // Skip UDP connections to relay servers if it's disallowed.
1428 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1429 relay_port->proto == PROTO_UDP) {
1430 continue;
1431 }
1432
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001433 // Do not create a port if the server address family is known and does
1434 // not match the local IP address family.
1435 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001436 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001437 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001438 RTC_LOG(LS_INFO)
1439 << "Server and local address families are not compatible. "
1440 << "Server address: " << relay_port->address.ipaddr().ToString()
1441 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001442 continue;
1443 }
1444
Jonas Oreland202994c2017-12-18 12:10:43 +01001445 CreateRelayPortArgs args;
1446 args.network_thread = session_->network_thread();
1447 args.socket_factory = session_->socket_factory();
1448 args.network = network_;
1449 args.username = session_->username();
1450 args.password = session_->password();
1451 args.server_address = &(*relay_port);
1452 args.config = &config;
1453 args.origin = session_->allocator()->origin();
1454 args.turn_customizer = session_->allocator()->turn_customizer();
1455
1456 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457 // Shared socket mode must be enabled only for UDP based ports. Hence
1458 // don't pass shared socket for ports which will create TCP sockets.
1459 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1460 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1461 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001462 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001463 port = session_->allocator()->relay_port_factory()->Create(
1464 args, udp_socket_.get());
1465
1466 if (!port) {
1467 RTC_LOG(LS_WARNING)
1468 << "Failed to create relay port with "
1469 << args.server_address->address.ToString();
1470 continue;
1471 }
1472
1473 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001474 // Listen to the port destroyed signal, to allow AllocationSequence to
1475 // remove entrt from it's map.
1476 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1477 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001478 port = session_->allocator()->relay_port_factory()->Create(
1479 args,
1480 session_->allocator()->min_port(),
1481 session_->allocator()->max_port());
1482
1483 if (!port) {
1484 RTC_LOG(LS_WARNING)
1485 << "Failed to create relay port with "
1486 << args.server_address->address.ToString();
1487 continue;
1488 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001489 }
nisseede5da42017-01-12 05:15:36 -08001490 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001491 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492 }
1493}
1494
1495void AllocationSequence::OnReadPacket(
1496 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1497 const rtc::SocketAddress& remote_addr,
1498 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001499 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001500
1501 bool turn_port_found = false;
1502
1503 // Try to find the TurnPort that matches the remote address. Note that the
1504 // message could be a STUN binding response if the TURN server is also used as
1505 // a STUN server. We don't want to parse every message here to check if it is
1506 // a STUN binding response, so we pass the message to TurnPort regardless of
1507 // the message type. The TurnPort will just ignore the message since it will
1508 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001509 for (auto* port : relay_ports_) {
1510 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001511 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1512 packet_time)) {
1513 return;
1514 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001515 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001516 }
1517 }
1518
1519 if (udp_port_) {
1520 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1521
1522 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1523 // the TURN server is also a STUN server.
1524 if (!turn_port_found ||
1525 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001526 RTC_DCHECK(udp_port_->SharedSocket());
1527 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1528 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001529 }
1530 }
1531}
1532
1533void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1534 if (udp_port_ == port) {
1535 udp_port_ = NULL;
1536 return;
1537 }
1538
Jonas Oreland202994c2017-12-18 12:10:43 +01001539 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1540 if (it != relay_ports_.end()) {
1541 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001542 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001543 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001544 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001545 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001546}
1547
1548// PortConfiguration
1549PortConfiguration::PortConfiguration(
1550 const rtc::SocketAddress& stun_address,
1551 const std::string& username,
1552 const std::string& password)
1553 : stun_address(stun_address), username(username), password(password) {
1554 if (!stun_address.IsNil())
1555 stun_servers.insert(stun_address);
1556}
1557
1558PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1559 const std::string& username,
1560 const std::string& password)
1561 : stun_servers(stun_servers),
1562 username(username),
1563 password(password) {
1564 if (!stun_servers.empty())
1565 stun_address = *(stun_servers.begin());
1566}
1567
Steve Anton7995d8c2017-10-30 16:23:38 -07001568PortConfiguration::~PortConfiguration() = default;
1569
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001570ServerAddresses PortConfiguration::StunServers() {
1571 if (!stun_address.IsNil() &&
1572 stun_servers.find(stun_address) == stun_servers.end()) {
1573 stun_servers.insert(stun_address);
1574 }
deadbeefc5d0d952015-07-16 10:22:21 -07001575 // Every UDP TURN server should also be used as a STUN server.
1576 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1577 for (const rtc::SocketAddress& turn_server : turn_servers) {
1578 if (stun_servers.find(turn_server) == stun_servers.end()) {
1579 stun_servers.insert(turn_server);
1580 }
1581 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001582 return stun_servers;
1583}
1584
1585void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1586 relays.push_back(config);
1587}
1588
1589bool PortConfiguration::SupportsProtocol(
1590 const RelayServerConfig& relay, ProtocolType type) const {
1591 PortList::const_iterator relay_port;
1592 for (relay_port = relay.ports.begin();
1593 relay_port != relay.ports.end();
1594 ++relay_port) {
1595 if (relay_port->proto == type)
1596 return true;
1597 }
1598 return false;
1599}
1600
1601bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1602 ProtocolType type) const {
1603 for (size_t i = 0; i < relays.size(); ++i) {
1604 if (relays[i].type == turn_type &&
1605 SupportsProtocol(relays[i], type))
1606 return true;
1607 }
1608 return false;
1609}
1610
1611ServerAddresses PortConfiguration::GetRelayServerAddresses(
1612 RelayType turn_type, ProtocolType type) const {
1613 ServerAddresses servers;
1614 for (size_t i = 0; i < relays.size(); ++i) {
1615 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1616 servers.insert(relays[i].ports.front().address);
1617 }
1618 }
1619 return servers;
1620}
1621
1622} // namespace cricket