blob: b1f147dcdcc637c0aea0c4268868914f8f9b8f2d [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "p2p/client/basic_port_allocator.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
Steve Antonae226f62019-01-29 12:47:38 -080019#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080020#include "p2p/base/basic_packet_socket_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "p2p/base/port.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "p2p/base/relay_port.h"
23#include "p2p/base/stun_port.h"
24#include "p2p/base/tcp_port.h"
25#include "p2p/base/turn_port.h"
26#include "p2p/base/udp_port.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/checks.h"
28#include "rtc_base/helpers.h"
29#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
Qingsi Wangc129c352019-04-18 10:41:58 -070034namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000035namespace {
36
37enum {
38 MSG_CONFIG_START,
39 MSG_CONFIG_READY,
40 MSG_ALLOCATE,
41 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000042 MSG_SEQUENCEOBJECTS_CREATED,
43 MSG_CONFIG_STOP,
44};
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
Qingsi Wangc129c352019-04-18 10:41:58 -0700116bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) {
117 // When binding to any address, before sending packets out, the getsockname
118 // returns all 0s, but after sending packets, it'll be the NIC used to
119 // send. All 0s is not a valid ICE candidate address and should be filtered
120 // out.
121 if (c.address().IsAnyIP()) {
122 return false;
123 }
124
125 if (c.type() == RELAY_PORT_TYPE) {
126 return ((filter & CF_RELAY) != 0);
127 } else if (c.type() == STUN_PORT_TYPE) {
128 return ((filter & CF_REFLEXIVE) != 0);
129 } else if (c.type() == LOCAL_PORT_TYPE) {
130 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
131 // We allow host candidates if the filter allows server-reflexive
132 // candidates and the candidate is a public IP. Because we don't generate
133 // server-reflexive candidates if they have the same IP as the host
134 // candidate (i.e. when the host candidate is a public IP), filtering to
135 // only server-reflexive candidates won't work right when the host
136 // candidates have public IPs.
137 return true;
138 }
139
140 return ((filter & CF_HOST) != 0);
141 }
142 return false;
143}
144
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145} // namespace
146
Peter Boström0c4e06b2015-10-07 12:23:21 +0200147const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700148 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
149 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150
151// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200152BasicPortAllocator::BasicPortAllocator(
153 rtc::NetworkManager* network_manager,
154 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100155 webrtc::TurnCustomizer* customizer,
156 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700157 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100158 InitRelayPortFactory(relay_port_factory);
159 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800160 RTC_DCHECK(network_manager_ != nullptr);
161 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200162 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
163 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 Construct();
165}
166
Yves Gerey665174f2018-06-19 15:03:05 +0200167BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700168 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100169 InitRelayPortFactory(nullptr);
170 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800171 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172 Construct();
173}
174
Yves Gerey665174f2018-06-19 15:03:05 +0200175BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
176 rtc::PacketSocketFactory* socket_factory,
177 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700178 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100179 InitRelayPortFactory(nullptr);
180 RTC_DCHECK(relay_port_factory_ != nullptr);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000181 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200182 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
183 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 Construct();
185}
186
187BasicPortAllocator::BasicPortAllocator(
188 rtc::NetworkManager* network_manager,
189 const ServerAddresses& stun_servers,
190 const rtc::SocketAddress& relay_address_udp,
191 const rtc::SocketAddress& relay_address_tcp,
192 const rtc::SocketAddress& relay_address_ssl)
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000193 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100194 InitRelayPortFactory(nullptr);
195 RTC_DCHECK(relay_port_factory_ != nullptr);
196 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700197 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800199 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800201 }
202 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800204 }
205 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800207 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000208
deadbeef653b8e02015-11-11 12:55:10 -0800209 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700210 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800211 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212
Jonas Orelandbdcee282017-10-10 14:01:40 +0200213 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214 Construct();
215}
216
217void BasicPortAllocator::Construct() {
218 allow_tcp_listen_ = true;
219}
220
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700221void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
222 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700223 // If the session has not been taken by an active channel, do not report the
224 // metric.
225 for (auto& allocator_session : pooled_sessions()) {
226 if (allocator_session.get() == session) {
227 return;
228 }
229 }
230
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700231 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
232 static_cast<int>(reason),
233 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700234}
235
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700237 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800238 // Our created port allocator sessions depend on us, so destroy our remaining
239 // pooled sessions before anything else.
240 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241}
242
Steve Anton7995d8c2017-10-30 16:23:38 -0700243void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
244 // TODO(phoglund): implement support for other types than loopback.
245 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
246 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700247 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700248 network_ignore_mask_ = network_ignore_mask;
249}
250
deadbeefc5d0d952015-07-16 10:22:21 -0700251PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200252 const std::string& content_name,
253 int component,
254 const std::string& ice_ufrag,
255 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700256 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700257 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700259 session->SignalIceRegathering.connect(this,
260 &BasicPortAllocator::OnIceRegathering);
261 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262}
263
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700264void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700265 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700266 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
267 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700268 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200269 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700270}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271
Jonas Oreland202994c2017-12-18 12:10:43 +0100272void BasicPortAllocator::InitRelayPortFactory(
273 RelayPortFactoryInterface* relay_port_factory) {
274 if (relay_port_factory != nullptr) {
275 relay_port_factory_ = relay_port_factory;
276 } else {
277 default_relay_port_factory_.reset(new TurnPortFactory());
278 relay_port_factory_ = default_relay_port_factory_.get();
279 }
280}
281
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282// BasicPortAllocatorSession
283BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700284 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 const std::string& content_name,
286 int component,
287 const std::string& ice_ufrag,
288 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700289 : PortAllocatorSession(content_name,
290 component,
291 ice_ufrag,
292 ice_pwd,
293 allocator->flags()),
294 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700295 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 socket_factory_(allocator->socket_factory()),
297 allocation_started_(false),
298 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700299 allocation_sequences_created_(false),
300 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000301 allocator_->network_manager()->SignalNetworksChanged.connect(
302 this, &BasicPortAllocatorSession::OnNetworksChanged);
303 allocator_->network_manager()->StartUpdating();
304}
305
306BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700307 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000308 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000309 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310 network_thread_->Clear(this);
311
Peter Boström0c4e06b2015-10-07 12:23:21 +0200312 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313 // AllocationSequence should clear it's map entry for turn ports before
314 // ports are destroyed.
315 sequences_[i]->Clear();
316 }
317
318 std::vector<PortData>::iterator it;
319 for (it = ports_.begin(); it != ports_.end(); it++)
320 delete it->port();
321
Peter Boström0c4e06b2015-10-07 12:23:21 +0200322 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000323 delete configs_[i];
324
Peter Boström0c4e06b2015-10-07 12:23:21 +0200325 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 delete sequences_[i];
327}
328
Steve Anton7995d8c2017-10-30 16:23:38 -0700329BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700330 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700331 return allocator_;
332}
333
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700334void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700335 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700336 if (filter == candidate_filter_) {
337 return;
338 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700339 uint32_t prev_filter = candidate_filter_;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700340 candidate_filter_ = filter;
Qingsi Wangc129c352019-04-18 10:41:58 -0700341 for (PortData& port_data : ports_) {
342 if (port_data.error() || port_data.pruned()) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700343 continue;
344 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700345 PortData::State cur_state = port_data.state();
346 bool found_signalable_candidate = false;
347 bool found_pairable_candidate = false;
348 cricket::Port* port = port_data.port();
349 for (const auto& c : port->Candidates()) {
350 if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) &&
351 IsAllowedByCandidateFilter(c, filter)) {
352 // This candidate was not signaled because of not matching the previous
353 // filter (see OnCandidateReady below). Let the Port to fire the signal
354 // again.
355 //
356 // Note that
357 // 1) we would need the Port to enter the state of in-progress of
358 // gathering to have candidates signaled;
359 //
360 // 2) firing the signal would also let the session set the port ready
361 // if needed, so that we could form candidate pairs with candidates
362 // from this port;
363 //
364 // * See again OnCandidateReady below for 1) and 2).
365 //
366 // 3) we only try to resurface candidates if we have not stopped
367 // getting ports, which is always true for the continual gathering.
368 if (!found_signalable_candidate) {
369 found_signalable_candidate = true;
370 port_data.set_state(PortData::STATE_INPROGRESS);
371 }
372 port->SignalCandidateReady(port, c);
373 }
374
375 if (CandidatePairable(c, port)) {
376 found_pairable_candidate = true;
377 }
378 }
379 // Restore the previous state.
380 port_data.set_state(cur_state);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700381 // Setting a filter may cause a ready port to become non-ready
382 // if it no longer has any pairable candidates.
Qingsi Wangc129c352019-04-18 10:41:58 -0700383 //
384 // Note that we only set for the negative case here, since a port would be
385 // set to have pairable candidates when it signals a ready candidate, which
386 // requires the port is still in the progress of gathering/surfacing
387 // candidates, and would be done in the firing of the signal above.
388 if (!found_pairable_candidate) {
389 port_data.set_has_pairable_candidate(false);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700390 }
391 }
392}
393
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700395 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700396 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000397 if (!socket_factory_) {
398 owned_socket_factory_.reset(
399 new rtc::BasicPacketSocketFactory(network_thread_));
400 socket_factory_ = owned_socket_factory_.get();
401 }
402
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700403 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700404
Mirko Bonadei675513b2017-11-09 11:09:25 +0100405 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
406 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407}
408
409void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700410 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700411 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700412 // Note: this must be called after ClearGettingPorts because both may set the
413 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700414 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700415}
416
417void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700418 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000419 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700420 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000421 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700422 }
deadbeefb60a8192016-08-24 15:15:00 -0700423 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700424 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700425}
426
Steve Anton7995d8c2017-10-30 16:23:38 -0700427bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700428 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700429 return state_ == SessionState::GATHERING;
430}
431
432bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700433 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700434 return state_ == SessionState::CLEARED;
435}
436
437bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700438 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700439 return state_ == SessionState::STOPPED;
440}
441
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700442std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700443 RTC_DCHECK_RUN_ON(network_thread_);
444
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700445 std::vector<rtc::Network*> networks = GetNetworks();
446
447 // A network interface may have both IPv4 and IPv6 networks. Only if
448 // neither of the networks has any connections, the network interface
449 // is considered failed and need to be regathered on.
450 std::set<std::string> networks_with_connection;
451 for (const PortData& data : ports_) {
452 Port* port = data.port();
453 if (!port->connections().empty()) {
454 networks_with_connection.insert(port->Network()->name());
455 }
456 }
457
458 networks.erase(
459 std::remove_if(networks.begin(), networks.end(),
460 [networks_with_connection](rtc::Network* network) {
461 // If a network does not have any connection, it is
462 // considered failed.
463 return networks_with_connection.find(network->name()) !=
464 networks_with_connection.end();
465 }),
466 networks.end());
467 return networks;
468}
469
470void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700471 RTC_DCHECK_RUN_ON(network_thread_);
472
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700473 // Find the list of networks that have no connection.
474 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
475 if (failed_networks.empty()) {
476 return;
477 }
478
Mirko Bonadei675513b2017-11-09 11:09:25 +0100479 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700480
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700481 // Mark a sequence as "network failed" if its network is in the list of failed
482 // networks, so that it won't be considered as equivalent when the session
483 // regathers ports and candidates.
484 for (AllocationSequence* sequence : sequences_) {
485 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800486 absl::c_linear_search(failed_networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700487 sequence->set_network_failed();
488 }
489 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700490
491 bool disable_equivalent_phases = true;
492 Regather(failed_networks, disable_equivalent_phases,
493 IceRegatheringReason::NETWORK_FAILURE);
494}
495
496void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700497 RTC_DCHECK_RUN_ON(network_thread_);
498
Steve Anton300bf8e2017-07-14 10:13:10 -0700499 std::vector<rtc::Network*> networks = GetNetworks();
500 if (networks.empty()) {
501 return;
502 }
503
Mirko Bonadei675513b2017-11-09 11:09:25 +0100504 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700505
506 // We expect to generate candidates that are equivalent to what we have now.
507 // Force DoAllocate to generate them instead of skipping.
508 bool disable_equivalent_phases = false;
509 Regather(networks, disable_equivalent_phases,
510 IceRegatheringReason::OCCASIONAL_REFRESH);
511}
512
513void BasicPortAllocatorSession::Regather(
514 const std::vector<rtc::Network*>& networks,
515 bool disable_equivalent_phases,
516 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700517 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700518 // Remove ports from being used locally and send signaling to remove
519 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700520 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700521 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100522 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000523 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700524 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700525
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700526 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700527 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700528
Steve Anton300bf8e2017-07-14 10:13:10 -0700529 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700530 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000531}
532
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800533void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200534 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700535 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800536 auto ports = ReadyPorts();
537 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800538 // The port type and protocol can be used to identify different subclasses
539 // of Port in the current implementation. Note that a TCPPort has the type
540 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
541 if (port->Type() == STUN_PORT_TYPE ||
542 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800543 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
544 stun_keepalive_interval);
545 }
546 }
547}
548
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700549std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700550 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700551 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700552 for (const PortData& data : ports_) {
553 if (data.ready()) {
554 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700555 }
556 }
557 return ret;
558}
559
560std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700561 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700562 std::vector<Candidate> candidates;
563 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700564 if (!data.ready()) {
565 continue;
566 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700567 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700568 }
569 return candidates;
570}
571
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700572void BasicPortAllocatorSession::GetCandidatesFromPort(
573 const PortData& data,
574 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700575 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700576 RTC_CHECK(candidates != nullptr);
577 for (const Candidate& candidate : data.port()->Candidates()) {
578 if (!CheckCandidateFilter(candidate)) {
579 continue;
580 }
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700581 auto sanitized_candidate = SanitizeCandidate(candidate);
582 candidates->push_back(sanitized_candidate);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700583 }
584}
585
Jeroen de Borst72d2ddd2018-11-27 13:20:39 -0800586bool BasicPortAllocatorSession::MdnsObfuscationEnabled() const {
587 return allocator_->network_manager()->GetMdnsResponder() != nullptr;
588}
589
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700590Candidate BasicPortAllocatorSession::SanitizeCandidate(
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700591 const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -0700592 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700593 // If the candidate has a generated hostname, we need to obfuscate its IP
594 // address when signaling this candidate.
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800595 bool use_hostname_address =
596 !c.address().hostname().empty() && !c.address().IsUnresolvedIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700597 // If adapter enumeration is disabled or host candidates are disabled,
598 // clear the raddr of STUN candidates to avoid local address leakage.
599 bool filter_stun_related_address =
600 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
601 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
Jeroen de Borst72d2ddd2018-11-27 13:20:39 -0800602 !(candidate_filter_ & CF_HOST) || MdnsObfuscationEnabled();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700603 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
604 // to avoid reflexive address leakage.
605 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800606 bool filter_related_address =
607 ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
608 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address));
609 return c.ToSanitizedCopy(use_hostname_address, filter_related_address);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700610}
611
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700612bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700613 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700614 // Done only if all required AllocationSequence objects
615 // are created.
616 if (!allocation_sequences_created_) {
617 return false;
618 }
619
620 // Check that all port allocation sequences are complete (not running).
Steve Antonae226f62019-01-29 12:47:38 -0800621 if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
622 return sequence->state() == AllocationSequence::kRunning;
623 })) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700624 return false;
625 }
626
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700627 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700628 // expected candidates. Session will trigger candidates allocation complete
629 // signal.
Steve Antonae226f62019-01-29 12:47:38 -0800630 return absl::c_none_of(
631 ports_, [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700632}
633
Yves Gerey665174f2018-06-19 15:03:05 +0200634void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200636 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200637 GetPortConfigurations();
638 break;
639 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200640 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
641 break;
642 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200643 OnAllocate();
644 break;
645 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200646 OnAllocationSequenceObjectsCreated();
647 break;
648 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200649 OnConfigStop();
650 break;
651 default:
652 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653 }
654}
655
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700656void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700657 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700658 for (PortData& port : ports_) {
659 port.port()->set_content_name(content_name());
660 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
661 }
662}
663
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700665 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangc129c352019-04-18 10:41:58 -0700666
Yves Gerey665174f2018-06-19 15:03:05 +0200667 PortConfiguration* config =
668 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000669
deadbeef653b8e02015-11-11 12:55:10 -0800670 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
671 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000672 }
673 ConfigReady(config);
674}
675
676void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700677 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700678 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000679}
680
681// Adds a configuration to the list.
682void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700683 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800684 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800686 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000687
688 AllocatePorts();
689}
690
691void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700692 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000693
694 // If any of the allocated ports have not completed the candidates allocation,
695 // mark those as error. Since session doesn't need any new candidates
696 // at this stage of the allocation, it's safe to discard any new candidates.
697 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200698 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
699 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700700 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000701 // Updating port state to error, which didn't finish allocating candidates
702 // yet.
Qingsi Wangc129c352019-04-18 10:41:58 -0700703 it->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704 send_signal = true;
705 }
706 }
707
708 // Did we stop any running sequences?
709 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
710 it != sequences_.end() && !send_signal; ++it) {
711 if ((*it)->state() == AllocationSequence::kStopped) {
712 send_signal = true;
713 }
714 }
715
716 // If we stopped anything that was running, send a done signal now.
717 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000718 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719 }
720}
721
722void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700723 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700724 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000725}
726
727void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700728 RTC_DCHECK_RUN_ON(network_thread_);
729
Steve Anton300bf8e2017-07-14 10:13:10 -0700730 if (network_manager_started_ && !IsStopped()) {
731 bool disable_equivalent_phases = true;
732 DoAllocate(disable_equivalent_phases);
733 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734
735 allocation_started_ = true;
736}
737
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700738std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700739 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700740 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700741 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800742 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700743 // If the network permission state is BLOCKED, we just act as if the flag has
744 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700745 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700746 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700747 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
748 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000749 // If the adapter enumeration is disabled, we'll just bind to any address
750 // instead of specific NIC. This is to ensure the same routing for http
751 // traffic by OS is also used here to avoid any local or public IP leakage
752 // during stun process.
753 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
754 network_manager->GetAnyAddressNetworks(&networks);
755 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700756 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000757 // If network enumeration fails, use the ANY address as a fallback, so we
758 // can at least try gathering candidates using the default route chosen by
759 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
760 // set, we'll use ANY address candidates either way.
761 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
762 network_manager->GetAnyAddressNetworks(&networks);
763 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000764 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100765 // Filter out link-local networks if needed.
766 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700767 NetworkFilter link_local_filter(
768 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
769 "link-local");
770 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100771 }
deadbeef3427f532017-07-26 16:09:33 -0700772 // Do some more filtering, depending on the network ignore mask and "disable
773 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700774 NetworkFilter ignored_filter(
775 [this](rtc::Network* network) {
776 return allocator_->network_ignore_mask() & network->type();
777 },
778 "ignored");
779 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700780 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
781 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700782 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000783 // Don't determine the lowest cost from a link-local network.
784 // On iOS, a device connected to the computer will get a link-local
785 // network for communicating with the computer, however this network can't
786 // be used to connect to a peer outside the network.
787 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800788 continue;
789 }
honghaiz60347052016-05-31 18:29:12 -0700790 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
791 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700792 NetworkFilter costly_filter(
793 [lowest_cost](rtc::Network* network) {
794 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
795 },
796 "costly");
797 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700798 }
deadbeef3427f532017-07-26 16:09:33 -0700799 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
800 // default, it's 5), remove networks to ensure that limit is satisfied.
801 //
802 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
803 // networks, we could try to choose a set that's "most likely to work". It's
804 // hard to define what that means though; it's not just "lowest cost".
805 // Alternatively, we could just focus on making our ICE pinging logic smarter
806 // such that this filtering isn't necessary in the first place.
807 int ipv6_networks = 0;
808 for (auto it = networks.begin(); it != networks.end();) {
809 if ((*it)->prefix().family() == AF_INET6) {
810 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
811 it = networks.erase(it);
812 continue;
813 } else {
814 ++ipv6_networks;
815 }
816 }
817 ++it;
818 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700819 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700820}
821
822// For each network, see if we have a sequence that covers it already. If not,
823// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700824void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700825 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700826 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700827 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100829 RTC_LOG(LS_WARNING)
830 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831 done_signal_needed = true;
832 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100833 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700834 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200835 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200836 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
838 // If all the ports are disabled we should just fire the allocation
839 // done event and return.
840 done_signal_needed = true;
841 break;
842 }
843
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844 if (!config || config->relays.empty()) {
845 // No relay ports specified in this config.
846 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
847 }
848
849 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 // Skip IPv6 networks unless the flag's been set.
852 continue;
853 }
854
zhihuangb09b3f92017-03-07 14:40:51 -0800855 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
856 networks[i]->GetBestIP().family() == AF_INET6 &&
857 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
858 // Skip IPv6 Wi-Fi networks unless the flag's been set.
859 continue;
860 }
861
Steve Anton300bf8e2017-07-14 10:13:10 -0700862 if (disable_equivalent) {
863 // Disable phases that would only create ports equivalent to
864 // ones that we have already made.
865 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866
Steve Anton300bf8e2017-07-14 10:13:10 -0700867 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
868 // New AllocationSequence would have nothing to do, so don't make it.
869 continue;
870 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000871 }
872
873 AllocationSequence* sequence =
874 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000875 sequence->SignalPortAllocationComplete.connect(
876 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700877 sequence->Init();
878 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700880 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 }
882 }
883 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700884 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 }
886}
887
888void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700889 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700890 std::vector<rtc::Network*> networks = GetNetworks();
891 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700892 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700893 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700894 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700895 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800896 !absl::c_linear_search(networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700897 sequence->OnNetworkFailed();
898 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700899 }
900 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700901 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
902 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100903 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
904 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000905 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700906 }
honghaiz8c404fa2015-09-28 07:59:43 -0700907
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700908 if (allocation_started_ && !IsStopped()) {
909 if (network_manager_started_) {
910 // If the network manager has started, it must be regathering.
911 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
912 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700913 bool disable_equivalent_phases = true;
914 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700915 }
916
Honghai Zhang5048f572016-08-23 15:47:33 -0700917 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100918 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700919 network_manager_started_ = true;
920 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000921}
922
923void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200924 rtc::Network* network,
925 PortConfiguration* config,
926 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700927 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200928 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200929 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200930 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000931 sequences_[i]->DisableEquivalentPhases(network, config, flags);
932 }
933}
934
935void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200936 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700938 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939 if (!port)
940 return;
941
Mirko Bonadei675513b2017-11-09 11:09:25 +0100942 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700944 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000945 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700946 if (allocator_->proxy().type != rtc::PROXY_NONE)
947 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700948 port->set_send_retransmit_count_attribute(
949 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000950
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000951 PortData data(port, seq);
952 ports_.push_back(data);
953
954 port->SignalCandidateReady.connect(
955 this, &BasicPortAllocatorSession::OnCandidateReady);
Eldar Relloda13ea22019-06-01 12:23:43 +0300956 port->SignalCandidateError.connect(
957 this, &BasicPortAllocatorSession::OnCandidateError);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000958 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200959 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000960 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200961 &BasicPortAllocatorSession::OnPortDestroyed);
962 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
963 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000964
965 if (prepare_address)
966 port->PrepareAddress();
967}
968
969void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700970 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971 allocation_sequences_created_ = true;
972 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000973 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000974}
975
Yves Gerey665174f2018-06-19 15:03:05 +0200976void BasicPortAllocatorSession::OnCandidateReady(Port* port,
977 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700978 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000980 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200981 RTC_LOG(LS_INFO) << port->ToString()
982 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000983 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700984 // already done with gathering.
985 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100986 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700987 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700988 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700989 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700990
danilchapf4e8cf02016-06-30 01:55:03 -0700991 // Mark that the port has a pairable candidate, either because we have a
992 // usable candidate from the port, or simply because the port is bound to the
993 // any address and therefore has no host candidate. This will trigger the port
994 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700995 // checks. If port has already been marked as having a pairable candidate,
996 // do nothing here.
997 // Note: We should check whether any candidates may become ready after this
998 // because there we will check whether the candidate is generated by the ready
999 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001000 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001001 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -07001002 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001003
1004 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001005 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001006 }
1007 // If the current port is not pruned yet, SignalPortReady.
1008 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001009 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
1010 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001011 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001012 }
Honghai Zhang17aac052016-06-29 21:41:53 -07001013 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001014
deadbeef1c5e6d02017-09-15 17:46:56 -07001015 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001016 std::vector<Candidate> candidates;
Qingsi Wangb49b8f12018-09-16 17:48:10 -07001017 candidates.push_back(SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001018 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -07001019 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001020 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001021 }
1022
1023 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001024 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001025 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001026 }
1027}
1028
Eldar Relloda13ea22019-06-01 12:23:43 +03001029void BasicPortAllocatorSession::OnCandidateError(
1030 Port* port,
1031 const IceCandidateErrorEvent& event) {
1032 RTC_DCHECK_RUN_ON(network_thread_);
1033 RTC_DCHECK(FindPort(port));
1034
1035 SignalCandidateError(this, event);
1036}
1037
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001038Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
1039 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -07001040 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001041 Port* best_turn_port = nullptr;
1042 for (const PortData& data : ports_) {
1043 if (data.port()->Network()->name() == network_name &&
1044 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1045 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
1046 best_turn_port = data.port();
1047 }
1048 }
1049 return best_turn_port;
1050}
1051
1052bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -07001053 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001054 // Note: We determine the same network based only on their network names. So
1055 // if an IPv4 address and an IPv6 address have the same network name, they
1056 // are considered the same network here.
1057 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1058 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1059 // |port| is already in the list of ports, so the best port cannot be nullptr.
1060 RTC_CHECK(best_turn_port != nullptr);
1061
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001062 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001063 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001064 for (PortData& data : ports_) {
1065 if (data.port()->Network()->name() == network_name &&
1066 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1067 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001068 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001069 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001070 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001071 ports_to_prune.push_back(&data);
1072 } else {
1073 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001074 }
1075 }
1076 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001077
1078 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001079 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1080 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001081 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001082 }
1083 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001084}
1085
Honghai Zhanga74363c2016-07-28 18:06:15 -07001086void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001087 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001088 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001089 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001090 }
1091}
1092
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001094 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001095 RTC_LOG(LS_INFO) << port->ToString()
1096 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001098 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001099
1100 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001101 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001102 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001103 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001104
1105 // Moving to COMPLETE state.
Qingsi Wangc129c352019-04-18 10:41:58 -07001106 data->set_state(PortData::STATE_COMPLETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001107 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001108 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109}
1110
1111void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001112 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001113 RTC_LOG(LS_INFO) << port->ToString()
1114 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001115 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001116 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001117 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001118 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001119 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001120 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121
1122 // SignalAddressError is currently sent from StunPort/TurnPort.
1123 // But this signal itself is generic.
Qingsi Wangc129c352019-04-18 10:41:58 -07001124 data->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001126 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001127}
1128
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001129bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001130 RTC_DCHECK_RUN_ON(network_thread_);
1131
Qingsi Wangc129c352019-04-18 10:41:58 -07001132 return IsAllowedByCandidateFilter(c, candidate_filter_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133}
1134
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001135bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1136 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001137 RTC_DCHECK_RUN_ON(network_thread_);
1138
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001139 bool candidate_signalable = CheckCandidateFilter(c);
1140
1141 // When device enumeration is disabled (to prevent non-default IP addresses
1142 // from leaking), we ping from some local candidates even though we don't
1143 // signal them. However, if host candidates are also disabled (for example, to
1144 // prevent even default IP addresses from leaking), we still don't want to
1145 // ping from them, even if device enumeration is disabled. Thus, we check for
1146 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001147 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001148 bool can_ping_from_candidate =
1149 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1150 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1151
1152 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001153 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001154 !host_candidates_disabled);
1155}
1156
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001157void BasicPortAllocatorSession::OnPortAllocationComplete(
1158 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001159 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001160 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001161 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001162}
1163
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001164void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001165 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001166 if (CandidatesAllocationDone()) {
1167 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001168 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001169 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001170 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1171 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001172 }
1173 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001174 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001175}
1176
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001177void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001178 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001179 for (std::vector<PortData>::iterator iter = ports_.begin();
1180 iter != ports_.end(); ++iter) {
1181 if (port == iter->port()) {
1182 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001183 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001184 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001185 return;
1186 }
1187 }
nissec80e7412017-01-11 05:56:46 -08001188 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001189}
1190
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1192 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001193 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001194 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1195 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001196 if (it->port() == port) {
1197 return &*it;
1198 }
1199 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001200 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001201}
1202
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001203std::vector<BasicPortAllocatorSession::PortData*>
1204BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001205 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001206 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001207 std::vector<PortData*> unpruned_ports;
1208 for (PortData& port : ports_) {
1209 if (!port.pruned() &&
Steve Antonae226f62019-01-29 12:47:38 -08001210 absl::c_linear_search(networks, port.sequence()->network())) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001211 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001212 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001213 }
1214 return unpruned_ports;
1215}
1216
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001217void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001218 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001219 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001220 std::vector<PortInterface*> pruned_ports;
1221 std::vector<Candidate> removed_candidates;
1222 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001223 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001224 data->Prune();
1225 pruned_ports.push_back(data->port());
1226 if (data->has_pairable_candidate()) {
1227 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001228 // Mark the port as having no pairable candidates so that its candidates
1229 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001230 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001231 }
1232 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001233 if (!pruned_ports.empty()) {
1234 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001235 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001236 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001237 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1238 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001239 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001240 }
1241}
1242
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243// AllocationSequence
1244
1245AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1246 rtc::Network* network,
1247 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001248 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001249 : session_(session),
1250 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001251 config_(config),
1252 state_(kInit),
1253 flags_(flags),
1254 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001255 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001256 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001257
Honghai Zhang5048f572016-08-23 15:47:33 -07001258void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1260 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001261 rtc::SocketAddress(network_->GetBestIP(), 0),
1262 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001263 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001264 udp_socket_->SignalReadPacket.connect(this,
1265 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001267 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1268 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001269 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270}
1271
1272void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001273 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001274 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001275}
1276
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001277void AllocationSequence::OnNetworkFailed() {
1278 RTC_DCHECK(!network_failed_);
1279 network_failed_ = true;
1280 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001281 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001282}
1283
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001284AllocationSequence::~AllocationSequence() {
1285 session_->network_thread()->Clear(this);
1286}
1287
1288void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001289 PortConfiguration* config,
1290 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001291 if (network_failed_) {
1292 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001293 // it won't be equivalent to the new network.
1294 return;
1295 }
1296
deadbeef5c3c1042017-08-04 15:01:57 -07001297 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001298 // Different network setup; nothing is equivalent.
1299 return;
1300 }
1301
1302 // Else turn off the stuff that we've already got covered.
1303
deadbeef1c46a352017-09-27 11:24:05 -07001304 // Every config implicitly specifies local, so turn that off right away if we
1305 // already have a port of the corresponding type. Look for a port that
1306 // matches this AllocationSequence's network, is the right protocol, and
1307 // hasn't encountered an error.
1308 // TODO(deadbeef): This doesn't take into account that there may be another
1309 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1310 // This can happen if, say, there's a network change event right before an
1311 // application-triggered ICE restart. Hopefully this problem will just go
1312 // away if we get rid of the gathering "phases" though, which is planned.
Qingsi Wangc129c352019-04-18 10:41:58 -07001313 //
1314 //
1315 // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1316 // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1317 // to disable the gathering of these candidates just becaue of an existing
1318 // Port over PROTO_UDP, namely a TurnPort over UDP.
Steve Antonae226f62019-01-29 12:47:38 -08001319 if (absl::c_any_of(session_->ports_,
1320 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001321 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001322 p.port()->GetProtocol() == PROTO_UDP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001323 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001324 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001325 *flags |= PORTALLOCATOR_DISABLE_UDP;
1326 }
Qingsi Wangc129c352019-04-18 10:41:58 -07001327 // Similarly we need to check both the protocol used by an existing Port and
1328 // its type.
Steve Antonae226f62019-01-29 12:47:38 -08001329 if (absl::c_any_of(session_->ports_,
1330 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001331 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001332 p.port()->GetProtocol() == PROTO_TCP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001333 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001334 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001335 *flags |= PORTALLOCATOR_DISABLE_TCP;
1336 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001337
1338 if (config_ && config) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001339 // We need to regather srflx candidates if either of the following
1340 // conditions occurs:
1341 // 1. The STUN servers are different from the previous gathering.
1342 // 2. We will regather host candidates, hence possibly inducing new NAT
1343 // bindings.
1344 if (config_->StunServers() == config->StunServers() &&
1345 (*flags & PORTALLOCATOR_DISABLE_UDP)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346 // Already got this STUN servers covered.
1347 *flags |= PORTALLOCATOR_DISABLE_STUN;
1348 }
1349 if (!config_->relays.empty()) {
1350 // Already got relays covered.
1351 // NOTE: This will even skip a _different_ set of relay servers if we
1352 // were to be given one, but that never happens in our codebase. Should
1353 // probably get rid of the list in PortConfiguration and just keep a
1354 // single relay server in each one.
1355 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1356 }
1357 }
1358}
1359
1360void AllocationSequence::Start() {
1361 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001362 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001363 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1364 // called next time, we enable all phases if the best IP has since changed.
1365 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001366}
1367
1368void AllocationSequence::Stop() {
1369 // If the port is completed, don't set it to stopped.
1370 if (state_ == kRunning) {
1371 state_ = kStopped;
1372 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1373 }
1374}
1375
1376void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001377 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1378 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379
deadbeef1c5e6d02017-09-15 17:46:56 -07001380 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001381
1382 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001383 RTC_LOG(LS_INFO) << network_->ToString()
1384 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385
1386 switch (phase_) {
1387 case PHASE_UDP:
1388 CreateUDPPorts();
1389 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 break;
1391
1392 case PHASE_RELAY:
1393 CreateRelayPorts();
1394 break;
1395
1396 case PHASE_TCP:
1397 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001398 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001399 break;
1400
1401 default:
nissec80e7412017-01-11 05:56:46 -08001402 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001403 }
1404
1405 if (state() == kRunning) {
1406 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001407 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1408 session_->allocator()->step_delay(),
1409 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001410 } else {
1411 // If all phases in AllocationSequence are completed, no allocation
1412 // steps needed further. Canceling pending signal.
1413 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1414 SignalPortAllocationComplete(this);
1415 }
1416}
1417
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001418void AllocationSequence::CreateUDPPorts() {
1419 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421 return;
1422 }
1423
1424 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1425 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001426 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001427 bool emit_local_candidate_for_anyaddress =
1428 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001430 port = UDPPort::Create(
1431 session_->network_thread(), session_->socket_factory(), network_,
1432 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001433 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1434 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001435 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001436 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001437 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001438 session_->allocator()->min_port(), session_->allocator()->max_port(),
1439 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001440 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1441 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001442 }
1443
1444 if (port) {
1445 // If shared socket is enabled, STUN candidate will be allocated by the
1446 // UDPPort.
1447 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001448 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001449 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001450
1451 // If STUN is not disabled, setting stun server address to port.
1452 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001453 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001454 RTC_LOG(LS_INFO)
1455 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001456 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001458 }
1459 }
1460 }
1461
Steve Antona8f1e562018-10-10 11:29:44 -07001462 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463 }
1464}
1465
1466void AllocationSequence::CreateTCPPorts() {
1467 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001468 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001469 return;
1470 }
1471
Steve Antona8f1e562018-10-10 11:29:44 -07001472 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001473 session_->network_thread(), session_->socket_factory(), network_,
1474 session_->allocator()->min_port(), session_->allocator()->max_port(),
1475 session_->username(), session_->password(),
1476 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001477 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001478 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001479 // Since TCPPort is not created using shared socket, |port| will not be
1480 // added to the dequeue.
1481 }
1482}
1483
1484void AllocationSequence::CreateStunPorts() {
1485 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001486 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001487 return;
1488 }
1489
1490 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1491 return;
1492 }
1493
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001494 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001495 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001496 << "AllocationSequence: No STUN server configured, skipping.";
1497 return;
1498 }
1499
Steve Antona8f1e562018-10-10 11:29:44 -07001500 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001501 session_->network_thread(), session_->socket_factory(), network_,
1502 session_->allocator()->min_port(), session_->allocator()->max_port(),
1503 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001504 session_->allocator()->origin(),
1505 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001506 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001507 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001508 // Since StunPort is not created using shared socket, |port| will not be
1509 // added to the dequeue.
1510 }
1511}
1512
1513void AllocationSequence::CreateRelayPorts() {
1514 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001515 RTC_LOG(LS_VERBOSE)
1516 << "AllocationSequence: Relay ports disabled, skipping.";
1517 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001518 }
1519
1520 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1521 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001522 RTC_DCHECK(config_);
1523 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001524 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001525 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001526 << "AllocationSequence: No relay server configured, skipping.";
1527 return;
1528 }
1529
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001530 for (RelayServerConfig& relay : config_->relays) {
1531 if (relay.type == RELAY_GTURN) {
1532 CreateGturnPort(relay);
1533 } else if (relay.type == RELAY_TURN) {
1534 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001535 } else {
nissec80e7412017-01-11 05:56:46 -08001536 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001537 }
1538 }
1539}
1540
1541void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1542 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001543 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001544 session_->network_thread(), session_->socket_factory(), network_,
1545 session_->allocator()->min_port(), session_->allocator()->max_port(),
1546 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001547 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001548 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001549 // Since RelayPort is not created using shared socket, |port| will not be
1550 // added to the dequeue.
1551 // Note: We must add the allocated port before we add addresses because
1552 // the latter will create candidates that need name and preference
1553 // settings. However, we also can't prepare the address (normally
1554 // done by AddAllocatedPort) until we have these addresses. So we
1555 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001556 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001557
1558 // Add the addresses of this protocol.
1559 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001560 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001561 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001562 port_ptr->AddServerAddress(*relay_port);
1563 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001564 }
1565 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001566 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001567 }
1568}
1569
1570void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1571 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001572 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1573 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001574 // Skip UDP connections to relay servers if it's disallowed.
1575 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1576 relay_port->proto == PROTO_UDP) {
1577 continue;
1578 }
1579
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001580 // Do not create a port if the server address family is known and does
1581 // not match the local IP address family.
1582 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001583 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001584 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001585 RTC_LOG(LS_INFO)
1586 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001587 "Server address: "
1588 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001589 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001590 continue;
1591 }
1592
Jonas Oreland202994c2017-12-18 12:10:43 +01001593 CreateRelayPortArgs args;
1594 args.network_thread = session_->network_thread();
1595 args.socket_factory = session_->socket_factory();
1596 args.network = network_;
1597 args.username = session_->username();
1598 args.password = session_->password();
1599 args.server_address = &(*relay_port);
1600 args.config = &config;
1601 args.origin = session_->allocator()->origin();
1602 args.turn_customizer = session_->allocator()->turn_customizer();
1603
1604 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001605 // Shared socket mode must be enabled only for UDP based ports. Hence
1606 // don't pass shared socket for ports which will create TCP sockets.
1607 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1608 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1609 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001610 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001611 port = session_->allocator()->relay_port_factory()->Create(
1612 args, udp_socket_.get());
1613
1614 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001615 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1616 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001617 continue;
1618 }
1619
1620 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001621 // Listen to the port destroyed signal, to allow AllocationSequence to
1622 // remove entrt from it's map.
1623 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1624 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001625 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001626 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001627 session_->allocator()->max_port());
1628
1629 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001630 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1631 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001632 continue;
1633 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001634 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001635 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001636 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001637 }
1638}
1639
Yves Gerey665174f2018-06-19 15:03:05 +02001640void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1641 const char* data,
1642 size_t size,
1643 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001644 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001645 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001646
1647 bool turn_port_found = false;
1648
1649 // Try to find the TurnPort that matches the remote address. Note that the
1650 // message could be a STUN binding response if the TURN server is also used as
1651 // a STUN server. We don't want to parse every message here to check if it is
1652 // a STUN binding response, so we pass the message to TurnPort regardless of
1653 // the message type. The TurnPort will just ignore the message since it will
1654 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001655 for (auto* port : relay_ports_) {
1656 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001657 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001658 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001659 return;
1660 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001661 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001662 }
1663 }
1664
1665 if (udp_port_) {
1666 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1667
1668 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1669 // the TURN server is also a STUN server.
1670 if (!turn_port_found ||
1671 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001672 RTC_DCHECK(udp_port_->SharedSocket());
1673 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001674 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001675 }
1676 }
1677}
1678
1679void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1680 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001681 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001682 return;
1683 }
1684
Steve Antonae226f62019-01-29 12:47:38 -08001685 auto it = absl::c_find(relay_ports_, port);
Jonas Oreland202994c2017-12-18 12:10:43 +01001686 if (it != relay_ports_.end()) {
1687 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001688 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001689 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001690 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001691 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001692}
1693
1694// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001695PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1696 const std::string& username,
1697 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001698 : stun_address(stun_address), username(username), password(password) {
1699 if (!stun_address.IsNil())
1700 stun_servers.insert(stun_address);
1701}
1702
1703PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1704 const std::string& username,
1705 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001706 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001707 if (!stun_servers.empty())
1708 stun_address = *(stun_servers.begin());
1709}
1710
Steve Anton7995d8c2017-10-30 16:23:38 -07001711PortConfiguration::~PortConfiguration() = default;
1712
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001713ServerAddresses PortConfiguration::StunServers() {
1714 if (!stun_address.IsNil() &&
1715 stun_servers.find(stun_address) == stun_servers.end()) {
1716 stun_servers.insert(stun_address);
1717 }
deadbeefc5d0d952015-07-16 10:22:21 -07001718 // Every UDP TURN server should also be used as a STUN server.
1719 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1720 for (const rtc::SocketAddress& turn_server : turn_servers) {
1721 if (stun_servers.find(turn_server) == stun_servers.end()) {
1722 stun_servers.insert(turn_server);
1723 }
1724 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001725 return stun_servers;
1726}
1727
1728void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1729 relays.push_back(config);
1730}
1731
Yves Gerey665174f2018-06-19 15:03:05 +02001732bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1733 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001734 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001735 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1736 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001737 if (relay_port->proto == type)
1738 return true;
1739 }
1740 return false;
1741}
1742
1743bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1744 ProtocolType type) const {
1745 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001746 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001747 return true;
1748 }
1749 return false;
1750}
1751
1752ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001753 RelayType turn_type,
1754 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001755 ServerAddresses servers;
1756 for (size_t i = 0; i < relays.size(); ++i) {
1757 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1758 servers.insert(relays[i].ports.front().address);
1759 }
1760 }
1761 return servers;
1762}
1763
1764} // namespace cricket