blob: 316bc879dd09bd46bfb68123101e2fcbee1a941c [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>
Qingsi Wang7627fdd2019-08-19 16:07:40 -070017#include <utility>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000018#include <vector>
19
Steve Antonae226f62019-01-29 12:47:38 -080020#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "p2p/base/basic_packet_socket_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "p2p/base/port.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "p2p/base/relay_port.h"
24#include "p2p/base/stun_port.h"
25#include "p2p/base/tcp_port.h"
26#include "p2p/base/turn_port.h"
27#include "p2p/base/udp_port.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
29#include "rtc_base/helpers.h"
30#include "rtc_base/logging.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070031#include "system_wrappers/include/metrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000034
Qingsi Wangc129c352019-04-18 10:41:58 -070035namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036namespace {
37
38enum {
39 MSG_CONFIG_START,
40 MSG_CONFIG_READY,
41 MSG_ALLOCATE,
42 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000043 MSG_SEQUENCEOBJECTS_CREATED,
44 MSG_CONFIG_STOP,
45};
46
47const int PHASE_UDP = 0;
48const int PHASE_RELAY = 1;
49const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050
deadbeef1c5e6d02017-09-15 17:46:56 -070051const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052
zhihuang696f8ca2017-06-27 15:11:24 -070053// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070054int GetProtocolPriority(cricket::ProtocolType protocol) {
55 switch (protocol) {
56 case cricket::PROTO_UDP:
57 return 2;
58 case cricket::PROTO_TCP:
59 return 1;
60 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070061 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070062 return 0;
63 default:
nisseeb4ca4e2017-01-12 02:24:27 -080064 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070065 return 0;
66 }
67}
68// Gets address family priority: IPv6 > IPv4 > Unspecified.
69int GetAddressFamilyPriority(int ip_family) {
70 switch (ip_family) {
71 case AF_INET6:
72 return 2;
73 case AF_INET:
74 return 1;
75 default:
nisseeb4ca4e2017-01-12 02:24:27 -080076 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070077 return 0;
78 }
79}
80
81// Returns positive if a is better, negative if b is better, and 0 otherwise.
82int ComparePort(const cricket::Port* a, const cricket::Port* b) {
83 int a_protocol = GetProtocolPriority(a->GetProtocol());
84 int b_protocol = GetProtocolPriority(b->GetProtocol());
85 int cmp_protocol = a_protocol - b_protocol;
86 if (cmp_protocol != 0) {
87 return cmp_protocol;
88 }
89
90 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
91 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
92 return a_family - b_family;
93}
94
Qingsi Wang10a0e512018-05-16 13:37:03 -070095struct NetworkFilter {
96 using Predicate = std::function<bool(rtc::Network*)>;
97 NetworkFilter(Predicate pred, const std::string& description)
98 : pred(pred), description(description) {}
99 Predicate pred;
100 const std::string description;
101};
102
103using NetworkList = rtc::NetworkManager::NetworkList;
104void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
105 auto start_to_remove =
106 std::remove_if(networks->begin(), networks->end(), filter.pred);
107 if (start_to_remove == networks->end()) {
108 return;
109 }
110 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
111 for (auto it = start_to_remove; it != networks->end(); ++it) {
112 RTC_LOG(INFO) << (*it)->ToString();
113 }
114 networks->erase(start_to_remove, networks->end());
115}
116
Qingsi Wangc129c352019-04-18 10:41:58 -0700117bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) {
118 // When binding to any address, before sending packets out, the getsockname
119 // returns all 0s, but after sending packets, it'll be the NIC used to
120 // send. All 0s is not a valid ICE candidate address and should be filtered
121 // out.
122 if (c.address().IsAnyIP()) {
123 return false;
124 }
125
126 if (c.type() == RELAY_PORT_TYPE) {
127 return ((filter & CF_RELAY) != 0);
128 } else if (c.type() == STUN_PORT_TYPE) {
129 return ((filter & CF_REFLEXIVE) != 0);
130 } else if (c.type() == LOCAL_PORT_TYPE) {
131 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
132 // We allow host candidates if the filter allows server-reflexive
133 // candidates and the candidate is a public IP. Because we don't generate
134 // server-reflexive candidates if they have the same IP as the host
135 // candidate (i.e. when the host candidate is a public IP), filtering to
136 // only server-reflexive candidates won't work right when the host
137 // candidates have public IPs.
138 return true;
139 }
140
141 return ((filter & CF_HOST) != 0);
142 }
143 return false;
144}
145
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146} // namespace
147
Peter Boström0c4e06b2015-10-07 12:23:21 +0200148const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700149 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
150 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151
152// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200153BasicPortAllocator::BasicPortAllocator(
154 rtc::NetworkManager* network_manager,
155 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100156 webrtc::TurnCustomizer* customizer,
157 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700158 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100159 InitRelayPortFactory(relay_port_factory);
160 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800161 RTC_DCHECK(network_manager_ != nullptr);
162 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200163 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
164 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 Construct();
166}
167
Yves Gerey665174f2018-06-19 15:03:05 +0200168BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700169 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100170 InitRelayPortFactory(nullptr);
171 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800172 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 Construct();
174}
175
Yves Gerey665174f2018-06-19 15:03:05 +0200176BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
177 rtc::PacketSocketFactory* socket_factory,
178 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700179 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100180 InitRelayPortFactory(nullptr);
181 RTC_DCHECK(relay_port_factory_ != nullptr);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000182 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200183 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
184 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 Construct();
186}
187
188BasicPortAllocator::BasicPortAllocator(
189 rtc::NetworkManager* network_manager,
190 const ServerAddresses& stun_servers,
191 const rtc::SocketAddress& relay_address_udp,
192 const rtc::SocketAddress& relay_address_tcp,
193 const rtc::SocketAddress& relay_address_ssl)
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000194 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100195 InitRelayPortFactory(nullptr);
196 RTC_DCHECK(relay_port_factory_ != nullptr);
197 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700198 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000199 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800200 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000201 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800202 }
203 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800205 }
206 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800208 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209
deadbeef653b8e02015-11-11 12:55:10 -0800210 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700211 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800212 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213
Jonas Orelandbdcee282017-10-10 14:01:40 +0200214 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215 Construct();
216}
217
218void BasicPortAllocator::Construct() {
219 allow_tcp_listen_ = true;
220}
221
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700222void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
223 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700224 // If the session has not been taken by an active channel, do not report the
225 // metric.
226 for (auto& allocator_session : pooled_sessions()) {
227 if (allocator_session.get() == session) {
228 return;
229 }
230 }
231
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700232 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
233 static_cast<int>(reason),
234 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700235}
236
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700238 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800239 // Our created port allocator sessions depend on us, so destroy our remaining
240 // pooled sessions before anything else.
241 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242}
243
Steve Anton7995d8c2017-10-30 16:23:38 -0700244void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
245 // TODO(phoglund): implement support for other types than loopback.
246 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
247 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700248 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700249 network_ignore_mask_ = network_ignore_mask;
250}
251
deadbeefc5d0d952015-07-16 10:22:21 -0700252PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200253 const std::string& content_name,
254 int component,
255 const std::string& ice_ufrag,
256 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700257 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700258 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700260 session->SignalIceRegathering.connect(this,
261 &BasicPortAllocator::OnIceRegathering);
262 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263}
264
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700265void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700266 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700267 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
268 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700269 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200270 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700271}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000272
Jonas Oreland202994c2017-12-18 12:10:43 +0100273void BasicPortAllocator::InitRelayPortFactory(
274 RelayPortFactoryInterface* relay_port_factory) {
275 if (relay_port_factory != nullptr) {
276 relay_port_factory_ = relay_port_factory;
277 } else {
278 default_relay_port_factory_.reset(new TurnPortFactory());
279 relay_port_factory_ = default_relay_port_factory_.get();
280 }
281}
282
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283// BasicPortAllocatorSession
284BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700285 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 const std::string& content_name,
287 int component,
288 const std::string& ice_ufrag,
289 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700290 : PortAllocatorSession(content_name,
291 component,
292 ice_ufrag,
293 ice_pwd,
294 allocator->flags()),
295 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700296 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297 socket_factory_(allocator->socket_factory()),
298 allocation_started_(false),
299 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700300 allocation_sequences_created_(false),
301 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302 allocator_->network_manager()->SignalNetworksChanged.connect(
303 this, &BasicPortAllocatorSession::OnNetworksChanged);
304 allocator_->network_manager()->StartUpdating();
305}
306
307BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700308 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000309 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000310 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 network_thread_->Clear(this);
312
Peter Boström0c4e06b2015-10-07 12:23:21 +0200313 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 // AllocationSequence should clear it's map entry for turn ports before
315 // ports are destroyed.
316 sequences_[i]->Clear();
317 }
318
319 std::vector<PortData>::iterator it;
320 for (it = ports_.begin(); it != ports_.end(); it++)
321 delete it->port();
322
Peter Boström0c4e06b2015-10-07 12:23:21 +0200323 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000324 delete configs_[i];
325
Peter Boström0c4e06b2015-10-07 12:23:21 +0200326 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327 delete sequences_[i];
328}
329
Steve Anton7995d8c2017-10-30 16:23:38 -0700330BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700331 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700332 return allocator_;
333}
334
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700335void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700336 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700337 if (filter == candidate_filter_) {
338 return;
339 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700340 uint32_t prev_filter = candidate_filter_;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700341 candidate_filter_ = filter;
Qingsi Wangc129c352019-04-18 10:41:58 -0700342 for (PortData& port_data : ports_) {
343 if (port_data.error() || port_data.pruned()) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700344 continue;
345 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700346 PortData::State cur_state = port_data.state();
347 bool found_signalable_candidate = false;
348 bool found_pairable_candidate = false;
349 cricket::Port* port = port_data.port();
350 for (const auto& c : port->Candidates()) {
351 if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) &&
352 IsAllowedByCandidateFilter(c, filter)) {
353 // This candidate was not signaled because of not matching the previous
354 // filter (see OnCandidateReady below). Let the Port to fire the signal
355 // again.
356 //
357 // Note that
358 // 1) we would need the Port to enter the state of in-progress of
359 // gathering to have candidates signaled;
360 //
361 // 2) firing the signal would also let the session set the port ready
362 // if needed, so that we could form candidate pairs with candidates
363 // from this port;
364 //
365 // * See again OnCandidateReady below for 1) and 2).
366 //
367 // 3) we only try to resurface candidates if we have not stopped
368 // getting ports, which is always true for the continual gathering.
369 if (!found_signalable_candidate) {
370 found_signalable_candidate = true;
371 port_data.set_state(PortData::STATE_INPROGRESS);
372 }
373 port->SignalCandidateReady(port, c);
374 }
375
376 if (CandidatePairable(c, port)) {
377 found_pairable_candidate = true;
378 }
379 }
380 // Restore the previous state.
381 port_data.set_state(cur_state);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700382 // Setting a filter may cause a ready port to become non-ready
383 // if it no longer has any pairable candidates.
Qingsi Wangc129c352019-04-18 10:41:58 -0700384 //
385 // Note that we only set for the negative case here, since a port would be
386 // set to have pairable candidates when it signals a ready candidate, which
387 // requires the port is still in the progress of gathering/surfacing
388 // candidates, and would be done in the firing of the signal above.
389 if (!found_pairable_candidate) {
390 port_data.set_has_pairable_candidate(false);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700391 }
392 }
393}
394
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700396 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700397 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 if (!socket_factory_) {
399 owned_socket_factory_.reset(
400 new rtc::BasicPacketSocketFactory(network_thread_));
401 socket_factory_ = owned_socket_factory_.get();
402 }
403
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700404 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700405
Mirko Bonadei675513b2017-11-09 11:09:25 +0100406 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
407 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408}
409
410void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700411 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700412 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700413 // Note: this must be called after ClearGettingPorts because both may set the
414 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700415 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700416}
417
418void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700419 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700421 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700423 }
deadbeefb60a8192016-08-24 15:15:00 -0700424 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700425 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700426}
427
Steve Anton7995d8c2017-10-30 16:23:38 -0700428bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700429 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700430 return state_ == SessionState::GATHERING;
431}
432
433bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700434 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700435 return state_ == SessionState::CLEARED;
436}
437
438bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700439 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700440 return state_ == SessionState::STOPPED;
441}
442
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700443std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700444 RTC_DCHECK_RUN_ON(network_thread_);
445
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700446 std::vector<rtc::Network*> networks = GetNetworks();
447
448 // A network interface may have both IPv4 and IPv6 networks. Only if
449 // neither of the networks has any connections, the network interface
450 // is considered failed and need to be regathered on.
451 std::set<std::string> networks_with_connection;
452 for (const PortData& data : ports_) {
453 Port* port = data.port();
454 if (!port->connections().empty()) {
455 networks_with_connection.insert(port->Network()->name());
456 }
457 }
458
459 networks.erase(
460 std::remove_if(networks.begin(), networks.end(),
461 [networks_with_connection](rtc::Network* network) {
462 // If a network does not have any connection, it is
463 // considered failed.
464 return networks_with_connection.find(network->name()) !=
465 networks_with_connection.end();
466 }),
467 networks.end());
468 return networks;
469}
470
471void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700472 RTC_DCHECK_RUN_ON(network_thread_);
473
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700474 // Find the list of networks that have no connection.
475 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
476 if (failed_networks.empty()) {
477 return;
478 }
479
Mirko Bonadei675513b2017-11-09 11:09:25 +0100480 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700481
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700482 // Mark a sequence as "network failed" if its network is in the list of failed
483 // networks, so that it won't be considered as equivalent when the session
484 // regathers ports and candidates.
485 for (AllocationSequence* sequence : sequences_) {
486 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800487 absl::c_linear_search(failed_networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700488 sequence->set_network_failed();
489 }
490 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700491
492 bool disable_equivalent_phases = true;
493 Regather(failed_networks, disable_equivalent_phases,
494 IceRegatheringReason::NETWORK_FAILURE);
495}
496
497void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700498 RTC_DCHECK_RUN_ON(network_thread_);
499
Steve Anton300bf8e2017-07-14 10:13:10 -0700500 std::vector<rtc::Network*> networks = GetNetworks();
501 if (networks.empty()) {
502 return;
503 }
504
Mirko Bonadei675513b2017-11-09 11:09:25 +0100505 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700506
507 // We expect to generate candidates that are equivalent to what we have now.
508 // Force DoAllocate to generate them instead of skipping.
509 bool disable_equivalent_phases = false;
510 Regather(networks, disable_equivalent_phases,
511 IceRegatheringReason::OCCASIONAL_REFRESH);
512}
513
514void BasicPortAllocatorSession::Regather(
515 const std::vector<rtc::Network*>& networks,
516 bool disable_equivalent_phases,
517 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700518 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700519 // Remove ports from being used locally and send signaling to remove
520 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700521 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700522 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100523 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000524 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700525 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700526
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700527 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700528 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700529
Steve Anton300bf8e2017-07-14 10:13:10 -0700530 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700531 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532}
533
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700534void BasicPortAllocatorSession::GetCandidateStatsFromReadyPorts(
535 CandidateStatsList* candidate_stats_list) const {
536 auto ports = ReadyPorts();
537 for (auto* port : ports) {
538 auto candidates = port->Candidates();
539 for (const auto& candidate : candidates) {
540 CandidateStats candidate_stats(allocator_->SanitizeCandidate(candidate));
541 port->GetStunStats(&candidate_stats.stun_stats);
542 candidate_stats_list->push_back(std::move(candidate_stats));
543 }
544 }
545}
546
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800547void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200548 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700549 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800550 auto ports = ReadyPorts();
551 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800552 // The port type and protocol can be used to identify different subclasses
553 // of Port in the current implementation. Note that a TCPPort has the type
554 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
555 if (port->Type() == STUN_PORT_TYPE ||
556 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800557 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
558 stun_keepalive_interval);
559 }
560 }
561}
562
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700563std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700564 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700565 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700566 for (const PortData& data : ports_) {
567 if (data.ready()) {
568 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700569 }
570 }
571 return ret;
572}
573
574std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700575 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700576 std::vector<Candidate> candidates;
577 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700578 if (!data.ready()) {
579 continue;
580 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700581 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700582 }
583 return candidates;
584}
585
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700586void BasicPortAllocatorSession::GetCandidatesFromPort(
587 const PortData& data,
588 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700589 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700590 RTC_CHECK(candidates != nullptr);
591 for (const Candidate& candidate : data.port()->Candidates()) {
592 if (!CheckCandidateFilter(candidate)) {
593 continue;
594 }
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700595 candidates->push_back(allocator_->SanitizeCandidate(candidate));
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700596 }
597}
598
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700599bool BasicPortAllocator::MdnsObfuscationEnabled() const {
600 return network_manager()->GetMdnsResponder() != nullptr;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700601}
602
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700603bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700604 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700605 // Done only if all required AllocationSequence objects
606 // are created.
607 if (!allocation_sequences_created_) {
608 return false;
609 }
610
611 // Check that all port allocation sequences are complete (not running).
Steve Antonae226f62019-01-29 12:47:38 -0800612 if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
613 return sequence->state() == AllocationSequence::kRunning;
614 })) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700615 return false;
616 }
617
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700618 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700619 // expected candidates. Session will trigger candidates allocation complete
620 // signal.
Steve Antonae226f62019-01-29 12:47:38 -0800621 return absl::c_none_of(
622 ports_, [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700623}
624
Yves Gerey665174f2018-06-19 15:03:05 +0200625void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200627 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200628 GetPortConfigurations();
629 break;
630 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200631 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
632 break;
633 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200634 OnAllocate();
635 break;
636 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200637 OnAllocationSequenceObjectsCreated();
638 break;
639 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200640 OnConfigStop();
641 break;
642 default:
643 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000644 }
645}
646
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700647void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700648 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700649 for (PortData& port : ports_) {
650 port.port()->set_content_name(content_name());
651 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
652 }
653}
654
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000655void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700656 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangc129c352019-04-18 10:41:58 -0700657
Yves Gerey665174f2018-06-19 15:03:05 +0200658 PortConfiguration* config =
659 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660
deadbeef653b8e02015-11-11 12:55:10 -0800661 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
662 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663 }
664 ConfigReady(config);
665}
666
667void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700668 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700669 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670}
671
672// Adds a configuration to the list.
673void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700674 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800675 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000676 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800677 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000678
679 AllocatePorts();
680}
681
682void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700683 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684
685 // If any of the allocated ports have not completed the candidates allocation,
686 // mark those as error. Since session doesn't need any new candidates
687 // at this stage of the allocation, it's safe to discard any new candidates.
688 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200689 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
690 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700691 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000692 // Updating port state to error, which didn't finish allocating candidates
693 // yet.
Qingsi Wangc129c352019-04-18 10:41:58 -0700694 it->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695 send_signal = true;
696 }
697 }
698
699 // Did we stop any running sequences?
700 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
701 it != sequences_.end() && !send_signal; ++it) {
702 if ((*it)->state() == AllocationSequence::kStopped) {
703 send_signal = true;
704 }
705 }
706
707 // If we stopped anything that was running, send a done signal now.
708 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000709 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000710 }
711}
712
713void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700714 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700715 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000716}
717
718void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700719 RTC_DCHECK_RUN_ON(network_thread_);
720
Steve Anton300bf8e2017-07-14 10:13:10 -0700721 if (network_manager_started_ && !IsStopped()) {
722 bool disable_equivalent_phases = true;
723 DoAllocate(disable_equivalent_phases);
724 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000725
726 allocation_started_ = true;
727}
728
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700729std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700730 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700731 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700732 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800733 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700734 // If the network permission state is BLOCKED, we just act as if the flag has
735 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700736 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700737 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700738 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
739 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000740 // If the adapter enumeration is disabled, we'll just bind to any address
741 // instead of specific NIC. This is to ensure the same routing for http
742 // traffic by OS is also used here to avoid any local or public IP leakage
743 // during stun process.
744 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
745 network_manager->GetAnyAddressNetworks(&networks);
746 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700747 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000748 // If network enumeration fails, use the ANY address as a fallback, so we
749 // can at least try gathering candidates using the default route chosen by
750 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
751 // set, we'll use ANY address candidates either way.
752 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
753 network_manager->GetAnyAddressNetworks(&networks);
754 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000755 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100756 // Filter out link-local networks if needed.
757 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700758 NetworkFilter link_local_filter(
759 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
760 "link-local");
761 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100762 }
deadbeef3427f532017-07-26 16:09:33 -0700763 // Do some more filtering, depending on the network ignore mask and "disable
764 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700765 NetworkFilter ignored_filter(
766 [this](rtc::Network* network) {
767 return allocator_->network_ignore_mask() & network->type();
768 },
769 "ignored");
770 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700771 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
772 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700773 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000774 // Don't determine the lowest cost from a link-local network.
775 // On iOS, a device connected to the computer will get a link-local
776 // network for communicating with the computer, however this network can't
777 // be used to connect to a peer outside the network.
778 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800779 continue;
780 }
honghaiz60347052016-05-31 18:29:12 -0700781 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
782 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700783 NetworkFilter costly_filter(
784 [lowest_cost](rtc::Network* network) {
785 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
786 },
787 "costly");
788 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700789 }
deadbeef3427f532017-07-26 16:09:33 -0700790 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
791 // default, it's 5), remove networks to ensure that limit is satisfied.
792 //
793 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
794 // networks, we could try to choose a set that's "most likely to work". It's
795 // hard to define what that means though; it's not just "lowest cost".
796 // Alternatively, we could just focus on making our ICE pinging logic smarter
797 // such that this filtering isn't necessary in the first place.
798 int ipv6_networks = 0;
799 for (auto it = networks.begin(); it != networks.end();) {
800 if ((*it)->prefix().family() == AF_INET6) {
801 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
802 it = networks.erase(it);
803 continue;
804 } else {
805 ++ipv6_networks;
806 }
807 }
808 ++it;
809 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700810 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700811}
812
813// For each network, see if we have a sequence that covers it already. If not,
814// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700815void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700816 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700817 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700818 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100820 RTC_LOG(LS_WARNING)
821 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822 done_signal_needed = true;
823 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100824 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700825 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200826 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200827 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
829 // If all the ports are disabled we should just fire the allocation
830 // done event and return.
831 done_signal_needed = true;
832 break;
833 }
834
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 if (!config || config->relays.empty()) {
836 // No relay ports specified in this config.
837 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
838 }
839
840 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842 // Skip IPv6 networks unless the flag's been set.
843 continue;
844 }
845
zhihuangb09b3f92017-03-07 14:40:51 -0800846 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
847 networks[i]->GetBestIP().family() == AF_INET6 &&
848 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
849 // Skip IPv6 Wi-Fi networks unless the flag's been set.
850 continue;
851 }
852
Steve Anton300bf8e2017-07-14 10:13:10 -0700853 if (disable_equivalent) {
854 // Disable phases that would only create ports equivalent to
855 // ones that we have already made.
856 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000857
Steve Anton300bf8e2017-07-14 10:13:10 -0700858 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
859 // New AllocationSequence would have nothing to do, so don't make it.
860 continue;
861 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862 }
863
864 AllocationSequence* sequence =
865 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 sequence->SignalPortAllocationComplete.connect(
867 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700868 sequence->Init();
869 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700871 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872 }
873 }
874 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700875 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876 }
877}
878
879void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700880 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700881 std::vector<rtc::Network*> networks = GetNetworks();
882 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700883 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700884 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700885 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700886 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800887 !absl::c_linear_search(networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700888 sequence->OnNetworkFailed();
889 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700890 }
891 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700892 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
893 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
895 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000896 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700897 }
honghaiz8c404fa2015-09-28 07:59:43 -0700898
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700899 if (allocation_started_ && !IsStopped()) {
900 if (network_manager_started_) {
901 // If the network manager has started, it must be regathering.
902 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
903 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700904 bool disable_equivalent_phases = true;
905 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700906 }
907
Honghai Zhang5048f572016-08-23 15:47:33 -0700908 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100909 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700910 network_manager_started_ = true;
911 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000912}
913
914void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200915 rtc::Network* network,
916 PortConfiguration* config,
917 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700918 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200919 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200920 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200921 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922 sequences_[i]->DisableEquivalentPhases(network, config, flags);
923 }
924}
925
926void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200927 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000928 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700929 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930 if (!port)
931 return;
932
Mirko Bonadei675513b2017-11-09 11:09:25 +0100933 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000934 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700935 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700937 if (allocator_->proxy().type != rtc::PROXY_NONE)
938 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700939 port->set_send_retransmit_count_attribute(
940 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000942 PortData data(port, seq);
943 ports_.push_back(data);
944
945 port->SignalCandidateReady.connect(
946 this, &BasicPortAllocatorSession::OnCandidateReady);
Eldar Relloda13ea22019-06-01 12:23:43 +0300947 port->SignalCandidateError.connect(
948 this, &BasicPortAllocatorSession::OnCandidateError);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200950 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000951 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200952 &BasicPortAllocatorSession::OnPortDestroyed);
953 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
954 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000955
956 if (prepare_address)
957 port->PrepareAddress();
958}
959
960void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700961 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962 allocation_sequences_created_ = true;
963 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000964 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000965}
966
Yves Gerey665174f2018-06-19 15:03:05 +0200967void BasicPortAllocatorSession::OnCandidateReady(Port* port,
968 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700969 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000971 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200972 RTC_LOG(LS_INFO) << port->ToString()
973 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000974 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700975 // already done with gathering.
976 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100977 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700978 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700979 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700980 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700981
danilchapf4e8cf02016-06-30 01:55:03 -0700982 // Mark that the port has a pairable candidate, either because we have a
983 // usable candidate from the port, or simply because the port is bound to the
984 // any address and therefore has no host candidate. This will trigger the port
985 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700986 // checks. If port has already been marked as having a pairable candidate,
987 // do nothing here.
988 // Note: We should check whether any candidates may become ready after this
989 // because there we will check whether the candidate is generated by the ready
990 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700991 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700992 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700993 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700994
995 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700996 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700997 }
998 // If the current port is not pruned yet, SignalPortReady.
999 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001000 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
1001 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001002 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001003 }
Honghai Zhang17aac052016-06-29 21:41:53 -07001004 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001005
deadbeef1c5e6d02017-09-15 17:46:56 -07001006 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001007 std::vector<Candidate> candidates;
Qingsi Wang7627fdd2019-08-19 16:07:40 -07001008 candidates.push_back(allocator_->SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001009 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -07001010 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001011 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001012 }
1013
1014 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001015 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001016 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001017 }
1018}
1019
Eldar Relloda13ea22019-06-01 12:23:43 +03001020void BasicPortAllocatorSession::OnCandidateError(
1021 Port* port,
1022 const IceCandidateErrorEvent& event) {
1023 RTC_DCHECK_RUN_ON(network_thread_);
1024 RTC_DCHECK(FindPort(port));
1025
1026 SignalCandidateError(this, event);
1027}
1028
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001029Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
1030 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -07001031 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001032 Port* best_turn_port = nullptr;
1033 for (const PortData& data : ports_) {
1034 if (data.port()->Network()->name() == network_name &&
1035 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1036 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
1037 best_turn_port = data.port();
1038 }
1039 }
1040 return best_turn_port;
1041}
1042
1043bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -07001044 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001045 // Note: We determine the same network based only on their network names. So
1046 // if an IPv4 address and an IPv6 address have the same network name, they
1047 // are considered the same network here.
1048 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1049 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1050 // |port| is already in the list of ports, so the best port cannot be nullptr.
1051 RTC_CHECK(best_turn_port != nullptr);
1052
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001053 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001054 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001055 for (PortData& data : ports_) {
1056 if (data.port()->Network()->name() == network_name &&
1057 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1058 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001059 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001060 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001061 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001062 ports_to_prune.push_back(&data);
1063 } else {
1064 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001065 }
1066 }
1067 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001068
1069 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001070 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1071 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001072 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001073 }
1074 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001075}
1076
Honghai Zhanga74363c2016-07-28 18:06:15 -07001077void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001078 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001079 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001080 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001081 }
1082}
1083
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001084void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001085 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001086 RTC_LOG(LS_INFO) << port->ToString()
1087 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001088 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001089 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001090
1091 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001092 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001094 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001095
1096 // Moving to COMPLETE state.
Qingsi Wangc129c352019-04-18 10:41:58 -07001097 data->set_state(PortData::STATE_COMPLETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001098 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001099 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100}
1101
1102void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001103 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001104 RTC_LOG(LS_INFO) << port->ToString()
1105 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001107 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001109 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001111 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112
1113 // SignalAddressError is currently sent from StunPort/TurnPort.
1114 // But this signal itself is generic.
Qingsi Wangc129c352019-04-18 10:41:58 -07001115 data->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001116 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001117 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001118}
1119
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001120bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001121 RTC_DCHECK_RUN_ON(network_thread_);
1122
Qingsi Wangc129c352019-04-18 10:41:58 -07001123 return IsAllowedByCandidateFilter(c, candidate_filter_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001124}
1125
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001126bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1127 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001128 RTC_DCHECK_RUN_ON(network_thread_);
1129
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001130 bool candidate_signalable = CheckCandidateFilter(c);
1131
1132 // When device enumeration is disabled (to prevent non-default IP addresses
1133 // from leaking), we ping from some local candidates even though we don't
1134 // signal them. However, if host candidates are also disabled (for example, to
1135 // prevent even default IP addresses from leaking), we still don't want to
1136 // ping from them, even if device enumeration is disabled. Thus, we check for
1137 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001138 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001139 bool can_ping_from_candidate =
1140 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1141 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1142
1143 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001144 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001145 !host_candidates_disabled);
1146}
1147
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001148void BasicPortAllocatorSession::OnPortAllocationComplete(
1149 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001150 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001151 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001152 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001153}
1154
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001155void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001156 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001157 if (CandidatesAllocationDone()) {
1158 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001159 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001160 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001161 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1162 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001163 }
1164 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001165 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001166}
1167
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001168void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001169 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 for (std::vector<PortData>::iterator iter = ports_.begin();
1171 iter != ports_.end(); ++iter) {
1172 if (port == iter->port()) {
1173 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001174 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001175 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001176 return;
1177 }
1178 }
nissec80e7412017-01-11 05:56:46 -08001179 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001180}
1181
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001182BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1183 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001184 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001185 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1186 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187 if (it->port() == port) {
1188 return &*it;
1189 }
1190 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001191 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001192}
1193
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001194std::vector<BasicPortAllocatorSession::PortData*>
1195BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001196 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001197 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001198 std::vector<PortData*> unpruned_ports;
1199 for (PortData& port : ports_) {
1200 if (!port.pruned() &&
Steve Antonae226f62019-01-29 12:47:38 -08001201 absl::c_linear_search(networks, port.sequence()->network())) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001202 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001203 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001204 }
1205 return unpruned_ports;
1206}
1207
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001208void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001209 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001210 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001211 std::vector<PortInterface*> pruned_ports;
1212 std::vector<Candidate> removed_candidates;
1213 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001214 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001215 data->Prune();
1216 pruned_ports.push_back(data->port());
1217 if (data->has_pairable_candidate()) {
1218 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001219 // Mark the port as having no pairable candidates so that its candidates
1220 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001221 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001222 }
1223 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001224 if (!pruned_ports.empty()) {
1225 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001226 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001227 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001228 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1229 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001230 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001231 }
1232}
1233
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001234// AllocationSequence
1235
1236AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1237 rtc::Network* network,
1238 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001239 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240 : session_(session),
1241 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001242 config_(config),
1243 state_(kInit),
1244 flags_(flags),
1245 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001246 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001247 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001248
Honghai Zhang5048f572016-08-23 15:47:33 -07001249void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001250 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1251 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001252 rtc::SocketAddress(network_->GetBestIP(), 0),
1253 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001254 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001255 udp_socket_->SignalReadPacket.connect(this,
1256 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001257 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001258 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1259 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001260 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001261}
1262
1263void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001264 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001265 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266}
1267
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001268void AllocationSequence::OnNetworkFailed() {
1269 RTC_DCHECK(!network_failed_);
1270 network_failed_ = true;
1271 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001272 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001273}
1274
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001275AllocationSequence::~AllocationSequence() {
1276 session_->network_thread()->Clear(this);
1277}
1278
1279void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001280 PortConfiguration* config,
1281 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001282 if (network_failed_) {
1283 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001284 // it won't be equivalent to the new network.
1285 return;
1286 }
1287
deadbeef5c3c1042017-08-04 15:01:57 -07001288 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001289 // Different network setup; nothing is equivalent.
1290 return;
1291 }
1292
1293 // Else turn off the stuff that we've already got covered.
1294
deadbeef1c46a352017-09-27 11:24:05 -07001295 // Every config implicitly specifies local, so turn that off right away if we
1296 // already have a port of the corresponding type. Look for a port that
1297 // matches this AllocationSequence's network, is the right protocol, and
1298 // hasn't encountered an error.
1299 // TODO(deadbeef): This doesn't take into account that there may be another
1300 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1301 // This can happen if, say, there's a network change event right before an
1302 // application-triggered ICE restart. Hopefully this problem will just go
1303 // away if we get rid of the gathering "phases" though, which is planned.
Qingsi Wangc129c352019-04-18 10:41:58 -07001304 //
1305 //
1306 // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1307 // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1308 // to disable the gathering of these candidates just becaue of an existing
1309 // Port over PROTO_UDP, namely a TurnPort over UDP.
Steve Antonae226f62019-01-29 12:47:38 -08001310 if (absl::c_any_of(session_->ports_,
1311 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001312 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001313 p.port()->GetProtocol() == PROTO_UDP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001314 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001315 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001316 *flags |= PORTALLOCATOR_DISABLE_UDP;
1317 }
Qingsi Wangc129c352019-04-18 10:41:58 -07001318 // Similarly we need to check both the protocol used by an existing Port and
1319 // its type.
Steve Antonae226f62019-01-29 12:47:38 -08001320 if (absl::c_any_of(session_->ports_,
1321 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001322 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001323 p.port()->GetProtocol() == PROTO_TCP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001324 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001325 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001326 *flags |= PORTALLOCATOR_DISABLE_TCP;
1327 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001328
1329 if (config_ && config) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001330 // We need to regather srflx candidates if either of the following
1331 // conditions occurs:
1332 // 1. The STUN servers are different from the previous gathering.
1333 // 2. We will regather host candidates, hence possibly inducing new NAT
1334 // bindings.
1335 if (config_->StunServers() == config->StunServers() &&
1336 (*flags & PORTALLOCATOR_DISABLE_UDP)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001337 // Already got this STUN servers covered.
1338 *flags |= PORTALLOCATOR_DISABLE_STUN;
1339 }
1340 if (!config_->relays.empty()) {
1341 // Already got relays covered.
1342 // NOTE: This will even skip a _different_ set of relay servers if we
1343 // were to be given one, but that never happens in our codebase. Should
1344 // probably get rid of the list in PortConfiguration and just keep a
1345 // single relay server in each one.
1346 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1347 }
1348 }
1349}
1350
1351void AllocationSequence::Start() {
1352 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001353 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001354 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1355 // called next time, we enable all phases if the best IP has since changed.
1356 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001357}
1358
1359void AllocationSequence::Stop() {
1360 // If the port is completed, don't set it to stopped.
1361 if (state_ == kRunning) {
1362 state_ = kStopped;
1363 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1364 }
1365}
1366
1367void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001368 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1369 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370
deadbeef1c5e6d02017-09-15 17:46:56 -07001371 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372
1373 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001374 RTC_LOG(LS_INFO) << network_->ToString()
1375 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001376
1377 switch (phase_) {
1378 case PHASE_UDP:
1379 CreateUDPPorts();
1380 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001381 break;
1382
1383 case PHASE_RELAY:
1384 CreateRelayPorts();
1385 break;
1386
1387 case PHASE_TCP:
1388 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001389 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 break;
1391
1392 default:
nissec80e7412017-01-11 05:56:46 -08001393 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001394 }
1395
1396 if (state() == kRunning) {
1397 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001398 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1399 session_->allocator()->step_delay(),
1400 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001401 } else {
1402 // If all phases in AllocationSequence are completed, no allocation
1403 // steps needed further. Canceling pending signal.
1404 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1405 SignalPortAllocationComplete(this);
1406 }
1407}
1408
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001409void AllocationSequence::CreateUDPPorts() {
1410 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001411 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412 return;
1413 }
1414
1415 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1416 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001417 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001418 bool emit_local_candidate_for_anyaddress =
1419 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001420 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001421 port = UDPPort::Create(
1422 session_->network_thread(), session_->socket_factory(), network_,
1423 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001424 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1425 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001427 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001428 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001429 session_->allocator()->min_port(), session_->allocator()->max_port(),
1430 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001431 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1432 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001433 }
1434
1435 if (port) {
1436 // If shared socket is enabled, STUN candidate will be allocated by the
1437 // UDPPort.
1438 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001439 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001440 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001441
1442 // If STUN is not disabled, setting stun server address to port.
1443 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001444 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001445 RTC_LOG(LS_INFO)
1446 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001447 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001448 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001449 }
1450 }
1451 }
1452
Steve Antona8f1e562018-10-10 11:29:44 -07001453 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001454 }
1455}
1456
1457void AllocationSequence::CreateTCPPorts() {
1458 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001459 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001460 return;
1461 }
1462
Steve Antona8f1e562018-10-10 11:29:44 -07001463 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001464 session_->network_thread(), session_->socket_factory(), network_,
1465 session_->allocator()->min_port(), session_->allocator()->max_port(),
1466 session_->username(), session_->password(),
1467 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001468 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001469 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001470 // Since TCPPort is not created using shared socket, |port| will not be
1471 // added to the dequeue.
1472 }
1473}
1474
1475void AllocationSequence::CreateStunPorts() {
1476 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001477 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001478 return;
1479 }
1480
1481 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1482 return;
1483 }
1484
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001485 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001486 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001487 << "AllocationSequence: No STUN server configured, skipping.";
1488 return;
1489 }
1490
Steve Antona8f1e562018-10-10 11:29:44 -07001491 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001492 session_->network_thread(), session_->socket_factory(), network_,
1493 session_->allocator()->min_port(), session_->allocator()->max_port(),
1494 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001495 session_->allocator()->origin(),
1496 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001497 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001498 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001499 // Since StunPort is not created using shared socket, |port| will not be
1500 // added to the dequeue.
1501 }
1502}
1503
1504void AllocationSequence::CreateRelayPorts() {
1505 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001506 RTC_LOG(LS_VERBOSE)
1507 << "AllocationSequence: Relay ports disabled, skipping.";
1508 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001509 }
1510
1511 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1512 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001513 RTC_DCHECK(config_);
1514 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001515 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001516 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001517 << "AllocationSequence: No relay server configured, skipping.";
1518 return;
1519 }
1520
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001521 for (RelayServerConfig& relay : config_->relays) {
1522 if (relay.type == RELAY_GTURN) {
1523 CreateGturnPort(relay);
1524 } else if (relay.type == RELAY_TURN) {
1525 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001526 } else {
nissec80e7412017-01-11 05:56:46 -08001527 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001528 }
1529 }
1530}
1531
1532void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1533 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001534 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001535 session_->network_thread(), session_->socket_factory(), network_,
1536 session_->allocator()->min_port(), session_->allocator()->max_port(),
1537 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001538 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001539 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001540 // Since RelayPort is not created using shared socket, |port| will not be
1541 // added to the dequeue.
1542 // Note: We must add the allocated port before we add addresses because
1543 // the latter will create candidates that need name and preference
1544 // settings. However, we also can't prepare the address (normally
1545 // done by AddAllocatedPort) until we have these addresses. So we
1546 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001547 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001548
1549 // Add the addresses of this protocol.
1550 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001551 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001552 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001553 port_ptr->AddServerAddress(*relay_port);
1554 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001555 }
1556 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001557 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001558 }
1559}
1560
1561void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1562 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001563 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1564 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001565 // Skip UDP connections to relay servers if it's disallowed.
1566 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1567 relay_port->proto == PROTO_UDP) {
1568 continue;
1569 }
1570
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001571 // Do not create a port if the server address family is known and does
1572 // not match the local IP address family.
1573 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001574 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001575 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001576 RTC_LOG(LS_INFO)
1577 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001578 "Server address: "
1579 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001580 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001581 continue;
1582 }
1583
Jonas Oreland202994c2017-12-18 12:10:43 +01001584 CreateRelayPortArgs args;
1585 args.network_thread = session_->network_thread();
1586 args.socket_factory = session_->socket_factory();
1587 args.network = network_;
1588 args.username = session_->username();
1589 args.password = session_->password();
1590 args.server_address = &(*relay_port);
1591 args.config = &config;
1592 args.origin = session_->allocator()->origin();
1593 args.turn_customizer = session_->allocator()->turn_customizer();
1594
1595 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001596 // Shared socket mode must be enabled only for UDP based ports. Hence
1597 // don't pass shared socket for ports which will create TCP sockets.
1598 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1599 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1600 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001601 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001602 port = session_->allocator()->relay_port_factory()->Create(
1603 args, udp_socket_.get());
1604
1605 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001606 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1607 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001608 continue;
1609 }
1610
1611 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001612 // Listen to the port destroyed signal, to allow AllocationSequence to
1613 // remove entrt from it's map.
1614 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1615 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001616 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001617 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001618 session_->allocator()->max_port());
1619
1620 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001621 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1622 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001623 continue;
1624 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001625 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001626 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001627 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001628 }
1629}
1630
Yves Gerey665174f2018-06-19 15:03:05 +02001631void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1632 const char* data,
1633 size_t size,
1634 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001635 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001636 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001637
1638 bool turn_port_found = false;
1639
1640 // Try to find the TurnPort that matches the remote address. Note that the
1641 // message could be a STUN binding response if the TURN server is also used as
1642 // a STUN server. We don't want to parse every message here to check if it is
1643 // a STUN binding response, so we pass the message to TurnPort regardless of
1644 // the message type. The TurnPort will just ignore the message since it will
1645 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001646 for (auto* port : relay_ports_) {
1647 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001648 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001649 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001650 return;
1651 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001652 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001653 }
1654 }
1655
1656 if (udp_port_) {
1657 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1658
1659 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1660 // the TURN server is also a STUN server.
1661 if (!turn_port_found ||
1662 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001663 RTC_DCHECK(udp_port_->SharedSocket());
1664 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001665 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001666 }
1667 }
1668}
1669
1670void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1671 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001672 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001673 return;
1674 }
1675
Steve Antonae226f62019-01-29 12:47:38 -08001676 auto it = absl::c_find(relay_ports_, port);
Jonas Oreland202994c2017-12-18 12:10:43 +01001677 if (it != relay_ports_.end()) {
1678 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001679 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001680 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001681 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001682 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001683}
1684
1685// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001686PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1687 const std::string& username,
1688 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001689 : stun_address(stun_address), username(username), password(password) {
1690 if (!stun_address.IsNil())
1691 stun_servers.insert(stun_address);
1692}
1693
1694PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1695 const std::string& username,
1696 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001697 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001698 if (!stun_servers.empty())
1699 stun_address = *(stun_servers.begin());
1700}
1701
Steve Anton7995d8c2017-10-30 16:23:38 -07001702PortConfiguration::~PortConfiguration() = default;
1703
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001704ServerAddresses PortConfiguration::StunServers() {
1705 if (!stun_address.IsNil() &&
1706 stun_servers.find(stun_address) == stun_servers.end()) {
1707 stun_servers.insert(stun_address);
1708 }
deadbeefc5d0d952015-07-16 10:22:21 -07001709 // Every UDP TURN server should also be used as a STUN server.
1710 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1711 for (const rtc::SocketAddress& turn_server : turn_servers) {
1712 if (stun_servers.find(turn_server) == stun_servers.end()) {
1713 stun_servers.insert(turn_server);
1714 }
1715 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001716 return stun_servers;
1717}
1718
1719void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1720 relays.push_back(config);
1721}
1722
Yves Gerey665174f2018-06-19 15:03:05 +02001723bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1724 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001725 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001726 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1727 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001728 if (relay_port->proto == type)
1729 return true;
1730 }
1731 return false;
1732}
1733
1734bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1735 ProtocolType type) const {
1736 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001737 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001738 return true;
1739 }
1740 return false;
1741}
1742
1743ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001744 RelayType turn_type,
1745 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001746 ServerAddresses servers;
1747 for (size_t i = 0; i < relays.size(); ++i) {
1748 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1749 servers.insert(relays[i].ports.front().address);
1750 }
1751 }
1752 return servers;
1753}
1754
1755} // namespace cricket