blob: eb14a3775886f29ebf62e92cde784682e377ea24 [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 "p2p/base/basicpacketsocketfactory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "p2p/base/port.h"
21#include "p2p/base/relayport.h"
22#include "p2p/base/stunport.h"
23#include "p2p/base/tcpport.h"
24#include "p2p/base/turnport.h"
25#include "p2p/base/udpport.h"
26#include "rtc_base/checks.h"
27#include "rtc_base/helpers.h"
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +000028#include "rtc_base/ipaddress.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/logging.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070030#include "system_wrappers/include/metrics.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) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700199 // If the session has not been taken by an active channel, do not report the
200 // metric.
201 for (auto& allocator_session : pooled_sessions()) {
202 if (allocator_session.get() == session) {
203 return;
204 }
205 }
206
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700207 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
208 static_cast<int>(reason),
209 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700210}
211
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700213 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800214 // Our created port allocator sessions depend on us, so destroy our remaining
215 // pooled sessions before anything else.
216 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217}
218
Steve Anton7995d8c2017-10-30 16:23:38 -0700219void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
220 // TODO(phoglund): implement support for other types than loopback.
221 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
222 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700223 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700224 network_ignore_mask_ = network_ignore_mask;
225}
226
deadbeefc5d0d952015-07-16 10:22:21 -0700227PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200228 const std::string& content_name,
229 int component,
230 const std::string& ice_ufrag,
231 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700232 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700233 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700235 session->SignalIceRegathering.connect(this,
236 &BasicPortAllocator::OnIceRegathering);
237 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238}
239
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700240void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700241 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700242 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
243 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700244 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200245 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247
Jonas Oreland202994c2017-12-18 12:10:43 +0100248void BasicPortAllocator::InitRelayPortFactory(
249 RelayPortFactoryInterface* relay_port_factory) {
250 if (relay_port_factory != nullptr) {
251 relay_port_factory_ = relay_port_factory;
252 } else {
253 default_relay_port_factory_.reset(new TurnPortFactory());
254 relay_port_factory_ = default_relay_port_factory_.get();
255 }
256}
257
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258// BasicPortAllocatorSession
259BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700260 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 const std::string& content_name,
262 int component,
263 const std::string& ice_ufrag,
264 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700265 : PortAllocatorSession(content_name,
266 component,
267 ice_ufrag,
268 ice_pwd,
269 allocator->flags()),
270 allocator_(allocator),
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000271 network_thread_(nullptr),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000272 socket_factory_(allocator->socket_factory()),
273 allocation_started_(false),
274 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700275 allocation_sequences_created_(false),
276 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277 allocator_->network_manager()->SignalNetworksChanged.connect(
278 this, &BasicPortAllocatorSession::OnNetworksChanged);
279 allocator_->network_manager()->StartUpdating();
280}
281
282BasicPortAllocatorSession::~BasicPortAllocatorSession() {
283 allocator_->network_manager()->StopUpdating();
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000284 if (network_thread_ != nullptr)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 network_thread_->Clear(this);
286
Peter Boström0c4e06b2015-10-07 12:23:21 +0200287 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 // AllocationSequence should clear it's map entry for turn ports before
289 // ports are destroyed.
290 sequences_[i]->Clear();
291 }
292
293 std::vector<PortData>::iterator it;
294 for (it = ports_.begin(); it != ports_.end(); it++)
295 delete it->port();
296
Peter Boström0c4e06b2015-10-07 12:23:21 +0200297 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000298 delete configs_[i];
299
Peter Boström0c4e06b2015-10-07 12:23:21 +0200300 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000301 delete sequences_[i];
302}
303
Steve Anton7995d8c2017-10-30 16:23:38 -0700304BasicPortAllocator* BasicPortAllocatorSession::allocator() {
305 return allocator_;
306}
307
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700308void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
309 if (filter == candidate_filter_) {
310 return;
311 }
312 // We assume the filter will only change from "ALL" to something else.
313 RTC_DCHECK(candidate_filter_ == CF_ALL);
314 candidate_filter_ = filter;
315 for (PortData& port : ports_) {
316 if (!port.has_pairable_candidate()) {
317 continue;
318 }
319 const auto& candidates = port.port()->Candidates();
320 // Setting a filter may cause a ready port to become non-ready
321 // if it no longer has any pairable candidates.
322 if (!std::any_of(candidates.begin(), candidates.end(),
323 [this, &port](const Candidate& candidate) {
324 return CandidatePairable(candidate, port.port());
325 })) {
326 port.set_has_pairable_candidate(false);
327 }
328 }
329}
330
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331void BasicPortAllocatorSession::StartGettingPorts() {
332 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700333 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000334 if (!socket_factory_) {
335 owned_socket_factory_.reset(
336 new rtc::BasicPacketSocketFactory(network_thread_));
337 socket_factory_ = owned_socket_factory_.get();
338 }
339
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700340 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700341
Mirko Bonadei675513b2017-11-09 11:09:25 +0100342 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
343 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344}
345
346void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800347 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700348 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700349 // Note: this must be called after ClearGettingPorts because both may set the
350 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700351 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700352}
353
354void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800355 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700357 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000358 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700359 }
deadbeefb60a8192016-08-24 15:15:00 -0700360 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700361 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700362}
363
Steve Anton7995d8c2017-10-30 16:23:38 -0700364bool BasicPortAllocatorSession::IsGettingPorts() {
365 return state_ == SessionState::GATHERING;
366}
367
368bool BasicPortAllocatorSession::IsCleared() const {
369 return state_ == SessionState::CLEARED;
370}
371
372bool BasicPortAllocatorSession::IsStopped() const {
373 return state_ == SessionState::STOPPED;
374}
375
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700376std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
377 std::vector<rtc::Network*> networks = GetNetworks();
378
379 // A network interface may have both IPv4 and IPv6 networks. Only if
380 // neither of the networks has any connections, the network interface
381 // is considered failed and need to be regathered on.
382 std::set<std::string> networks_with_connection;
383 for (const PortData& data : ports_) {
384 Port* port = data.port();
385 if (!port->connections().empty()) {
386 networks_with_connection.insert(port->Network()->name());
387 }
388 }
389
390 networks.erase(
391 std::remove_if(networks.begin(), networks.end(),
392 [networks_with_connection](rtc::Network* network) {
393 // If a network does not have any connection, it is
394 // considered failed.
395 return networks_with_connection.find(network->name()) !=
396 networks_with_connection.end();
397 }),
398 networks.end());
399 return networks;
400}
401
402void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
403 // Find the list of networks that have no connection.
404 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
405 if (failed_networks.empty()) {
406 return;
407 }
408
Mirko Bonadei675513b2017-11-09 11:09:25 +0100409 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700410
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700411 // Mark a sequence as "network failed" if its network is in the list of failed
412 // networks, so that it won't be considered as equivalent when the session
413 // regathers ports and candidates.
414 for (AllocationSequence* sequence : sequences_) {
415 if (!sequence->network_failed() &&
416 std::find(failed_networks.begin(), failed_networks.end(),
417 sequence->network()) != failed_networks.end()) {
418 sequence->set_network_failed();
419 }
420 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700421
422 bool disable_equivalent_phases = true;
423 Regather(failed_networks, disable_equivalent_phases,
424 IceRegatheringReason::NETWORK_FAILURE);
425}
426
427void BasicPortAllocatorSession::RegatherOnAllNetworks() {
428 std::vector<rtc::Network*> networks = GetNetworks();
429 if (networks.empty()) {
430 return;
431 }
432
Mirko Bonadei675513b2017-11-09 11:09:25 +0100433 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700434
435 // We expect to generate candidates that are equivalent to what we have now.
436 // Force DoAllocate to generate them instead of skipping.
437 bool disable_equivalent_phases = false;
438 Regather(networks, disable_equivalent_phases,
439 IceRegatheringReason::OCCASIONAL_REFRESH);
440}
441
442void BasicPortAllocatorSession::Regather(
443 const std::vector<rtc::Network*>& networks,
444 bool disable_equivalent_phases,
445 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700446 // Remove ports from being used locally and send signaling to remove
447 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700448 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700449 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100450 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000451 PrunePortsAndSignalCandidatesRemoval(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700452 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700453
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700454 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700455 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700456
Steve Anton300bf8e2017-07-14 10:13:10 -0700457 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700458 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459}
460
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800461void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200462 const absl::optional<int>& stun_keepalive_interval) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800463 auto ports = ReadyPorts();
464 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800465 // The port type and protocol can be used to identify different subclasses
466 // of Port in the current implementation. Note that a TCPPort has the type
467 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
468 if (port->Type() == STUN_PORT_TYPE ||
469 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800470 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
471 stun_keepalive_interval);
472 }
473 }
474}
475
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700476std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
477 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700478 for (const PortData& data : ports_) {
479 if (data.ready()) {
480 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700481 }
482 }
483 return ret;
484}
485
486std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
487 std::vector<Candidate> candidates;
488 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700489 if (!data.ready()) {
490 continue;
491 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700492 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700493 }
494 return candidates;
495}
496
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700497void BasicPortAllocatorSession::GetCandidatesFromPort(
498 const PortData& data,
499 std::vector<Candidate>* candidates) const {
500 RTC_CHECK(candidates != nullptr);
501 for (const Candidate& candidate : data.port()->Candidates()) {
502 if (!CheckCandidateFilter(candidate)) {
503 continue;
504 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700505 candidates->push_back(SanitizeRelatedAddress(candidate));
506 }
507}
508
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700509Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
510 const Candidate& c) const {
511 Candidate copy = c;
512 // If adapter enumeration is disabled or host candidates are disabled,
513 // clear the raddr of STUN candidates to avoid local address leakage.
514 bool filter_stun_related_address =
515 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
516 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
517 !(candidate_filter_ & CF_HOST);
518 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
519 // to avoid reflexive address leakage.
520 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
521 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
522 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
523 copy.set_related_address(
524 rtc::EmptySocketAddressWithFamily(copy.address().family()));
525 }
526 return copy;
527}
528
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700529bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
530 // Done only if all required AllocationSequence objects
531 // are created.
532 if (!allocation_sequences_created_) {
533 return false;
534 }
535
536 // Check that all port allocation sequences are complete (not running).
537 if (std::any_of(sequences_.begin(), sequences_.end(),
538 [](const AllocationSequence* sequence) {
539 return sequence->state() == AllocationSequence::kRunning;
540 })) {
541 return false;
542 }
543
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700544 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700545 // expected candidates. Session will trigger candidates allocation complete
546 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700547 return std::none_of(ports_.begin(), ports_.end(),
548 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700549}
550
Yves Gerey665174f2018-06-19 15:03:05 +0200551void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200553 case MSG_CONFIG_START:
554 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
555 GetPortConfigurations();
556 break;
557 case MSG_CONFIG_READY:
558 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
559 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
560 break;
561 case MSG_ALLOCATE:
562 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
563 OnAllocate();
564 break;
565 case MSG_SEQUENCEOBJECTS_CREATED:
566 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
567 OnAllocationSequenceObjectsCreated();
568 break;
569 case MSG_CONFIG_STOP:
570 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
571 OnConfigStop();
572 break;
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000573 case MSG_SIGNAL_ANY_ADDRESS_PORTS:
574 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
575 SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant();
576 break;
Yves Gerey665174f2018-06-19 15:03:05 +0200577 default:
578 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000579 }
580}
581
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700582void BasicPortAllocatorSession::UpdateIceParametersInternal() {
583 for (PortData& port : ports_) {
584 port.port()->set_content_name(content_name());
585 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
586 }
587}
588
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589void BasicPortAllocatorSession::GetPortConfigurations() {
Yves Gerey665174f2018-06-19 15:03:05 +0200590 PortConfiguration* config =
591 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592
deadbeef653b8e02015-11-11 12:55:10 -0800593 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
594 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595 }
596 ConfigReady(config);
597}
598
599void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700600 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000601}
602
603// Adds a configuration to the list.
604void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800605 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000606 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800607 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608
609 AllocatePorts();
610}
611
612void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800613 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614
615 // If any of the allocated ports have not completed the candidates allocation,
616 // mark those as error. Since session doesn't need any new candidates
617 // at this stage of the allocation, it's safe to discard any new candidates.
618 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200619 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
620 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700621 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000622 // Updating port state to error, which didn't finish allocating candidates
623 // yet.
624 it->set_error();
625 send_signal = true;
626 }
627 }
628
629 // Did we stop any running sequences?
630 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
631 it != sequences_.end() && !send_signal; ++it) {
632 if ((*it)->state() == AllocationSequence::kStopped) {
633 send_signal = true;
634 }
635 }
636
637 // If we stopped anything that was running, send a done signal now.
638 if (send_signal) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000639 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640 }
641}
642
643void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800644 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700645 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646}
647
648void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700649 if (network_manager_started_ && !IsStopped()) {
650 bool disable_equivalent_phases = true;
651 DoAllocate(disable_equivalent_phases);
652 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653
654 allocation_started_ = true;
655}
656
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700657std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
658 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700659 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800660 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700661 // If the network permission state is BLOCKED, we just act as if the flag has
662 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700663 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700664 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700665 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
666 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000667
668 // If adapter enumeration is disabled, we'll just bind to any address
669 // instead of a specific NIC. This is to ensure that WebRTC traffic is routed
670 // by the OS in the same way that HTTP traffic would be, and no additional
671 // local or public IPs are leaked during ICE processing.
672 //
673 // Even when adapter enumeration is enabled, we still bind to the "any"
674 // address as a fallback, since this may potentially reveal network
675 // interfaces that weren't otherwise accessible. Note that the candidates
676 // gathered by binding to the "any" address won't be surfaced to the
677 // application if they're determined to be redundant (if they have the same
678 // address as a candidate gathered by binding to an interface explicitly).
679 if (!(flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION)) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700680 network_manager->GetNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000681 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000682
683 network_manager->GetAnyAddressNetworks(&networks);
684
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100685 // Filter out link-local networks if needed.
686 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700687 NetworkFilter link_local_filter(
688 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
689 "link-local");
690 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100691 }
deadbeef3427f532017-07-26 16:09:33 -0700692 // Do some more filtering, depending on the network ignore mask and "disable
693 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700694 NetworkFilter ignored_filter(
695 [this](rtc::Network* network) {
696 return allocator_->network_ignore_mask() & network->type();
697 },
698 "ignored");
699 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700700 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
701 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700702 for (rtc::Network* network : networks) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000703 // Don't determine the lowest cost from a link-local or any address
704 // network. On iOS, a device connected to the computer will get a
705 // link-local network for communicating with the computer, however this
706 // network can't be used to connect to a peer outside the network.
707 if (rtc::IPIsLinkLocal(network->GetBestIP()) ||
708 rtc::IPIsAny(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800709 continue;
710 }
honghaiz60347052016-05-31 18:29:12 -0700711 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
712 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700713 NetworkFilter costly_filter(
714 [lowest_cost](rtc::Network* network) {
715 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
716 },
717 "costly");
718 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700719 }
deadbeef3427f532017-07-26 16:09:33 -0700720 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
721 // default, it's 5), remove networks to ensure that limit is satisfied.
722 //
723 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
724 // networks, we could try to choose a set that's "most likely to work". It's
725 // hard to define what that means though; it's not just "lowest cost".
726 // Alternatively, we could just focus on making our ICE pinging logic smarter
727 // such that this filtering isn't necessary in the first place.
728 int ipv6_networks = 0;
729 for (auto it = networks.begin(); it != networks.end();) {
730 if ((*it)->prefix().family() == AF_INET6) {
731 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
732 it = networks.erase(it);
733 continue;
734 } else {
735 ++ipv6_networks;
736 }
737 }
738 ++it;
739 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700740 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700741}
742
743// For each network, see if we have a sequence that covers it already. If not,
744// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700745void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700746 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700747 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100749 RTC_LOG(LS_WARNING)
750 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000751 done_signal_needed = true;
752 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700754 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200755 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200756 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
758 // If all the ports are disabled we should just fire the allocation
759 // done event and return.
760 done_signal_needed = true;
761 break;
762 }
763
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000764 if (!config || config->relays.empty()) {
765 // No relay ports specified in this config.
766 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
767 }
768
769 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000770 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771 // Skip IPv6 networks unless the flag's been set.
772 continue;
773 }
774
zhihuangb09b3f92017-03-07 14:40:51 -0800775 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
776 networks[i]->GetBestIP().family() == AF_INET6 &&
777 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
778 // Skip IPv6 Wi-Fi networks unless the flag's been set.
779 continue;
780 }
781
Steve Anton300bf8e2017-07-14 10:13:10 -0700782 if (disable_equivalent) {
783 // Disable phases that would only create ports equivalent to
784 // ones that we have already made.
785 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786
Steve Anton300bf8e2017-07-14 10:13:10 -0700787 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
788 // New AllocationSequence would have nothing to do, so don't make it.
789 continue;
790 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791 }
792
793 AllocationSequence* sequence =
794 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000795 sequence->SignalPortAllocationComplete.connect(
796 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700797 sequence->Init();
798 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000799 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700800 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 }
802 }
803 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700804 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000805 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000806
807 // If adapter enumeration is enabled, then we prefer binding to individual
808 // network adapters, only using ports bound to the "any" address (0.0.0.0) if
809 // they reveal an interface not otherwise accessible. Normally these will be
810 // surfaced when candidate allocation completes, but sometimes candidate
811 // allocation can take a long time, if a STUN transaction times out for
812 // instance. So as a backup, we'll surface these ports/candidates after
813 // |kMaxWaitMsBeforeSignalingAnyAddressPortsAndCandidates| passes.
814 if (!(flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION)) {
815 network_thread_->PostDelayed(
816 RTC_FROM_HERE, kMaxWaitMsBeforeSignalingAnyAddressPortsAndCandidates,
817 this, MSG_SIGNAL_ANY_ADDRESS_PORTS);
818 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819}
820
821void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700822 std::vector<rtc::Network*> networks = GetNetworks();
823 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700824 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700825 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700826 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700827 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700828 std::find(networks.begin(), networks.end(), sequence->network()) ==
829 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700830 sequence->OnNetworkFailed();
831 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700832 }
833 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700834 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
835 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100836 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
837 << " ports because their networks were gone";
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000838 PrunePortsAndSignalCandidatesRemoval(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700839 }
honghaiz8c404fa2015-09-28 07:59:43 -0700840
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700841 if (allocation_started_ && !IsStopped()) {
842 if (network_manager_started_) {
843 // If the network manager has started, it must be regathering.
844 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
845 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700846 bool disable_equivalent_phases = true;
847 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700848 }
849
Honghai Zhang5048f572016-08-23 15:47:33 -0700850 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100851 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700852 network_manager_started_ = true;
853 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854}
855
856void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200857 rtc::Network* network,
858 PortConfiguration* config,
859 uint32_t* flags) {
860 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200861 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200862 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863 sequences_[i]->DisableEquivalentPhases(network, config, flags);
864 }
865}
866
867void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200868 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000869 bool prepare_address) {
870 if (!port)
871 return;
872
Mirko Bonadei675513b2017-11-09 11:09:25 +0100873 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700875 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700877 if (allocator_->proxy().type != rtc::PROXY_NONE)
878 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700879 port->set_send_retransmit_count_attribute(
880 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000882 PortData data(port, seq);
883 ports_.push_back(data);
884
885 port->SignalCandidateReady.connect(
886 this, &BasicPortAllocatorSession::OnCandidateReady);
887 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200888 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200890 &BasicPortAllocatorSession::OnPortDestroyed);
891 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
892 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893
894 if (prepare_address)
895 port->PrepareAddress();
896}
897
898void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
899 allocation_sequences_created_ = true;
900 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000901 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902}
903
Yves Gerey665174f2018-06-19 15:03:05 +0200904void BasicPortAllocatorSession::OnCandidateReady(Port* port,
905 const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800906 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000907 PortData* data = FindPort(port);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000908 RTC_DCHECK(data != nullptr);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200909 RTC_LOG(LS_INFO) << port->ToString()
910 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700912 // already done with gathering.
913 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100914 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700915 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700916 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700917 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700918
danilchapf4e8cf02016-06-30 01:55:03 -0700919 // Mark that the port has a pairable candidate, either because we have a
920 // usable candidate from the port, or simply because the port is bound to the
921 // any address and therefore has no host candidate. This will trigger the port
922 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700923 // checks. If port has already been marked as having a pairable candidate,
924 // do nothing here.
925 // Note: We should check whether any candidates may become ready after this
926 // because there we will check whether the candidate is generated by the ready
927 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700928 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700929 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700930 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700931
932 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700933 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700934 }
935 // If the current port is not pruned yet, SignalPortReady.
936 if (!data->pruned()) {
Honghai Zhanga74363c2016-07-28 18:06:15 -0700937 port->KeepAliveUntilPruned();
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000938 // We postpone the signaling of any address ports to when the candidates
939 // allocation is done or the candidate allocation process has start for
940 // more than kMaxWaitMsBeforeSignalingAnyAddressPortsAndCandidates, and
941 // we check whether they are redundant or not (in
942 // SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant). Otherwise,
943 // connectivity checks will be sent from these possibly redundant ports,
944 // likely also resulting in "prflx" candidate pairs being created on the
945 // other side if not pruned in time. The signaling of any address ports
946 // that are not redundant happens in
947 // SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant.
948 //
949 // If adapter enumeration is disabled, these "any" address ports
950 // are all we'll get, so we can signal them immediately.
951 //
952 // Same logic applies to candidates below.
953
954 if (!IsAnyAddressPort(port) ||
955 (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION)) {
956 RTC_LOG(INFO) << port->ToString() << ": Port ready.";
957 SignalPortReady(this, port);
958 data->set_signaled();
959 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700960 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700961 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700962
deadbeef1c5e6d02017-09-15 17:46:56 -0700963 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000964 // See comment above about why we delay signaling candidates from "any
965 // address" ports.
966 //
967 // For candidates gathered after the any address port is signaled, we will
968 // not perform the redundancy check anymore. Note that late candiates
969 // gathered from the any address port should be a srflx candidate from a
970 // late STUN binding response.
971 if (data->signaled()) {
972 std::vector<Candidate> candidates;
973 candidates.push_back(SanitizeRelatedAddress(c));
974 SignalCandidatesReady(this, candidates);
975 } else {
976 RTC_LOG(INFO) << "Candidate not signaled yet because it is from the "
977 "any address port: "
978 << c.ToSensitiveString();
979 }
deadbeefa64edb82016-07-15 14:42:21 -0700980 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100981 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700982 }
983
984 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700985 if (pruned) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +0000986 FireAllocationStatusSignalsIfNeeded();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700987 }
988}
989
990Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
991 const std::string& network_name) const {
992 Port* best_turn_port = nullptr;
993 for (const PortData& data : ports_) {
994 if (data.port()->Network()->name() == network_name &&
995 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
996 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
997 best_turn_port = data.port();
998 }
999 }
1000 return best_turn_port;
1001}
1002
1003bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001004 // Note: We determine the same network based only on their network names. So
1005 // if an IPv4 address and an IPv6 address have the same network name, they
1006 // are considered the same network here.
1007 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1008 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1009 // |port| is already in the list of ports, so the best port cannot be nullptr.
1010 RTC_CHECK(best_turn_port != nullptr);
1011
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001012 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001013 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001014 for (PortData& data : ports_) {
1015 if (data.port()->Network()->name() == network_name &&
1016 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1017 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001018 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001019 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001020 // These ports will be pruned in PrunePortsAndSignalCandidatesRemoval.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001021 ports_to_prune.push_back(&data);
1022 } else {
1023 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001024 }
1025 }
1026 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001027
1028 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001029 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1030 << " low-priority TURN ports";
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001031 PrunePortsAndSignalCandidatesRemoval(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001032 }
1033 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001034}
1035
Honghai Zhanga74363c2016-07-28 18:06:15 -07001036void BasicPortAllocatorSession::PruneAllPorts() {
1037 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001038 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001039 }
1040}
1041
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001042void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001043 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001044 RTC_LOG(LS_INFO) << port->ToString()
1045 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 PortData* data = FindPort(port);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001047 RTC_DCHECK(data != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048
1049 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001050 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001051 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001052 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001053
1054 // Moving to COMPLETE state.
1055 data->set_complete();
1056 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001057 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001058}
1059
1060void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001061 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001062 RTC_LOG(LS_INFO) << port->ToString()
1063 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001064 PortData* data = FindPort(port);
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001065 RTC_DCHECK(data != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001066 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001067 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001068 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001069 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001070
1071 // SignalAddressError is currently sent from StunPort/TurnPort.
1072 // But this signal itself is generic.
1073 data->set_error();
1074 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001075 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076}
1077
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001078bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001079 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001080
1081 // When binding to any address, before sending packets out, the getsockname
1082 // returns all 0s, but after sending packets, it'll be the NIC used to
1083 // send. All 0s is not a valid ICE candidate address and should be filtered
1084 // out.
1085 if (c.address().IsAnyIP()) {
1086 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001087 }
1088
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001089 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001090 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001091 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001092 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001093 } else if (c.type() == LOCAL_PORT_TYPE) {
1094 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1095 // We allow host candidates if the filter allows server-reflexive
1096 // candidates and the candidate is a public IP. Because we don't generate
1097 // server-reflexive candidates if they have the same IP as the host
1098 // candidate (i.e. when the host candidate is a public IP), filtering to
1099 // only server-reflexive candidates won't work right when the host
1100 // candidates have public IPs.
1101 return true;
1102 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001103
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001104 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001105 }
1106 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001107}
1108
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001109bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1110 const Port* port) const {
1111 bool candidate_signalable = CheckCandidateFilter(c);
1112
1113 // When device enumeration is disabled (to prevent non-default IP addresses
1114 // from leaking), we ping from some local candidates even though we don't
1115 // signal them. However, if host candidates are also disabled (for example, to
1116 // prevent even default IP addresses from leaking), we still don't want to
1117 // ping from them, even if device enumeration is disabled. Thus, we check for
1118 // both device enumeration and host candidates being disabled.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001119 bool candidate_has_any_address = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001120 bool can_ping_from_candidate =
1121 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1122 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1123
1124 return candidate_signalable ||
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001125 (candidate_has_any_address && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001126 !host_candidates_disabled);
1127}
1128
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001129void BasicPortAllocatorSession::OnPortAllocationComplete(
1130 AllocationSequence* seq) {
1131 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001132 FireAllocationStatusSignalsIfNeeded();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133}
1134
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001135void BasicPortAllocatorSession::FireAllocationStatusSignalsIfNeeded() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001136 if (CandidatesAllocationDone()) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001137 // Now that allocation is done, we can surface any ports bound to the "any"
1138 // address if they're not redundant (if they don't have the same address as
1139 // a port bound to a specific interface). We don't surface them as soon as
1140 // they're gathered because we may not know yet whether they're redundant.
1141 //
1142 // This also happens after a timeout of 2 seconds (see comment in
1143 // DoAllocate); if allocation completes first we clear that timer since
1144 // it's not needed.
1145 network_thread_->Clear(this, MSG_SIGNAL_ANY_ADDRESS_PORTS);
1146 SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001147 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001148 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001149 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001150 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1151 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001152 }
1153 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001155}
1156
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001157// We detect the redundancy in any address ports as follows:
1158//
1159// 1. Delay the signaling of all any address ports and candidates gathered from
1160// these ports, which happens in OnCandidateReady.
1161//
1162// 2. For all non-any address ports, collect the IPs of their candidates
1163// (ignoring "active" TCP candidates, since no sockets are created for them
1164// until a connection is made and there's no guarantee they'll work).
1165//
1166// 3. For each any address port, compare their candidates to the existing IPs
1167// collected from step 2, and this port can be signaled if it has candidates
1168// with unseen IPs.
1169void BasicPortAllocatorSession::
1170 SignalAnyAddressPortsAndCandidatesReadyIfNotRedundant() {
1171 // Note that this is called either when allocation completes, or after a
1172 // timeout, so some ports may still be waiting for STUN transactions to
1173 // finish.
1174 //
1175 // First, get a list of all "any address" ports that have not yet been
1176 // signaled, and a list of candidate IP addresses from all other ports.
1177 std::vector<PortData*> maybe_signalable_any_address_ports;
1178 std::set<rtc::IPAddress> ips_from_non_any_address_ports;
1179 for (PortData& port_data : ports_) {
1180 if (!port_data.ready()) {
1181 continue;
1182 }
1183 if (IsAnyAddressPort(port_data.port())) {
1184 if (!port_data.signaled()) {
1185 maybe_signalable_any_address_ports.push_back(&port_data);
1186 }
1187 } else {
1188 for (const Candidate& c : port_data.port()->Candidates()) {
1189 // If the port of the candidate is |DISCARD_PORT| (9), this is an
1190 // "active" TCP candidate and it doesn't mean we actually bound a
1191 // socket to this address, so ignore it.
1192 if (c.address().port() != DISCARD_PORT) {
1193 ips_from_non_any_address_ports.insert(c.address().ipaddr());
1194 }
1195 }
1196 }
1197 }
1198 // Now signal "any" address ports that have a unique address, and prune any
1199 // that don't.
1200 std::vector<PortData*> signalable_any_address_ports;
1201 std::vector<PortData*> prunable_any_address_ports;
1202 std::vector<Candidate> signalable_candidates_from_any_address_ports;
1203 for (PortData* port_data : maybe_signalable_any_address_ports) {
1204 bool port_signalable = false;
1205 for (const Candidate& c : port_data->port()->Candidates()) {
1206 if (!CandidatePairable(c, port_data->port()) ||
1207 ips_from_non_any_address_ports.count(c.address().ipaddr())) {
1208 continue;
1209 }
1210 // Even when a port is bound to the "any" address, it should normally
1211 // still have an associated IP (determined by calling "connect" and then
1212 // "getsockaddr"). Though sometimes even this fails (meaning |is_any_ip|
1213 // will be true), and thus we have no way of knowing whether the port is
1214 // redundant or not. In that case, we'll use the port if we have
1215 // *no* ports bound to specific addresses. This is needed for corner
1216 // cases such as bugs.webrtc.org/7798.
1217 bool is_any_ip = rtc::IPIsAny(c.address().ipaddr());
1218 if (is_any_ip && !ips_from_non_any_address_ports.empty()) {
1219 continue;
1220 }
1221 port_signalable = true;
1222 // Still need to check the candidiate filter and sanitize the related
1223 // address before signaling the candidate itself.
1224 if (CheckCandidateFilter(c)) {
1225 signalable_candidates_from_any_address_ports.push_back(
1226 SanitizeRelatedAddress(c));
1227 }
1228 }
1229 if (port_signalable) {
1230 signalable_any_address_ports.push_back(port_data);
1231 } else {
1232 prunable_any_address_ports.push_back(port_data);
1233 }
1234 }
1235 PrunePorts(prunable_any_address_ports);
1236 for (PortData* port_data : signalable_any_address_ports) {
1237 RTC_LOG(INFO) << port_data->port()->ToString() << ": Port ready.";
1238 SignalPortReady(this, port_data->port());
1239 port_data->set_signaled();
1240 }
1241 RTC_LOG(INFO) << "Signaling candidates from the any address ports.";
1242 SignalCandidatesReady(this, signalable_candidates_from_any_address_ports);
1243}
1244
1245void BasicPortAllocatorSession::OnPortDestroyed(
1246 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001247 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001248 for (std::vector<PortData>::iterator iter = ports_.begin();
1249 iter != ports_.end(); ++iter) {
1250 if (port == iter->port()) {
1251 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001252 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001253 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001254 return;
1255 }
1256 }
nissec80e7412017-01-11 05:56:46 -08001257 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001258}
1259
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001260BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1261 Port* port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001262 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1263 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001264 if (it->port() == port) {
1265 return &*it;
1266 }
1267 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001268 return nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001269}
1270
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001271std::vector<BasicPortAllocatorSession::PortData*>
1272BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001273 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001274 std::vector<PortData*> unpruned_ports;
1275 for (PortData& port : ports_) {
1276 if (!port.pruned() &&
1277 std::find(networks.begin(), networks.end(),
1278 port.sequence()->network()) != networks.end()) {
1279 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001280 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001281 }
1282 return unpruned_ports;
1283}
1284
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001285std::vector<Candidate> BasicPortAllocatorSession::PrunePorts(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001286 const std::vector<PortData*>& port_data_list) {
1287 std::vector<PortInterface*> pruned_ports;
1288 std::vector<Candidate> removed_candidates;
1289 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001290 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001291 data->Prune();
1292 pruned_ports.push_back(data->port());
1293 if (data->has_pairable_candidate()) {
1294 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001295 // Mark the port as having no pairable candidates so that its candidates
1296 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001297 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001298 }
1299 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001300 if (!pruned_ports.empty()) {
1301 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001302 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001303 return removed_candidates;
1304}
1305
1306void BasicPortAllocatorSession::PrunePortsAndSignalCandidatesRemoval(
1307 const std::vector<PortData*>& port_data_list) {
1308 std::vector<Candidate> removed_candidates = PrunePorts(port_data_list);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001309 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001310 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1311 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001312 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001313 }
1314}
1315
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316// AllocationSequence
1317
1318AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1319 rtc::Network* network,
1320 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001321 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 : session_(session),
1323 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001324 config_(config),
1325 state_(kInit),
1326 flags_(flags),
1327 udp_socket_(),
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001328 udp_port_(nullptr),
Yves Gerey665174f2018-06-19 15:03:05 +02001329 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330
Honghai Zhang5048f572016-08-23 15:47:33 -07001331void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001332 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1333 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001334 rtc::SocketAddress(network_->GetBestIP(), 0),
1335 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001337 udp_socket_->SignalReadPacket.connect(this,
1338 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001339 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001340 // Continuing if |udp_socket_| is null, as local TCP and RelayPort using
1341 // TCP are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001343}
1344
1345void AllocationSequence::Clear() {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001346 udp_port_ = nullptr;
Jonas Oreland202994c2017-12-18 12:10:43 +01001347 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001348}
1349
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001350void AllocationSequence::OnNetworkFailed() {
1351 RTC_DCHECK(!network_failed_);
1352 network_failed_ = true;
1353 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001354 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001355}
1356
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001357AllocationSequence::~AllocationSequence() {
1358 session_->network_thread()->Clear(this);
1359}
1360
1361void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001362 PortConfiguration* config,
1363 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001364 if (network_failed_) {
1365 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001366 // it won't be equivalent to the new network.
1367 return;
1368 }
1369
deadbeef5c3c1042017-08-04 15:01:57 -07001370 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001371 // Different network setup; nothing is equivalent.
1372 return;
1373 }
1374
1375 // Else turn off the stuff that we've already got covered.
1376
deadbeef1c46a352017-09-27 11:24:05 -07001377 // Every config implicitly specifies local, so turn that off right away if we
1378 // already have a port of the corresponding type. Look for a port that
1379 // matches this AllocationSequence's network, is the right protocol, and
1380 // hasn't encountered an error.
1381 // TODO(deadbeef): This doesn't take into account that there may be another
1382 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1383 // This can happen if, say, there's a network change event right before an
1384 // application-triggered ICE restart. Hopefully this problem will just go
1385 // away if we get rid of the gathering "phases" though, which is planned.
1386 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1387 [this](const BasicPortAllocatorSession::PortData& p) {
1388 return p.port()->Network() == network_ &&
1389 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1390 })) {
1391 *flags |= PORTALLOCATOR_DISABLE_UDP;
1392 }
1393 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1394 [this](const BasicPortAllocatorSession::PortData& p) {
1395 return p.port()->Network() == network_ &&
1396 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1397 })) {
1398 *flags |= PORTALLOCATOR_DISABLE_TCP;
1399 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001400
1401 if (config_ && config) {
1402 if (config_->StunServers() == config->StunServers()) {
1403 // Already got this STUN servers covered.
1404 *flags |= PORTALLOCATOR_DISABLE_STUN;
1405 }
1406 if (!config_->relays.empty()) {
1407 // Already got relays covered.
1408 // NOTE: This will even skip a _different_ set of relay servers if we
1409 // were to be given one, but that never happens in our codebase. Should
1410 // probably get rid of the list in PortConfiguration and just keep a
1411 // single relay server in each one.
1412 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1413 }
1414 }
1415}
1416
1417void AllocationSequence::Start() {
1418 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001419 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001420 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1421 // called next time, we enable all phases if the best IP has since changed.
1422 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001423}
1424
1425void AllocationSequence::Stop() {
1426 // If the port is completed, don't set it to stopped.
1427 if (state_ == kRunning) {
1428 state_ = kStopped;
1429 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1430 }
1431}
1432
1433void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001434 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1435 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001436
deadbeef1c5e6d02017-09-15 17:46:56 -07001437 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001438
1439 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001440 RTC_LOG(LS_INFO) << network_->ToString()
1441 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001442
1443 switch (phase_) {
1444 case PHASE_UDP:
1445 CreateUDPPorts();
1446 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001447 break;
1448
1449 case PHASE_RELAY:
1450 CreateRelayPorts();
1451 break;
1452
1453 case PHASE_TCP:
1454 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001455 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001456 break;
1457
1458 default:
nissec80e7412017-01-11 05:56:46 -08001459 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001460 }
1461
1462 if (state() == kRunning) {
1463 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001464 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1465 session_->allocator()->step_delay(),
1466 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001467 } else {
1468 // If all phases in AllocationSequence are completed, no allocation
1469 // steps needed further. Canceling pending signal.
1470 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1471 SignalPortAllocationComplete(this);
1472 }
1473}
1474
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001475void AllocationSequence::CreateUDPPorts() {
1476 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001477 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001478 return;
1479 }
1480
1481 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1482 // is enabled completely.
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001483 UDPPort* port = nullptr;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001484 bool emit_local_candidate_for_anyaddress =
1485 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001486 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001487 port = UDPPort::Create(
1488 session_->network_thread(), session_->socket_factory(), network_,
1489 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001490 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1491 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001493 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001494 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001495 session_->allocator()->min_port(), session_->allocator()->max_port(),
1496 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001497 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1498 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001499 }
1500
1501 if (port) {
1502 // If shared socket is enabled, STUN candidate will be allocated by the
1503 // UDPPort.
1504 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1505 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001506 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001507
1508 // If STUN is not disabled, setting stun server address to port.
1509 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001510 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001511 RTC_LOG(LS_INFO)
1512 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001513 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001514 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001515 }
1516 }
1517 }
1518
1519 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001520 }
1521}
1522
1523void AllocationSequence::CreateTCPPorts() {
1524 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001525 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001526 return;
1527 }
1528
deadbeef5c3c1042017-08-04 15:01:57 -07001529 Port* port = TCPPort::Create(
1530 session_->network_thread(), session_->socket_factory(), network_,
1531 session_->allocator()->min_port(), session_->allocator()->max_port(),
1532 session_->username(), session_->password(),
1533 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001534 if (port) {
1535 session_->AddAllocatedPort(port, this, true);
1536 // Since TCPPort is not created using shared socket, |port| will not be
1537 // added to the dequeue.
1538 }
1539}
1540
1541void AllocationSequence::CreateStunPorts() {
1542 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001543 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001544 return;
1545 }
1546
1547 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1548 return;
1549 }
1550
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001551 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001552 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001553 << "AllocationSequence: No STUN server configured, skipping.";
1554 return;
1555 }
1556
deadbeef5c3c1042017-08-04 15:01:57 -07001557 StunPort* port = StunPort::Create(
1558 session_->network_thread(), session_->socket_factory(), network_,
1559 session_->allocator()->min_port(), session_->allocator()->max_port(),
1560 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001561 session_->allocator()->origin(),
1562 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001563 if (port) {
1564 session_->AddAllocatedPort(port, this, true);
1565 // Since StunPort is not created using shared socket, |port| will not be
1566 // added to the dequeue.
1567 }
1568}
1569
1570void AllocationSequence::CreateRelayPorts() {
1571 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001572 RTC_LOG(LS_VERBOSE)
1573 << "AllocationSequence: Relay ports disabled, skipping.";
1574 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001575 }
1576
1577 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1578 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001579 RTC_DCHECK(config_);
1580 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001581 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001582 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001583 << "AllocationSequence: No relay server configured, skipping.";
1584 return;
1585 }
1586
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001587 for (RelayServerConfig& relay : config_->relays) {
1588 if (relay.type == RELAY_GTURN) {
1589 CreateGturnPort(relay);
1590 } else if (relay.type == RELAY_TURN) {
1591 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001592 } else {
nissec80e7412017-01-11 05:56:46 -08001593 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001594 }
1595 }
1596}
1597
1598void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1599 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001600 RelayPort* port = RelayPort::Create(
1601 session_->network_thread(), session_->socket_factory(), network_,
1602 session_->allocator()->min_port(), session_->allocator()->max_port(),
1603 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001604 if (port) {
1605 // Since RelayPort is not created using shared socket, |port| will not be
1606 // added to the dequeue.
1607 // Note: We must add the allocated port before we add addresses because
1608 // the latter will create candidates that need name and preference
1609 // settings. However, we also can't prepare the address (normally
1610 // done by AddAllocatedPort) until we have these addresses. So we
1611 // wait to do that until below.
1612 session_->AddAllocatedPort(port, this, false);
1613
1614 // Add the addresses of this protocol.
1615 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001616 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001617 ++relay_port) {
1618 port->AddServerAddress(*relay_port);
1619 port->AddExternalAddress(*relay_port);
1620 }
1621 // Start fetching an address for this port.
1622 port->PrepareAddress();
1623 }
1624}
1625
1626void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1627 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001628 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1629 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001630 // Skip UDP connections to relay servers if it's disallowed.
1631 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1632 relay_port->proto == PROTO_UDP) {
1633 continue;
1634 }
1635
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001636 // Do not create a port if the server address family is known and does
1637 // not match the local IP address family.
1638 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001639 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001640 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001641 RTC_LOG(LS_INFO)
1642 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001643 "Server address: "
1644 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001645 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001646 continue;
1647 }
1648
Jonas Oreland202994c2017-12-18 12:10:43 +01001649 CreateRelayPortArgs args;
1650 args.network_thread = session_->network_thread();
1651 args.socket_factory = session_->socket_factory();
1652 args.network = network_;
1653 args.username = session_->username();
1654 args.password = session_->password();
1655 args.server_address = &(*relay_port);
1656 args.config = &config;
1657 args.origin = session_->allocator()->origin();
1658 args.turn_customizer = session_->allocator()->turn_customizer();
1659
1660 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001661 // Shared socket mode must be enabled only for UDP based ports. Hence
1662 // don't pass shared socket for ports which will create TCP sockets.
1663 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1664 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1665 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001666 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001667 port = session_->allocator()->relay_port_factory()->Create(
1668 args, udp_socket_.get());
1669
1670 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001671 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1672 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001673 continue;
1674 }
1675
1676 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001677 // Listen to the port destroyed signal, to allow AllocationSequence to
1678 // remove entrt from it's map.
1679 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1680 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001681 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001682 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001683 session_->allocator()->max_port());
1684
1685 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001686 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1687 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001688 continue;
1689 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001690 }
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001691 RTC_DCHECK(port != nullptr);
Jonas Oreland202994c2017-12-18 12:10:43 +01001692 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001693 }
1694}
1695
Yves Gerey665174f2018-06-19 15:03:05 +02001696void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1697 const char* data,
1698 size_t size,
1699 const rtc::SocketAddress& remote_addr,
1700 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001701 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001702
1703 bool turn_port_found = false;
1704
1705 // Try to find the TurnPort that matches the remote address. Note that the
1706 // message could be a STUN binding response if the TURN server is also used as
1707 // a STUN server. We don't want to parse every message here to check if it is
1708 // a STUN binding response, so we pass the message to TurnPort regardless of
1709 // the message type. The TurnPort will just ignore the message since it will
1710 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001711 for (auto* port : relay_ports_) {
1712 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001713 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1714 packet_time)) {
1715 return;
1716 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001717 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001718 }
1719 }
1720
1721 if (udp_port_) {
1722 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1723
1724 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1725 // the TURN server is also a STUN server.
1726 if (!turn_port_found ||
1727 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001728 RTC_DCHECK(udp_port_->SharedSocket());
1729 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1730 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001731 }
1732 }
1733}
1734
1735void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1736 if (udp_port_ == port) {
Mirko Bonadeiac5bbd92018-06-22 12:06:07 +00001737 udp_port_ = nullptr;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001738 return;
1739 }
1740
Jonas Oreland202994c2017-12-18 12:10:43 +01001741 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1742 if (it != relay_ports_.end()) {
1743 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001744 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001745 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001746 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001747 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001748}
1749
1750// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001751PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1752 const std::string& username,
1753 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001754 : stun_address(stun_address), username(username), password(password) {
1755 if (!stun_address.IsNil())
1756 stun_servers.insert(stun_address);
1757}
1758
1759PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1760 const std::string& username,
1761 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001762 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001763 if (!stun_servers.empty())
1764 stun_address = *(stun_servers.begin());
1765}
1766
Steve Anton7995d8c2017-10-30 16:23:38 -07001767PortConfiguration::~PortConfiguration() = default;
1768
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001769ServerAddresses PortConfiguration::StunServers() {
1770 if (!stun_address.IsNil() &&
1771 stun_servers.find(stun_address) == stun_servers.end()) {
1772 stun_servers.insert(stun_address);
1773 }
deadbeefc5d0d952015-07-16 10:22:21 -07001774 // Every UDP TURN server should also be used as a STUN server.
1775 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1776 for (const rtc::SocketAddress& turn_server : turn_servers) {
1777 if (stun_servers.find(turn_server) == stun_servers.end()) {
1778 stun_servers.insert(turn_server);
1779 }
1780 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001781 return stun_servers;
1782}
1783
1784void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1785 relays.push_back(config);
1786}
1787
Yves Gerey665174f2018-06-19 15:03:05 +02001788bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1789 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001790 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001791 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1792 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001793 if (relay_port->proto == type)
1794 return true;
1795 }
1796 return false;
1797}
1798
1799bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1800 ProtocolType type) const {
1801 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001802 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001803 return true;
1804 }
1805 return false;
1806}
1807
1808ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001809 RelayType turn_type,
1810 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001811 ServerAddresses servers;
1812 for (size_t i = 0; i < relays.size(); ++i) {
1813 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1814 servers.insert(relays[i].ports.front().address);
1815 }
1816 }
1817 return servers;
1818}
1819
1820} // namespace cricket