blob: 4335ddaad4bc2c87c4357fc436814e77d3675124 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "p2p/client/basicportallocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
Qingsi Wang10a0e512018-05-16 13:37:03 -070014#include <functional>
Steve Anton6c38cc72017-11-29 10:25:58 -080015#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <string>
17#include <vector>
18
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/umametrics.h"
20#include "p2p/base/basicpacketsocketfactory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "p2p/base/port.h"
22#include "p2p/base/relayport.h"
23#include "p2p/base/stunport.h"
24#include "p2p/base/tcpport.h"
25#include "p2p/base/turnport.h"
26#include "p2p/base/udpport.h"
27#include "rtc_base/checks.h"
28#include "rtc_base/helpers.h"
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +000029#include "rtc_base/ipaddress.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/logging.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000033
34namespace {
35
36enum {
37 MSG_CONFIG_START,
38 MSG_CONFIG_READY,
39 MSG_ALLOCATE,
40 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000041 MSG_SEQUENCEOBJECTS_CREATED,
42 MSG_CONFIG_STOP,
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +000043 MSG_SIGNAL_ANY_ADDRESS_PORTS,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044};
45
46const int PHASE_UDP = 0;
47const int PHASE_RELAY = 1;
48const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049
deadbeef1c5e6d02017-09-15 17:46:56 -070050const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000051
zhihuang696f8ca2017-06-27 15:11:24 -070052// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070053int GetProtocolPriority(cricket::ProtocolType protocol) {
54 switch (protocol) {
55 case cricket::PROTO_UDP:
56 return 2;
57 case cricket::PROTO_TCP:
58 return 1;
59 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070060 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070061 return 0;
62 default:
nisseeb4ca4e2017-01-12 02:24:27 -080063 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070064 return 0;
65 }
66}
67// Gets address family priority: IPv6 > IPv4 > Unspecified.
68int GetAddressFamilyPriority(int ip_family) {
69 switch (ip_family) {
70 case AF_INET6:
71 return 2;
72 case AF_INET:
73 return 1;
74 default:
nisseeb4ca4e2017-01-12 02:24:27 -080075 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070076 return 0;
77 }
78}
79
80// Returns positive if a is better, negative if b is better, and 0 otherwise.
81int ComparePort(const cricket::Port* a, const cricket::Port* b) {
82 int a_protocol = GetProtocolPriority(a->GetProtocol());
83 int b_protocol = GetProtocolPriority(b->GetProtocol());
84 int cmp_protocol = a_protocol - b_protocol;
85 if (cmp_protocol != 0) {
86 return cmp_protocol;
87 }
88
89 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
90 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
91 return a_family - b_family;
92}
93
Qingsi Wang10a0e512018-05-16 13:37:03 -070094struct NetworkFilter {
95 using Predicate = std::function<bool(rtc::Network*)>;
96 NetworkFilter(Predicate pred, const std::string& description)
97 : pred(pred), description(description) {}
98 Predicate pred;
99 const std::string description;
100};
101
102using NetworkList = rtc::NetworkManager::NetworkList;
103void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
104 auto start_to_remove =
105 std::remove_if(networks->begin(), networks->end(), filter.pred);
106 if (start_to_remove == networks->end()) {
107 return;
108 }
109 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
110 for (auto it = start_to_remove; it != networks->end(); ++it) {
111 RTC_LOG(INFO) << (*it)->ToString();
112 }
113 networks->erase(start_to_remove, networks->end());
114}
115
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000116bool IsAnyAddressPort(const cricket::Port* port) {
117 return rtc::IPIsAny(port->Network()->GetBestIP());
118}
119
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120} // namespace
121
122namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200123const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700124 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
125 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000126
127// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200128BasicPortAllocator::BasicPortAllocator(
129 rtc::NetworkManager* network_manager,
130 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100131 webrtc::TurnCustomizer* customizer,
132 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700133 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100134 InitRelayPortFactory(relay_port_factory);
135 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800136 RTC_DCHECK(network_manager_ != nullptr);
137 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200138 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
139 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 Construct();
141}
142
Yves Gerey665174f2018-06-19 15:03:05 +0200143BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700144 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100145 InitRelayPortFactory(nullptr);
146 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800147 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000148 Construct();
149}
150
Yves Gerey665174f2018-06-19 15:03:05 +0200151BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
152 rtc::PacketSocketFactory* socket_factory,
153 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700154 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100155 InitRelayPortFactory(nullptr);
156 RTC_DCHECK(relay_port_factory_ != nullptr);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000157 RTC_DCHECK(socket_factory_ != nullptr);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200158 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
159 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 Construct();
161}
162
163BasicPortAllocator::BasicPortAllocator(
164 rtc::NetworkManager* network_manager,
165 const ServerAddresses& stun_servers,
166 const rtc::SocketAddress& relay_address_udp,
167 const rtc::SocketAddress& relay_address_tcp,
168 const rtc::SocketAddress& relay_address_ssl)
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000169 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100170 InitRelayPortFactory(nullptr);
171 RTC_DCHECK(relay_port_factory_ != nullptr);
172 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700173 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000174 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800175 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800177 }
178 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800180 }
181 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800183 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184
deadbeef653b8e02015-11-11 12:55:10 -0800185 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700186 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800187 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188
Jonas Orelandbdcee282017-10-10 14:01:40 +0200189 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 Construct();
191}
192
193void BasicPortAllocator::Construct() {
194 allow_tcp_listen_ = true;
195}
196
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700197void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
198 IceRegatheringReason reason) {
199 if (!metrics_observer()) {
200 return;
201 }
202 // If the session has not been taken by an active channel, do not report the
203 // metric.
204 for (auto& allocator_session : pooled_sessions()) {
205 if (allocator_session.get() == session) {
206 return;
207 }
208 }
209
210 metrics_observer()->IncrementEnumCounter(
211 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
212 static_cast<int>(IceRegatheringReason::MAX_VALUE));
213}
214
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700216 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800217 // Our created port allocator sessions depend on us, so destroy our remaining
218 // pooled sessions before anything else.
219 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220}
221
Steve Anton7995d8c2017-10-30 16:23:38 -0700222void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
223 // TODO(phoglund): implement support for other types than loopback.
224 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
225 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700226 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700227 network_ignore_mask_ = network_ignore_mask;
228}
229
deadbeefc5d0d952015-07-16 10:22:21 -0700230PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200231 const std::string& content_name,
232 int component,
233 const std::string& ice_ufrag,
234 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700235 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700236 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700238 session->SignalIceRegathering.connect(this,
239 &BasicPortAllocator::OnIceRegathering);
240 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241}
242
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700243void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700244 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700245 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
246 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700247 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200248 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700249}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250
Jonas Oreland202994c2017-12-18 12:10:43 +0100251void BasicPortAllocator::InitRelayPortFactory(
252 RelayPortFactoryInterface* relay_port_factory) {
253 if (relay_port_factory != nullptr) {
254 relay_port_factory_ = relay_port_factory;
255 } else {
256 default_relay_port_factory_.reset(new TurnPortFactory());
257 relay_port_factory_ = default_relay_port_factory_.get();
258 }
259}
260
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261// BasicPortAllocatorSession
262BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700263 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 const std::string& content_name,
265 int component,
266 const std::string& ice_ufrag,
267 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700268 : PortAllocatorSession(content_name,
269 component,
270 ice_ufrag,
271 ice_pwd,
272 allocator->flags()),
273 allocator_(allocator),
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000274 network_thread_(nullptr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000275 socket_factory_(allocator->socket_factory()),
276 allocation_started_(false),
277 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700278 allocation_sequences_created_(false),
279 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000280 allocator_->network_manager()->SignalNetworksChanged.connect(
281 this, &BasicPortAllocatorSession::OnNetworksChanged);
282 allocator_->network_manager()->StartUpdating();
283}
284
285BasicPortAllocatorSession::~BasicPortAllocatorSession() {
286 allocator_->network_manager()->StopUpdating();
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000287 if (network_thread_ != nullptr)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 network_thread_->Clear(this);
289
Peter Boström0c4e06b2015-10-07 12:23:21 +0200290 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 // AllocationSequence should clear it's map entry for turn ports before
292 // ports are destroyed.
293 sequences_[i]->Clear();
294 }
295
296 std::vector<PortData>::iterator it;
297 for (it = ports_.begin(); it != ports_.end(); it++)
298 delete it->port();
299
Peter Boström0c4e06b2015-10-07 12:23:21 +0200300 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000301 delete configs_[i];
302
Peter Boström0c4e06b2015-10-07 12:23:21 +0200303 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 delete sequences_[i];
305}
306
Steve Anton7995d8c2017-10-30 16:23:38 -0700307BasicPortAllocator* BasicPortAllocatorSession::allocator() {
308 return allocator_;
309}
310
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700311void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
312 if (filter == candidate_filter_) {
313 return;
314 }
315 // We assume the filter will only change from "ALL" to something else.
316 RTC_DCHECK(candidate_filter_ == CF_ALL);
317 candidate_filter_ = filter;
318 for (PortData& port : ports_) {
319 if (!port.has_pairable_candidate()) {
320 continue;
321 }
322 const auto& candidates = port.port()->Candidates();
323 // Setting a filter may cause a ready port to become non-ready
324 // if it no longer has any pairable candidates.
325 if (!std::any_of(candidates.begin(), candidates.end(),
326 [this, &port](const Candidate& candidate) {
327 return CandidatePairable(candidate, port.port());
328 })) {
329 port.set_has_pairable_candidate(false);
330 }
331 }
332}
333
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000334void BasicPortAllocatorSession::StartGettingPorts() {
335 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700336 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000337 if (!socket_factory_) {
338 owned_socket_factory_.reset(
339 new rtc::BasicPacketSocketFactory(network_thread_));
340 socket_factory_ = owned_socket_factory_.get();
341 }
342
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700343 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700344
Mirko Bonadei675513b2017-11-09 11:09:25 +0100345 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
346 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000347}
348
349void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800350 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700351 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700352 // Note: this must be called after ClearGettingPorts because both may set the
353 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700354 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700355}
356
357void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800358 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000359 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700360 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700362 }
deadbeefb60a8192016-08-24 15:15:00 -0700363 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700364 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700365}
366
Steve Anton7995d8c2017-10-30 16:23:38 -0700367bool BasicPortAllocatorSession::IsGettingPorts() {
368 return state_ == SessionState::GATHERING;
369}
370
371bool BasicPortAllocatorSession::IsCleared() const {
372 return state_ == SessionState::CLEARED;
373}
374
375bool BasicPortAllocatorSession::IsStopped() const {
376 return state_ == SessionState::STOPPED;
377}
378
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700379std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
380 std::vector<rtc::Network*> networks = GetNetworks();
381
382 // A network interface may have both IPv4 and IPv6 networks. Only if
383 // neither of the networks has any connections, the network interface
384 // is considered failed and need to be regathered on.
385 std::set<std::string> networks_with_connection;
386 for (const PortData& data : ports_) {
387 Port* port = data.port();
388 if (!port->connections().empty()) {
389 networks_with_connection.insert(port->Network()->name());
390 }
391 }
392
393 networks.erase(
394 std::remove_if(networks.begin(), networks.end(),
395 [networks_with_connection](rtc::Network* network) {
396 // If a network does not have any connection, it is
397 // considered failed.
398 return networks_with_connection.find(network->name()) !=
399 networks_with_connection.end();
400 }),
401 networks.end());
402 return networks;
403}
404
405void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
406 // Find the list of networks that have no connection.
407 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
408 if (failed_networks.empty()) {
409 return;
410 }
411
Mirko Bonadei675513b2017-11-09 11:09:25 +0100412 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700413
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700414 // Mark a sequence as "network failed" if its network is in the list of failed
415 // networks, so that it won't be considered as equivalent when the session
416 // regathers ports and candidates.
417 for (AllocationSequence* sequence : sequences_) {
418 if (!sequence->network_failed() &&
419 std::find(failed_networks.begin(), failed_networks.end(),
420 sequence->network()) != failed_networks.end()) {
421 sequence->set_network_failed();
422 }
423 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700424
425 bool disable_equivalent_phases = true;
426 Regather(failed_networks, disable_equivalent_phases,
427 IceRegatheringReason::NETWORK_FAILURE);
428}
429
430void BasicPortAllocatorSession::RegatherOnAllNetworks() {
431 std::vector<rtc::Network*> networks = GetNetworks();
432 if (networks.empty()) {
433 return;
434 }
435
Mirko Bonadei675513b2017-11-09 11:09:25 +0100436 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700437
438 // We expect to generate candidates that are equivalent to what we have now.
439 // Force DoAllocate to generate them instead of skipping.
440 bool disable_equivalent_phases = false;
441 Regather(networks, disable_equivalent_phases,
442 IceRegatheringReason::OCCASIONAL_REFRESH);
443}
444
445void BasicPortAllocatorSession::Regather(
446 const std::vector<rtc::Network*>& networks,
447 bool disable_equivalent_phases,
448 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700449 // Remove ports from being used locally and send signaling to remove
450 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700451 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700452 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100453 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000454 PrunePortsAndSignalCandidatesRemoval(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700455 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700456
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700457 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700458 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700459
Steve Anton300bf8e2017-07-14 10:13:10 -0700460 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700461 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462}
463
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800464void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200465 const absl::optional<int>& stun_keepalive_interval) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800466 auto ports = ReadyPorts();
467 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800468 // The port type and protocol can be used to identify different subclasses
469 // of Port in the current implementation. Note that a TCPPort has the type
470 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
471 if (port->Type() == STUN_PORT_TYPE ||
472 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800473 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
474 stun_keepalive_interval);
475 }
476 }
477}
478
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700479std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
480 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700481 for (const PortData& data : ports_) {
482 if (data.ready()) {
483 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700484 }
485 }
486 return ret;
487}
488
489std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
490 std::vector<Candidate> candidates;
491 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700492 if (!data.ready()) {
493 continue;
494 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700495 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700496 }
497 return candidates;
498}
499
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700500void BasicPortAllocatorSession::GetCandidatesFromPort(
501 const PortData& data,
502 std::vector<Candidate>* candidates) const {
503 RTC_CHECK(candidates != nullptr);
504 for (const Candidate& candidate : data.port()->Candidates()) {
505 if (!CheckCandidateFilter(candidate)) {
506 continue;
507 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700508 candidates->push_back(SanitizeRelatedAddress(candidate));
509 }
510}
511
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700512Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
513 const Candidate& c) const {
514 Candidate copy = c;
515 // If adapter enumeration is disabled or host candidates are disabled,
516 // clear the raddr of STUN candidates to avoid local address leakage.
517 bool filter_stun_related_address =
518 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
519 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
520 !(candidate_filter_ & CF_HOST);
521 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
522 // to avoid reflexive address leakage.
523 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
524 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
525 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
526 copy.set_related_address(
527 rtc::EmptySocketAddressWithFamily(copy.address().family()));
528 }
529 return copy;
530}
531
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700532bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
533 // Done only if all required AllocationSequence objects
534 // are created.
535 if (!allocation_sequences_created_) {
536 return false;
537 }
538
539 // Check that all port allocation sequences are complete (not running).
540 if (std::any_of(sequences_.begin(), sequences_.end(),
541 [](const AllocationSequence* sequence) {
542 return sequence->state() == AllocationSequence::kRunning;
543 })) {
544 return false;
545 }
546
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700547 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700548 // expected candidates. Session will trigger candidates allocation complete
549 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700550 return std::none_of(ports_.begin(), ports_.end(),
551 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700552}
553
Yves Gerey665174f2018-06-19 15:03:05 +0200554void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000555 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200556 case MSG_CONFIG_START:
557 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
558 GetPortConfigurations();
559 break;
560 case MSG_CONFIG_READY:
561 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
562 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
563 break;
564 case MSG_ALLOCATE:
565 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
566 OnAllocate();
567 break;
568 case MSG_SEQUENCEOBJECTS_CREATED:
569 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
570 OnAllocationSequenceObjectsCreated();
571 break;
572 case MSG_CONFIG_STOP:
573 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
574 OnConfigStop();
575 break;
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000576 case MSG_SIGNAL_ANY_ADDRESS_PORTS:
577 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
578 SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant();
579 break;
Yves Gerey665174f2018-06-19 15:03:05 +0200580 default:
581 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582 }
583}
584
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700585void BasicPortAllocatorSession::UpdateIceParametersInternal() {
586 for (PortData& port : ports_) {
587 port.port()->set_content_name(content_name());
588 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
589 }
590}
591
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592void BasicPortAllocatorSession::GetPortConfigurations() {
Yves Gerey665174f2018-06-19 15:03:05 +0200593 PortConfiguration* config =
594 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595
deadbeef653b8e02015-11-11 12:55:10 -0800596 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
597 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 }
599 ConfigReady(config);
600}
601
602void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700603 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604}
605
606// Adds a configuration to the list.
607void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800608 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800610 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611
612 AllocatePorts();
613}
614
615void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800616 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000617
618 // If any of the allocated ports have not completed the candidates allocation,
619 // mark those as error. Since session doesn't need any new candidates
620 // at this stage of the allocation, it's safe to discard any new candidates.
621 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200622 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
623 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700624 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000625 // Updating port state to error, which didn't finish allocating candidates
626 // yet.
627 it->set_error();
628 send_signal = true;
629 }
630 }
631
632 // Did we stop any running sequences?
633 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
634 it != sequences_.end() && !send_signal; ++it) {
635 if ((*it)->state() == AllocationSequence::kStopped) {
636 send_signal = true;
637 }
638 }
639
640 // If we stopped anything that was running, send a done signal now.
641 if (send_signal) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000642 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000643 }
644}
645
646void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800647 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700648 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000649}
650
651void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700652 if (network_manager_started_ && !IsStopped()) {
653 bool disable_equivalent_phases = true;
654 DoAllocate(disable_equivalent_phases);
655 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000656
657 allocation_started_ = true;
658}
659
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700660std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
661 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700662 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800663 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700664 // If the network permission state is BLOCKED, we just act as if the flag has
665 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700666 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700667 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700668 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
669 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000670
671 // If adapter enumeration is disabled, we'll just bind to any address
672 // instead of a specific NIC. This is to ensure that WebRTC traffic is routed
673 // by the OS in the same way that HTTP traffic would be, and no additional
674 // local or public IPs are leaked during ICE processing.
675 //
676 // Even when adapter enumeration is enabled, we still bind to the "any"
677 // address as a fallback, since this may potentially reveal network
678 // interfaces that weren't otherwise accessible. Note that the candidates
679 // gathered by binding to the "any" address won't be surfaced to the
680 // application if they're determined to be redundant (if they have the same
681 // address as a candidate gathered by binding to an interface explicitly).
682 if (!(flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION)) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700683 network_manager->GetNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000684 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000685
686 network_manager->GetAnyAddressNetworks(&networks);
687
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100688 // Filter out link-local networks if needed.
689 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700690 NetworkFilter link_local_filter(
691 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
692 "link-local");
693 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100694 }
deadbeef3427f532017-07-26 16:09:33 -0700695 // Do some more filtering, depending on the network ignore mask and "disable
696 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700697 NetworkFilter ignored_filter(
698 [this](rtc::Network* network) {
699 return allocator_->network_ignore_mask() & network->type();
700 },
701 "ignored");
702 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700703 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
704 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700705 for (rtc::Network* network : networks) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000706 // Don't determine the lowest cost from a link-local or any address
707 // network. On iOS, a device connected to the computer will get a
708 // link-local network for communicating with the computer, however this
709 // network can't be used to connect to a peer outside the network.
710 if (rtc::IPIsLinkLocal(network->GetBestIP()) ||
711 rtc::IPIsAny(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800712 continue;
713 }
honghaiz60347052016-05-31 18:29:12 -0700714 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
715 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700716 NetworkFilter costly_filter(
717 [lowest_cost](rtc::Network* network) {
718 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
719 },
720 "costly");
721 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700722 }
deadbeef3427f532017-07-26 16:09:33 -0700723 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
724 // default, it's 5), remove networks to ensure that limit is satisfied.
725 //
726 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
727 // networks, we could try to choose a set that's "most likely to work". It's
728 // hard to define what that means though; it's not just "lowest cost".
729 // Alternatively, we could just focus on making our ICE pinging logic smarter
730 // such that this filtering isn't necessary in the first place.
731 int ipv6_networks = 0;
732 for (auto it = networks.begin(); it != networks.end();) {
733 if ((*it)->prefix().family() == AF_INET6) {
734 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
735 it = networks.erase(it);
736 continue;
737 } else {
738 ++ipv6_networks;
739 }
740 }
741 ++it;
742 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700743 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700744}
745
746// For each network, see if we have a sequence that covers it already. If not,
747// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700748void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700749 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700750 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000751 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100752 RTC_LOG(LS_WARNING)
753 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000754 done_signal_needed = true;
755 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700757 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200758 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200759 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000760 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
761 // If all the ports are disabled we should just fire the allocation
762 // done event and return.
763 done_signal_needed = true;
764 break;
765 }
766
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000767 if (!config || config->relays.empty()) {
768 // No relay ports specified in this config.
769 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
770 }
771
772 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000773 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774 // Skip IPv6 networks unless the flag's been set.
775 continue;
776 }
777
zhihuangb09b3f92017-03-07 14:40:51 -0800778 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
779 networks[i]->GetBestIP().family() == AF_INET6 &&
780 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
781 // Skip IPv6 Wi-Fi networks unless the flag's been set.
782 continue;
783 }
784
Steve Anton300bf8e2017-07-14 10:13:10 -0700785 if (disable_equivalent) {
786 // Disable phases that would only create ports equivalent to
787 // ones that we have already made.
788 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789
Steve Anton300bf8e2017-07-14 10:13:10 -0700790 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
791 // New AllocationSequence would have nothing to do, so don't make it.
792 continue;
793 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000794 }
795
796 AllocationSequence* sequence =
797 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000798 sequence->SignalPortAllocationComplete.connect(
799 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700800 sequence->Init();
801 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700803 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000804 }
805 }
806 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700807 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000808 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000809
810 // If adapter enumeration is enabled, then we prefer binding to individual
811 // network adapters, only using ports bound to the "any" address (0.0.0.0) if
812 // they reveal an interface not otherwise accessible. Normally these will be
813 // surfaced when candidate allocation completes, but sometimes candidate
814 // allocation can take a long time, if a STUN transaction times out for
815 // instance. So as a backup, we'll surface these ports/candidates after
816 // |kMaxWaitMsBeforeSignalingAnyAddressPortsAndCandidates| passes.
817 if (!(flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION)) {
818 network_thread_->PostDelayed(
819 RTC_FROM_HERE, kMaxWaitMsBeforeSignalingAnyAddressPortsAndCandidates,
820 this, MSG_SIGNAL_ANY_ADDRESS_PORTS);
821 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822}
823
824void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700825 std::vector<rtc::Network*> networks = GetNetworks();
826 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700827 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700828 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700829 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700830 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700831 std::find(networks.begin(), networks.end(), sequence->network()) ==
832 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700833 sequence->OnNetworkFailed();
834 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700835 }
836 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700837 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
838 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100839 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
840 << " ports because their networks were gone";
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000841 PrunePortsAndSignalCandidatesRemoval(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700842 }
honghaiz8c404fa2015-09-28 07:59:43 -0700843
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700844 if (allocation_started_ && !IsStopped()) {
845 if (network_manager_started_) {
846 // If the network manager has started, it must be regathering.
847 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
848 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700849 bool disable_equivalent_phases = true;
850 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700851 }
852
Honghai Zhang5048f572016-08-23 15:47:33 -0700853 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100854 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700855 network_manager_started_ = true;
856 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000857}
858
859void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200860 rtc::Network* network,
861 PortConfiguration* config,
862 uint32_t* flags) {
863 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200864 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200865 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 sequences_[i]->DisableEquivalentPhases(network, config, flags);
867 }
868}
869
870void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200871 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872 bool prepare_address) {
873 if (!port)
874 return;
875
Mirko Bonadei675513b2017-11-09 11:09:25 +0100876 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700878 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700880 if (allocator_->proxy().type != rtc::PROXY_NONE)
881 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700882 port->set_send_retransmit_count_attribute(
883 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 PortData data(port, seq);
886 ports_.push_back(data);
887
888 port->SignalCandidateReady.connect(
889 this, &BasicPortAllocatorSession::OnCandidateReady);
890 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200891 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200893 &BasicPortAllocatorSession::OnPortDestroyed);
894 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
895 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000896
897 if (prepare_address)
898 port->PrepareAddress();
899}
900
901void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
902 allocation_sequences_created_ = true;
903 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000904 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905}
906
Yves Gerey665174f2018-06-19 15:03:05 +0200907void BasicPortAllocatorSession::OnCandidateReady(Port* port,
908 const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800909 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910 PortData* data = FindPort(port);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000911 RTC_DCHECK(data != nullptr);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200912 RTC_LOG(LS_INFO) << port->ToString()
913 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700915 // already done with gathering.
916 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100917 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700918 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700919 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700920 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700921
danilchapf4e8cf02016-06-30 01:55:03 -0700922 // Mark that the port has a pairable candidate, either because we have a
923 // usable candidate from the port, or simply because the port is bound to the
924 // any address and therefore has no host candidate. This will trigger the port
925 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700926 // checks. If port has already been marked as having a pairable candidate,
927 // do nothing here.
928 // Note: We should check whether any candidates may become ready after this
929 // because there we will check whether the candidate is generated by the ready
930 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700931 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700932 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700933 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700934
935 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700936 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700937 }
938 // If the current port is not pruned yet, SignalPortReady.
939 if (!data->pruned()) {
Honghai Zhanga74363c2016-07-28 18:06:15 -0700940 port->KeepAliveUntilPruned();
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000941 // We postpone the signaling of any address ports to when the candidates
942 // allocation is done or the candidate allocation process has start for
943 // more than kMaxWaitMsBeforeSignalingAnyAddressPortsAndCandidates, and
944 // we check whether they are redundant or not (in
945 // SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant). Otherwise,
946 // connectivity checks will be sent from these possibly redundant ports,
947 // likely also resulting in "prflx" candidate pairs being created on the
948 // other side if not pruned in time. The signaling of any address ports
949 // that are not redundant happens in
950 // SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant.
951 //
952 // If adapter enumeration is disabled, these "any" address ports
953 // are all we'll get, so we can signal them immediately.
954 //
955 // Same logic applies to candidates below.
956
957 if (!IsAnyAddressPort(port) ||
958 (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION)) {
959 RTC_LOG(INFO) << port->ToString() << ": Port ready.";
960 SignalPortReady(this, port);
961 data->set_signaled();
962 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700963 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700964 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700965
deadbeef1c5e6d02017-09-15 17:46:56 -0700966 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000967 // See comment above about why we delay signaling candidates from "any
968 // address" ports.
969 //
970 // For candidates gathered after the any address port is signaled, we will
971 // not perform the redundancy check anymore. Note that late candiates
972 // gathered from the any address port should be a srflx candidate from a
973 // late STUN binding response.
974 if (data->signaled()) {
975 std::vector<Candidate> candidates;
976 candidates.push_back(SanitizeRelatedAddress(c));
977 SignalCandidatesReady(this, candidates);
978 } else {
979 RTC_LOG(INFO) << "Candidate not signaled yet because it is from the "
980 "any address port: "
981 << c.ToSensitiveString();
982 }
deadbeefa64edb82016-07-15 14:42:21 -0700983 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100984 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700985 }
986
987 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700988 if (pruned) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000989 FireAllocationStatusSignalsIfNeeded();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700990 }
991}
992
993Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
994 const std::string& network_name) const {
995 Port* best_turn_port = nullptr;
996 for (const PortData& data : ports_) {
997 if (data.port()->Network()->name() == network_name &&
998 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
999 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
1000 best_turn_port = data.port();
1001 }
1002 }
1003 return best_turn_port;
1004}
1005
1006bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001007 // Note: We determine the same network based only on their network names. So
1008 // if an IPv4 address and an IPv6 address have the same network name, they
1009 // are considered the same network here.
1010 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1011 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1012 // |port| is already in the list of ports, so the best port cannot be nullptr.
1013 RTC_CHECK(best_turn_port != nullptr);
1014
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001015 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001016 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001017 for (PortData& data : ports_) {
1018 if (data.port()->Network()->name() == network_name &&
1019 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1020 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001021 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001022 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001023 // These ports will be pruned in PrunePortsAndSignalCandidatesRemoval.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001024 ports_to_prune.push_back(&data);
1025 } else {
1026 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001027 }
1028 }
1029 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001030
1031 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001032 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1033 << " low-priority TURN ports";
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001034 PrunePortsAndSignalCandidatesRemoval(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001035 }
1036 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001037}
1038
Honghai Zhanga74363c2016-07-28 18:06:15 -07001039void BasicPortAllocatorSession::PruneAllPorts() {
1040 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001041 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001042 }
1043}
1044
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001046 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001047 RTC_LOG(LS_INFO) << port->ToString()
1048 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001049 PortData* data = FindPort(port);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001050 RTC_DCHECK(data != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001051
1052 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001053 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001054 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001055 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001056
1057 // Moving to COMPLETE state.
1058 data->set_complete();
1059 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001060 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001061}
1062
1063void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001064 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001065 RTC_LOG(LS_INFO) << port->ToString()
1066 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001067 PortData* data = FindPort(port);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001068 RTC_DCHECK(data != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001069 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001070 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001071 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001072 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001073
1074 // SignalAddressError is currently sent from StunPort/TurnPort.
1075 // But this signal itself is generic.
1076 data->set_error();
1077 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001078 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001079}
1080
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001081bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001082 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001083
1084 // When binding to any address, before sending packets out, the getsockname
1085 // returns all 0s, but after sending packets, it'll be the NIC used to
1086 // send. All 0s is not a valid ICE candidate address and should be filtered
1087 // out.
1088 if (c.address().IsAnyIP()) {
1089 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001090 }
1091
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001092 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001093 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001094 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001095 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001096 } else if (c.type() == LOCAL_PORT_TYPE) {
1097 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1098 // We allow host candidates if the filter allows server-reflexive
1099 // candidates and the candidate is a public IP. Because we don't generate
1100 // server-reflexive candidates if they have the same IP as the host
1101 // candidate (i.e. when the host candidate is a public IP), filtering to
1102 // only server-reflexive candidates won't work right when the host
1103 // candidates have public IPs.
1104 return true;
1105 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001107 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001108 }
1109 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110}
1111
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001112bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1113 const Port* port) const {
1114 bool candidate_signalable = CheckCandidateFilter(c);
1115
1116 // When device enumeration is disabled (to prevent non-default IP addresses
1117 // from leaking), we ping from some local candidates even though we don't
1118 // signal them. However, if host candidates are also disabled (for example, to
1119 // prevent even default IP addresses from leaking), we still don't want to
1120 // ping from them, even if device enumeration is disabled. Thus, we check for
1121 // both device enumeration and host candidates being disabled.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001122 bool candidate_has_any_address = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001123 bool can_ping_from_candidate =
1124 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1125 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1126
1127 return candidate_signalable ||
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001128 (candidate_has_any_address && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001129 !host_candidates_disabled);
1130}
1131
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132void BasicPortAllocatorSession::OnPortAllocationComplete(
1133 AllocationSequence* seq) {
1134 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001135 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001136}
1137
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001138void BasicPortAllocatorSession::FireAllocationStatusSignalsIfNeeded() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001139 if (CandidatesAllocationDone()) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001140 // Now that allocation is done, we can surface any ports bound to the "any"
1141 // address if they're not redundant (if they don't have the same address as
1142 // a port bound to a specific interface). We don't surface them as soon as
1143 // they're gathered because we may not know yet whether they're redundant.
1144 //
1145 // This also happens after a timeout of 2 seconds (see comment in
1146 // DoAllocate); if allocation completes first we clear that timer since
1147 // it's not needed.
1148 network_thread_->Clear(this, MSG_SIGNAL_ANY_ADDRESS_PORTS);
1149 SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001150 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001151 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001152 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001153 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1154 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001155 }
1156 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001157 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001158}
1159
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001160// We detect the redundancy in any address ports as follows:
1161//
1162// 1. Delay the signaling of all any address ports and candidates gathered from
1163// these ports, which happens in OnCandidateReady.
1164//
1165// 2. For all non-any address ports, collect the IPs of their candidates
1166// (ignoring "active" TCP candidates, since no sockets are created for them
1167// until a connection is made and there's no guarantee they'll work).
1168//
1169// 3. For each any address port, compare their candidates to the existing IPs
1170// collected from step 2, and this port can be signaled if it has candidates
1171// with unseen IPs.
1172void BasicPortAllocatorSession::
1173 SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant() {
1174 // Note that this is called either when allocation completes, or after a
1175 // timeout, so some ports may still be waiting for STUN transactions to
1176 // finish.
1177 //
1178 // First, get a list of all "any address" ports that have not yet been
1179 // signaled, and a list of candidate IP addresses from all other ports.
1180 std::vector<PortData*> maybe_signalable_any_address_ports;
1181 std::set<rtc::IPAddress> ips_from_non_any_address_ports;
1182 for (PortData& port_data : ports_) {
1183 if (!port_data.ready()) {
1184 continue;
1185 }
1186 if (IsAnyAddressPort(port_data.port())) {
1187 if (!port_data.signaled()) {
1188 maybe_signalable_any_address_ports.push_back(&port_data);
1189 }
1190 } else {
1191 for (const Candidate& c : port_data.port()->Candidates()) {
1192 // If the port of the candidate is |DISCARD_PORT| (9), this is an
1193 // "active" TCP candidate and it doesn't mean we actually bound a
1194 // socket to this address, so ignore it.
1195 if (c.address().port() != DISCARD_PORT) {
1196 ips_from_non_any_address_ports.insert(c.address().ipaddr());
1197 }
1198 }
1199 }
1200 }
1201 // Now signal "any" address ports that have a unique address, and prune any
1202 // that don't.
1203 std::vector<PortData*> signalable_any_address_ports;
1204 std::vector<PortData*> prunable_any_address_ports;
1205 std::vector<Candidate> signalable_candidates_from_any_address_ports;
1206 for (PortData* port_data : maybe_signalable_any_address_ports) {
1207 bool port_signalable = false;
1208 for (const Candidate& c : port_data->port()->Candidates()) {
1209 if (!CandidatePairable(c, port_data->port()) ||
1210 ips_from_non_any_address_ports.count(c.address().ipaddr())) {
1211 continue;
1212 }
1213 // Even when a port is bound to the "any" address, it should normally
1214 // still have an associated IP (determined by calling "connect" and then
1215 // "getsockaddr"). Though sometimes even this fails (meaning |is_any_ip|
1216 // will be true), and thus we have no way of knowing whether the port is
1217 // redundant or not. In that case, we'll use the port if we have
1218 // *no* ports bound to specific addresses. This is needed for corner
1219 // cases such as bugs.webrtc.org/7798.
1220 bool is_any_ip = rtc::IPIsAny(c.address().ipaddr());
1221 if (is_any_ip && !ips_from_non_any_address_ports.empty()) {
1222 continue;
1223 }
1224 port_signalable = true;
1225 // Still need to check the candidiate filter and sanitize the related
1226 // address before signaling the candidate itself.
1227 if (CheckCandidateFilter(c)) {
1228 signalable_candidates_from_any_address_ports.push_back(
1229 SanitizeRelatedAddress(c));
1230 }
1231 }
1232 if (port_signalable) {
1233 signalable_any_address_ports.push_back(port_data);
1234 } else {
1235 prunable_any_address_ports.push_back(port_data);
1236 }
1237 }
1238 PrunePorts(prunable_any_address_ports);
1239 for (PortData* port_data : signalable_any_address_ports) {
1240 RTC_LOG(INFO) << port_data->port()->ToString() << ": Port ready.";
1241 SignalPortReady(this, port_data->port());
1242 port_data->set_signaled();
1243 }
1244 RTC_LOG(INFO) << "Signaling candidates from the any address ports.";
1245 SignalCandidatesReady(this, signalable_candidates_from_any_address_ports);
1246}
1247
1248void BasicPortAllocatorSession::OnPortDestroyed(
1249 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001250 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001251 for (std::vector<PortData>::iterator iter = ports_.begin();
1252 iter != ports_.end(); ++iter) {
1253 if (port == iter->port()) {
1254 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001255 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001256 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001257 return;
1258 }
1259 }
nissec80e7412017-01-11 05:56:46 -08001260 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001261}
1262
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001263BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1264 Port* port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001265 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1266 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001267 if (it->port() == port) {
1268 return &*it;
1269 }
1270 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001271 return nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001272}
1273
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001274std::vector<BasicPortAllocatorSession::PortData*>
1275BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001276 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001277 std::vector<PortData*> unpruned_ports;
1278 for (PortData& port : ports_) {
1279 if (!port.pruned() &&
1280 std::find(networks.begin(), networks.end(),
1281 port.sequence()->network()) != networks.end()) {
1282 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001283 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001284 }
1285 return unpruned_ports;
1286}
1287
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001288std::vector<Candidate> BasicPortAllocatorSession::PrunePorts(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001289 const std::vector<PortData*>& port_data_list) {
1290 std::vector<PortInterface*> pruned_ports;
1291 std::vector<Candidate> removed_candidates;
1292 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001293 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001294 data->Prune();
1295 pruned_ports.push_back(data->port());
1296 if (data->has_pairable_candidate()) {
1297 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001298 // Mark the port as having no pairable candidates so that its candidates
1299 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001300 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001301 }
1302 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001303 if (!pruned_ports.empty()) {
1304 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001305 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001306 return removed_candidates;
1307}
1308
1309void BasicPortAllocatorSession::PrunePortsAndSignalCandidatesRemoval(
1310 const std::vector<PortData*>& port_data_list) {
1311 std::vector<Candidate> removed_candidates = PrunePorts(port_data_list);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001312 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001313 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1314 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001315 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001316 }
1317}
1318
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001319// AllocationSequence
1320
1321AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1322 rtc::Network* network,
1323 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001324 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325 : session_(session),
1326 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001327 config_(config),
1328 state_(kInit),
1329 flags_(flags),
1330 udp_socket_(),
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001331 udp_port_(nullptr),
Yves Gerey665174f2018-06-19 15:03:05 +02001332 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333
Honghai Zhang5048f572016-08-23 15:47:33 -07001334void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001335 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1336 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001337 rtc::SocketAddress(network_->GetBestIP(), 0),
1338 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001339 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001340 udp_socket_->SignalReadPacket.connect(this,
1341 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001343 // Continuing if |udp_socket_| is null, as local TCP and RelayPort using
1344 // TCP are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001345 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346}
1347
1348void AllocationSequence::Clear() {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001349 udp_port_ = nullptr;
Jonas Oreland202994c2017-12-18 12:10:43 +01001350 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001351}
1352
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001353void AllocationSequence::OnNetworkFailed() {
1354 RTC_DCHECK(!network_failed_);
1355 network_failed_ = true;
1356 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001357 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001358}
1359
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001360AllocationSequence::~AllocationSequence() {
1361 session_->network_thread()->Clear(this);
1362}
1363
1364void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001365 PortConfiguration* config,
1366 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001367 if (network_failed_) {
1368 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001369 // it won't be equivalent to the new network.
1370 return;
1371 }
1372
deadbeef5c3c1042017-08-04 15:01:57 -07001373 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001374 // Different network setup; nothing is equivalent.
1375 return;
1376 }
1377
1378 // Else turn off the stuff that we've already got covered.
1379
deadbeef1c46a352017-09-27 11:24:05 -07001380 // Every config implicitly specifies local, so turn that off right away if we
1381 // already have a port of the corresponding type. Look for a port that
1382 // matches this AllocationSequence's network, is the right protocol, and
1383 // hasn't encountered an error.
1384 // TODO(deadbeef): This doesn't take into account that there may be another
1385 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1386 // This can happen if, say, there's a network change event right before an
1387 // application-triggered ICE restart. Hopefully this problem will just go
1388 // away if we get rid of the gathering "phases" though, which is planned.
1389 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1390 [this](const BasicPortAllocatorSession::PortData& p) {
1391 return p.port()->Network() == network_ &&
1392 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1393 })) {
1394 *flags |= PORTALLOCATOR_DISABLE_UDP;
1395 }
1396 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1397 [this](const BasicPortAllocatorSession::PortData& p) {
1398 return p.port()->Network() == network_ &&
1399 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1400 })) {
1401 *flags |= PORTALLOCATOR_DISABLE_TCP;
1402 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001403
1404 if (config_ && config) {
1405 if (config_->StunServers() == config->StunServers()) {
1406 // Already got this STUN servers covered.
1407 *flags |= PORTALLOCATOR_DISABLE_STUN;
1408 }
1409 if (!config_->relays.empty()) {
1410 // Already got relays covered.
1411 // NOTE: This will even skip a _different_ set of relay servers if we
1412 // were to be given one, but that never happens in our codebase. Should
1413 // probably get rid of the list in PortConfiguration and just keep a
1414 // single relay server in each one.
1415 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1416 }
1417 }
1418}
1419
1420void AllocationSequence::Start() {
1421 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001422 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001423 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1424 // called next time, we enable all phases if the best IP has since changed.
1425 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426}
1427
1428void AllocationSequence::Stop() {
1429 // If the port is completed, don't set it to stopped.
1430 if (state_ == kRunning) {
1431 state_ = kStopped;
1432 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1433 }
1434}
1435
1436void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001437 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1438 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001439
deadbeef1c5e6d02017-09-15 17:46:56 -07001440 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001441
1442 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001443 RTC_LOG(LS_INFO) << network_->ToString()
1444 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001445
1446 switch (phase_) {
1447 case PHASE_UDP:
1448 CreateUDPPorts();
1449 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001450 break;
1451
1452 case PHASE_RELAY:
1453 CreateRelayPorts();
1454 break;
1455
1456 case PHASE_TCP:
1457 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001458 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001459 break;
1460
1461 default:
nissec80e7412017-01-11 05:56:46 -08001462 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463 }
1464
1465 if (state() == kRunning) {
1466 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001467 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1468 session_->allocator()->step_delay(),
1469 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001470 } else {
1471 // If all phases in AllocationSequence are completed, no allocation
1472 // steps needed further. Canceling pending signal.
1473 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1474 SignalPortAllocationComplete(this);
1475 }
1476}
1477
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001478void AllocationSequence::CreateUDPPorts() {
1479 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001480 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001481 return;
1482 }
1483
1484 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1485 // is enabled completely.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001486 UDPPort* port = nullptr;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001487 bool emit_local_candidate_for_anyaddress =
1488 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001489 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001490 port = UDPPort::Create(
1491 session_->network_thread(), session_->socket_factory(), network_,
1492 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001493 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1494 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001495 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001496 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001497 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001498 session_->allocator()->min_port(), session_->allocator()->max_port(),
1499 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001500 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1501 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001502 }
1503
1504 if (port) {
1505 // If shared socket is enabled, STUN candidate will be allocated by the
1506 // UDPPort.
1507 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1508 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001509 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001510
1511 // If STUN is not disabled, setting stun server address to port.
1512 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001513 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001514 RTC_LOG(LS_INFO)
1515 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001516 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001517 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001518 }
1519 }
1520 }
1521
1522 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001523 }
1524}
1525
1526void AllocationSequence::CreateTCPPorts() {
1527 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001528 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001529 return;
1530 }
1531
deadbeef5c3c1042017-08-04 15:01:57 -07001532 Port* port = TCPPort::Create(
1533 session_->network_thread(), session_->socket_factory(), network_,
1534 session_->allocator()->min_port(), session_->allocator()->max_port(),
1535 session_->username(), session_->password(),
1536 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001537 if (port) {
1538 session_->AddAllocatedPort(port, this, true);
1539 // Since TCPPort is not created using shared socket, |port| will not be
1540 // added to the dequeue.
1541 }
1542}
1543
1544void AllocationSequence::CreateStunPorts() {
1545 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001546 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001547 return;
1548 }
1549
1550 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1551 return;
1552 }
1553
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001554 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001555 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001556 << "AllocationSequence: No STUN server configured, skipping.";
1557 return;
1558 }
1559
deadbeef5c3c1042017-08-04 15:01:57 -07001560 StunPort* port = StunPort::Create(
1561 session_->network_thread(), session_->socket_factory(), network_,
1562 session_->allocator()->min_port(), session_->allocator()->max_port(),
1563 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001564 session_->allocator()->origin(),
1565 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001566 if (port) {
1567 session_->AddAllocatedPort(port, this, true);
1568 // Since StunPort is not created using shared socket, |port| will not be
1569 // added to the dequeue.
1570 }
1571}
1572
1573void AllocationSequence::CreateRelayPorts() {
1574 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001575 RTC_LOG(LS_VERBOSE)
1576 << "AllocationSequence: Relay ports disabled, skipping.";
1577 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001578 }
1579
1580 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1581 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001582 RTC_DCHECK(config_);
1583 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001584 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001585 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001586 << "AllocationSequence: No relay server configured, skipping.";
1587 return;
1588 }
1589
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001590 for (RelayServerConfig& relay : config_->relays) {
1591 if (relay.type == RELAY_GTURN) {
1592 CreateGturnPort(relay);
1593 } else if (relay.type == RELAY_TURN) {
1594 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001595 } else {
nissec80e7412017-01-11 05:56:46 -08001596 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001597 }
1598 }
1599}
1600
1601void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1602 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001603 RelayPort* port = RelayPort::Create(
1604 session_->network_thread(), session_->socket_factory(), network_,
1605 session_->allocator()->min_port(), session_->allocator()->max_port(),
1606 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001607 if (port) {
1608 // Since RelayPort is not created using shared socket, |port| will not be
1609 // added to the dequeue.
1610 // Note: We must add the allocated port before we add addresses because
1611 // the latter will create candidates that need name and preference
1612 // settings. However, we also can't prepare the address (normally
1613 // done by AddAllocatedPort) until we have these addresses. So we
1614 // wait to do that until below.
1615 session_->AddAllocatedPort(port, this, false);
1616
1617 // Add the addresses of this protocol.
1618 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001619 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001620 ++relay_port) {
1621 port->AddServerAddress(*relay_port);
1622 port->AddExternalAddress(*relay_port);
1623 }
1624 // Start fetching an address for this port.
1625 port->PrepareAddress();
1626 }
1627}
1628
1629void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1630 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001631 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1632 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001633 // Skip UDP connections to relay servers if it's disallowed.
1634 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1635 relay_port->proto == PROTO_UDP) {
1636 continue;
1637 }
1638
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001639 // Do not create a port if the server address family is known and does
1640 // not match the local IP address family.
1641 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001642 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001643 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001644 RTC_LOG(LS_INFO)
1645 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001646 "Server address: "
1647 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001648 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001649 continue;
1650 }
1651
Jonas Oreland202994c2017-12-18 12:10:43 +01001652 CreateRelayPortArgs args;
1653 args.network_thread = session_->network_thread();
1654 args.socket_factory = session_->socket_factory();
1655 args.network = network_;
1656 args.username = session_->username();
1657 args.password = session_->password();
1658 args.server_address = &(*relay_port);
1659 args.config = &config;
1660 args.origin = session_->allocator()->origin();
1661 args.turn_customizer = session_->allocator()->turn_customizer();
1662
1663 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001664 // Shared socket mode must be enabled only for UDP based ports. Hence
1665 // don't pass shared socket for ports which will create TCP sockets.
1666 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1667 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1668 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001669 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001670 port = session_->allocator()->relay_port_factory()->Create(
1671 args, udp_socket_.get());
1672
1673 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001674 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1675 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001676 continue;
1677 }
1678
1679 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001680 // Listen to the port destroyed signal, to allow AllocationSequence to
1681 // remove entrt from it's map.
1682 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1683 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001684 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001685 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001686 session_->allocator()->max_port());
1687
1688 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001689 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1690 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001691 continue;
1692 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001693 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001694 RTC_DCHECK(port != nullptr);
Jonas Oreland202994c2017-12-18 12:10:43 +01001695 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001696 }
1697}
1698
Yves Gerey665174f2018-06-19 15:03:05 +02001699void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1700 const char* data,
1701 size_t size,
1702 const rtc::SocketAddress& remote_addr,
1703 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001704 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001705
1706 bool turn_port_found = false;
1707
1708 // Try to find the TurnPort that matches the remote address. Note that the
1709 // message could be a STUN binding response if the TURN server is also used as
1710 // a STUN server. We don't want to parse every message here to check if it is
1711 // a STUN binding response, so we pass the message to TurnPort regardless of
1712 // the message type. The TurnPort will just ignore the message since it will
1713 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001714 for (auto* port : relay_ports_) {
1715 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001716 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1717 packet_time)) {
1718 return;
1719 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001720 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001721 }
1722 }
1723
1724 if (udp_port_) {
1725 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1726
1727 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1728 // the TURN server is also a STUN server.
1729 if (!turn_port_found ||
1730 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001731 RTC_DCHECK(udp_port_->SharedSocket());
1732 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1733 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001734 }
1735 }
1736}
1737
1738void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1739 if (udp_port_ == port) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001740 udp_port_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001741 return;
1742 }
1743
Jonas Oreland202994c2017-12-18 12:10:43 +01001744 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1745 if (it != relay_ports_.end()) {
1746 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001747 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001748 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001749 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001750 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001751}
1752
1753// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001754PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1755 const std::string& username,
1756 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001757 : stun_address(stun_address), username(username), password(password) {
1758 if (!stun_address.IsNil())
1759 stun_servers.insert(stun_address);
1760}
1761
1762PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1763 const std::string& username,
1764 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001765 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001766 if (!stun_servers.empty())
1767 stun_address = *(stun_servers.begin());
1768}
1769
Steve Anton7995d8c2017-10-30 16:23:38 -07001770PortConfiguration::~PortConfiguration() = default;
1771
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001772ServerAddresses PortConfiguration::StunServers() {
1773 if (!stun_address.IsNil() &&
1774 stun_servers.find(stun_address) == stun_servers.end()) {
1775 stun_servers.insert(stun_address);
1776 }
deadbeefc5d0d952015-07-16 10:22:21 -07001777 // Every UDP TURN server should also be used as a STUN server.
1778 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1779 for (const rtc::SocketAddress& turn_server : turn_servers) {
1780 if (stun_servers.find(turn_server) == stun_servers.end()) {
1781 stun_servers.insert(turn_server);
1782 }
1783 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001784 return stun_servers;
1785}
1786
1787void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1788 relays.push_back(config);
1789}
1790
Yves Gerey665174f2018-06-19 15:03:05 +02001791bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1792 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001793 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001794 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1795 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001796 if (relay_port->proto == type)
1797 return true;
1798 }
1799 return false;
1800}
1801
1802bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1803 ProtocolType type) const {
1804 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001805 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001806 return true;
1807 }
1808 return false;
1809}
1810
1811ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001812 RelayType turn_type,
1813 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001814 ServerAddresses servers;
1815 for (size_t i = 0; i < relays.size(); ++i) {
1816 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1817 servers.insert(relays[i].ports.front().address);
1818 }
1819 }
1820 return servers;
1821}
1822
1823} // namespace cricket