blob: b2cc99a2b7e2e5760623bb990a63fc1c7fdfe0df [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"
Honghai Zhang6981fb52019-10-29 12:45:34 -070031#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070032#include "system_wrappers/include/metrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000033
34using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000035
Qingsi Wangc129c352019-04-18 10:41:58 -070036namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037namespace {
38
39enum {
40 MSG_CONFIG_START,
41 MSG_CONFIG_READY,
42 MSG_ALLOCATE,
43 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000044 MSG_SEQUENCEOBJECTS_CREATED,
45 MSG_CONFIG_STOP,
46};
47
48const int PHASE_UDP = 0;
49const int PHASE_RELAY = 1;
50const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000051
deadbeef1c5e6d02017-09-15 17:46:56 -070052const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053
zhihuang696f8ca2017-06-27 15:11:24 -070054// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070055int GetProtocolPriority(cricket::ProtocolType protocol) {
56 switch (protocol) {
57 case cricket::PROTO_UDP:
58 return 2;
59 case cricket::PROTO_TCP:
60 return 1;
61 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070062 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070063 return 0;
64 default:
nisseeb4ca4e2017-01-12 02:24:27 -080065 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070066 return 0;
67 }
68}
69// Gets address family priority: IPv6 > IPv4 > Unspecified.
70int GetAddressFamilyPriority(int ip_family) {
71 switch (ip_family) {
72 case AF_INET6:
73 return 2;
74 case AF_INET:
75 return 1;
76 default:
nisseeb4ca4e2017-01-12 02:24:27 -080077 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070078 return 0;
79 }
80}
81
82// Returns positive if a is better, negative if b is better, and 0 otherwise.
83int ComparePort(const cricket::Port* a, const cricket::Port* b) {
84 int a_protocol = GetProtocolPriority(a->GetProtocol());
85 int b_protocol = GetProtocolPriority(b->GetProtocol());
86 int cmp_protocol = a_protocol - b_protocol;
87 if (cmp_protocol != 0) {
88 return cmp_protocol;
89 }
90
91 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
92 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
93 return a_family - b_family;
94}
95
Qingsi Wang10a0e512018-05-16 13:37:03 -070096struct NetworkFilter {
97 using Predicate = std::function<bool(rtc::Network*)>;
98 NetworkFilter(Predicate pred, const std::string& description)
99 : pred(pred), description(description) {}
100 Predicate pred;
101 const std::string description;
102};
103
104using NetworkList = rtc::NetworkManager::NetworkList;
105void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
106 auto start_to_remove =
107 std::remove_if(networks->begin(), networks->end(), filter.pred);
108 if (start_to_remove == networks->end()) {
109 return;
110 }
111 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
112 for (auto it = start_to_remove; it != networks->end(); ++it) {
113 RTC_LOG(INFO) << (*it)->ToString();
114 }
115 networks->erase(start_to_remove, networks->end());
116}
117
Qingsi Wangc129c352019-04-18 10:41:58 -0700118bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) {
119 // When binding to any address, before sending packets out, the getsockname
120 // returns all 0s, but after sending packets, it'll be the NIC used to
121 // send. All 0s is not a valid ICE candidate address and should be filtered
122 // out.
123 if (c.address().IsAnyIP()) {
124 return false;
125 }
126
127 if (c.type() == RELAY_PORT_TYPE) {
128 return ((filter & CF_RELAY) != 0);
129 } else if (c.type() == STUN_PORT_TYPE) {
130 return ((filter & CF_REFLEXIVE) != 0);
131 } else if (c.type() == LOCAL_PORT_TYPE) {
132 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
133 // We allow host candidates if the filter allows server-reflexive
134 // candidates and the candidate is a public IP. Because we don't generate
135 // server-reflexive candidates if they have the same IP as the host
136 // candidate (i.e. when the host candidate is a public IP), filtering to
137 // only server-reflexive candidates won't work right when the host
138 // candidates have public IPs.
139 return true;
140 }
141
142 return ((filter & CF_HOST) != 0);
143 }
144 return false;
145}
146
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147} // namespace
148
Peter Boström0c4e06b2015-10-07 12:23:21 +0200149const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700150 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
151 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152
153// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200154BasicPortAllocator::BasicPortAllocator(
155 rtc::NetworkManager* network_manager,
156 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100157 webrtc::TurnCustomizer* customizer,
158 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700159 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100160 InitRelayPortFactory(relay_port_factory);
161 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800162 RTC_DCHECK(network_manager_ != nullptr);
163 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200164 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700165 webrtc::NO_PRUNE, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000166 Construct();
167}
168
Yves Gerey665174f2018-06-19 15:03:05 +0200169BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700170 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100171 InitRelayPortFactory(nullptr);
172 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800173 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000174 Construct();
175}
176
Yves Gerey665174f2018-06-19 15:03:05 +0200177BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
Niels Möllera3baf2a2019-09-06 10:29:50 +0200178 const ServerAddresses& stun_servers)
179 : BasicPortAllocator(network_manager,
180 /*socket_factory=*/nullptr,
181 stun_servers) {}
182
183BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
Yves Gerey665174f2018-06-19 15:03:05 +0200184 rtc::PacketSocketFactory* socket_factory,
185 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700186 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100187 InitRelayPortFactory(nullptr);
188 RTC_DCHECK(relay_port_factory_ != nullptr);
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700189 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0,
190 webrtc::NO_PRUNE, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 Construct();
192}
193
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194void BasicPortAllocator::Construct() {
195 allow_tcp_listen_ = true;
196}
197
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700198void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
199 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700200 // If the session has not been taken by an active channel, do not report the
201 // metric.
202 for (auto& allocator_session : pooled_sessions()) {
203 if (allocator_session.get() == session) {
204 return;
205 }
206 }
207
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700208 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
209 static_cast<int>(reason),
210 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700211}
212
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700214 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800215 // Our created port allocator sessions depend on us, so destroy our remaining
216 // pooled sessions before anything else.
217 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218}
219
Steve Anton7995d8c2017-10-30 16:23:38 -0700220void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
221 // TODO(phoglund): implement support for other types than loopback.
222 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
223 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700224 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700225 network_ignore_mask_ = network_ignore_mask;
226}
227
deadbeefc5d0d952015-07-16 10:22:21 -0700228PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200229 const std::string& content_name,
230 int component,
231 const std::string& ice_ufrag,
232 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700233 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700234 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700236 session->SignalIceRegathering.connect(this,
237 &BasicPortAllocator::OnIceRegathering);
238 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239}
240
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700241void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700242 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700243 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
244 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700245 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700246 turn_port_prune_policy(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700247}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000248
Jonas Oreland202994c2017-12-18 12:10:43 +0100249void BasicPortAllocator::InitRelayPortFactory(
250 RelayPortFactoryInterface* relay_port_factory) {
251 if (relay_port_factory != nullptr) {
252 relay_port_factory_ = relay_port_factory;
253 } else {
254 default_relay_port_factory_.reset(new TurnPortFactory());
255 relay_port_factory_ = default_relay_port_factory_.get();
256 }
257}
258
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000259// BasicPortAllocatorSession
260BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700261 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262 const std::string& content_name,
263 int component,
264 const std::string& ice_ufrag,
265 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700266 : PortAllocatorSession(content_name,
267 component,
268 ice_ufrag,
269 ice_pwd,
270 allocator->flags()),
271 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700272 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273 socket_factory_(allocator->socket_factory()),
274 allocation_started_(false),
275 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700276 allocation_sequences_created_(false),
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700277 turn_port_prune_policy_(allocator->turn_port_prune_policy()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000278 allocator_->network_manager()->SignalNetworksChanged.connect(
279 this, &BasicPortAllocatorSession::OnNetworksChanged);
280 allocator_->network_manager()->StartUpdating();
281}
282
283BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700284 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000286 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 network_thread_->Clear(this);
288
Peter Boström0c4e06b2015-10-07 12:23:21 +0200289 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290 // AllocationSequence should clear it's map entry for turn ports before
291 // ports are destroyed.
292 sequences_[i]->Clear();
293 }
294
295 std::vector<PortData>::iterator it;
296 for (it = ports_.begin(); it != ports_.end(); it++)
297 delete it->port();
298
Peter Boström0c4e06b2015-10-07 12:23:21 +0200299 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000300 delete configs_[i];
301
Peter Boström0c4e06b2015-10-07 12:23:21 +0200302 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000303 delete sequences_[i];
304}
305
Steve Anton7995d8c2017-10-30 16:23:38 -0700306BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700307 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700308 return allocator_;
309}
310
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700311void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700312 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700313 if (filter == candidate_filter_) {
314 return;
315 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700316 uint32_t prev_filter = candidate_filter_;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700317 candidate_filter_ = filter;
Qingsi Wangc129c352019-04-18 10:41:58 -0700318 for (PortData& port_data : ports_) {
319 if (port_data.error() || port_data.pruned()) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700320 continue;
321 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700322 PortData::State cur_state = port_data.state();
323 bool found_signalable_candidate = false;
324 bool found_pairable_candidate = false;
325 cricket::Port* port = port_data.port();
326 for (const auto& c : port->Candidates()) {
327 if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) &&
328 IsAllowedByCandidateFilter(c, filter)) {
329 // This candidate was not signaled because of not matching the previous
330 // filter (see OnCandidateReady below). Let the Port to fire the signal
331 // again.
332 //
333 // Note that
334 // 1) we would need the Port to enter the state of in-progress of
335 // gathering to have candidates signaled;
336 //
337 // 2) firing the signal would also let the session set the port ready
338 // if needed, so that we could form candidate pairs with candidates
339 // from this port;
340 //
341 // * See again OnCandidateReady below for 1) and 2).
342 //
343 // 3) we only try to resurface candidates if we have not stopped
344 // getting ports, which is always true for the continual gathering.
345 if (!found_signalable_candidate) {
346 found_signalable_candidate = true;
347 port_data.set_state(PortData::STATE_INPROGRESS);
348 }
349 port->SignalCandidateReady(port, c);
350 }
351
352 if (CandidatePairable(c, port)) {
353 found_pairable_candidate = true;
354 }
355 }
356 // Restore the previous state.
357 port_data.set_state(cur_state);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700358 // Setting a filter may cause a ready port to become non-ready
359 // if it no longer has any pairable candidates.
Qingsi Wangc129c352019-04-18 10:41:58 -0700360 //
361 // Note that we only set for the negative case here, since a port would be
362 // set to have pairable candidates when it signals a ready candidate, which
363 // requires the port is still in the progress of gathering/surfacing
364 // candidates, and would be done in the firing of the signal above.
365 if (!found_pairable_candidate) {
366 port_data.set_has_pairable_candidate(false);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700367 }
368 }
369}
370
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000371void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700372 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700373 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000374 if (!socket_factory_) {
375 owned_socket_factory_.reset(
376 new rtc::BasicPacketSocketFactory(network_thread_));
377 socket_factory_ = owned_socket_factory_.get();
378 }
379
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700380 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700381
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700382 RTC_LOG(LS_INFO) << "Start getting ports with turn_port_prune_policy "
383 << turn_port_prune_policy_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000384}
385
386void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700387 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700388 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700389 // Note: this must be called after ClearGettingPorts because both may set the
390 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700391 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700392}
393
394void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700395 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700397 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700399 }
deadbeefb60a8192016-08-24 15:15:00 -0700400 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700401 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700402}
403
Steve Anton7995d8c2017-10-30 16:23:38 -0700404bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700405 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700406 return state_ == SessionState::GATHERING;
407}
408
409bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700410 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700411 return state_ == SessionState::CLEARED;
412}
413
414bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700415 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700416 return state_ == SessionState::STOPPED;
417}
418
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700419std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700420 RTC_DCHECK_RUN_ON(network_thread_);
421
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700422 std::vector<rtc::Network*> networks = GetNetworks();
423
424 // A network interface may have both IPv4 and IPv6 networks. Only if
425 // neither of the networks has any connections, the network interface
426 // is considered failed and need to be regathered on.
427 std::set<std::string> networks_with_connection;
428 for (const PortData& data : ports_) {
429 Port* port = data.port();
430 if (!port->connections().empty()) {
431 networks_with_connection.insert(port->Network()->name());
432 }
433 }
434
435 networks.erase(
436 std::remove_if(networks.begin(), networks.end(),
437 [networks_with_connection](rtc::Network* network) {
438 // If a network does not have any connection, it is
439 // considered failed.
440 return networks_with_connection.find(network->name()) !=
441 networks_with_connection.end();
442 }),
443 networks.end());
444 return networks;
445}
446
447void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700448 RTC_DCHECK_RUN_ON(network_thread_);
449
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700450 // Find the list of networks that have no connection.
451 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
452 if (failed_networks.empty()) {
453 return;
454 }
455
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700457
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700458 // Mark a sequence as "network failed" if its network is in the list of failed
459 // networks, so that it won't be considered as equivalent when the session
460 // regathers ports and candidates.
461 for (AllocationSequence* sequence : sequences_) {
462 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800463 absl::c_linear_search(failed_networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700464 sequence->set_network_failed();
465 }
466 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700467
468 bool disable_equivalent_phases = true;
469 Regather(failed_networks, disable_equivalent_phases,
470 IceRegatheringReason::NETWORK_FAILURE);
471}
472
473void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700474 RTC_DCHECK_RUN_ON(network_thread_);
475
Steve Anton300bf8e2017-07-14 10:13:10 -0700476 std::vector<rtc::Network*> networks = GetNetworks();
477 if (networks.empty()) {
478 return;
479 }
480
Mirko Bonadei675513b2017-11-09 11:09:25 +0100481 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700482
483 // We expect to generate candidates that are equivalent to what we have now.
484 // Force DoAllocate to generate them instead of skipping.
485 bool disable_equivalent_phases = false;
486 Regather(networks, disable_equivalent_phases,
487 IceRegatheringReason::OCCASIONAL_REFRESH);
488}
489
490void BasicPortAllocatorSession::Regather(
491 const std::vector<rtc::Network*>& networks,
492 bool disable_equivalent_phases,
493 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700494 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700495 // Remove ports from being used locally and send signaling to remove
496 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700497 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700498 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000500 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700501 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700502
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700503 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700504 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700505
Steve Anton300bf8e2017-07-14 10:13:10 -0700506 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700507 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508}
509
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700510void BasicPortAllocatorSession::GetCandidateStatsFromReadyPorts(
511 CandidateStatsList* candidate_stats_list) const {
512 auto ports = ReadyPorts();
513 for (auto* port : ports) {
514 auto candidates = port->Candidates();
515 for (const auto& candidate : candidates) {
516 CandidateStats candidate_stats(allocator_->SanitizeCandidate(candidate));
517 port->GetStunStats(&candidate_stats.stun_stats);
518 candidate_stats_list->push_back(std::move(candidate_stats));
519 }
520 }
521}
522
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800523void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200524 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700525 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800526 auto ports = ReadyPorts();
527 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800528 // The port type and protocol can be used to identify different subclasses
529 // of Port in the current implementation. Note that a TCPPort has the type
530 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
531 if (port->Type() == STUN_PORT_TYPE ||
532 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800533 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
534 stun_keepalive_interval);
535 }
536 }
537}
538
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700539std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700540 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700541 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700542 for (const PortData& data : ports_) {
543 if (data.ready()) {
544 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700545 }
546 }
547 return ret;
548}
549
550std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700551 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700552 std::vector<Candidate> candidates;
553 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700554 if (!data.ready()) {
555 continue;
556 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700557 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700558 }
559 return candidates;
560}
561
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700562void BasicPortAllocatorSession::GetCandidatesFromPort(
563 const PortData& data,
564 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700565 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700566 RTC_CHECK(candidates != nullptr);
567 for (const Candidate& candidate : data.port()->Candidates()) {
568 if (!CheckCandidateFilter(candidate)) {
569 continue;
570 }
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700571 candidates->push_back(allocator_->SanitizeCandidate(candidate));
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700572 }
573}
574
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700575bool BasicPortAllocator::MdnsObfuscationEnabled() const {
576 return network_manager()->GetMdnsResponder() != nullptr;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700577}
578
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700579bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700580 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700581 // Done only if all required AllocationSequence objects
582 // are created.
583 if (!allocation_sequences_created_) {
584 return false;
585 }
586
587 // Check that all port allocation sequences are complete (not running).
Steve Antonae226f62019-01-29 12:47:38 -0800588 if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
589 return sequence->state() == AllocationSequence::kRunning;
590 })) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700591 return false;
592 }
593
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700594 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700595 // expected candidates. Session will trigger candidates allocation complete
596 // signal.
Steve Antonae226f62019-01-29 12:47:38 -0800597 return absl::c_none_of(
598 ports_, [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700599}
600
Yves Gerey665174f2018-06-19 15:03:05 +0200601void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200603 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200604 GetPortConfigurations();
605 break;
606 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200607 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
608 break;
609 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200610 OnAllocate();
611 break;
612 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200613 OnAllocationSequenceObjectsCreated();
614 break;
615 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200616 OnConfigStop();
617 break;
618 default:
619 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000620 }
621}
622
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700623void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700624 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700625 for (PortData& port : ports_) {
626 port.port()->set_content_name(content_name());
627 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
628 }
629}
630
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700632 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangc129c352019-04-18 10:41:58 -0700633
Yves Gerey665174f2018-06-19 15:03:05 +0200634 PortConfiguration* config =
635 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636
deadbeef653b8e02015-11-11 12:55:10 -0800637 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
638 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 }
640 ConfigReady(config);
641}
642
643void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700644 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700645 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646}
647
648// Adds a configuration to the list.
649void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700650 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800651 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000652 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800653 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000654
655 AllocatePorts();
656}
657
658void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700659 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660
661 // If any of the allocated ports have not completed the candidates allocation,
662 // mark those as error. Since session doesn't need any new candidates
663 // at this stage of the allocation, it's safe to discard any new candidates.
664 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200665 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
666 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700667 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000668 // Updating port state to error, which didn't finish allocating candidates
669 // yet.
Qingsi Wangc129c352019-04-18 10:41:58 -0700670 it->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000671 send_signal = true;
672 }
673 }
674
675 // Did we stop any running sequences?
676 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
677 it != sequences_.end() && !send_signal; ++it) {
678 if ((*it)->state() == AllocationSequence::kStopped) {
679 send_signal = true;
680 }
681 }
682
683 // If we stopped anything that was running, send a done signal now.
684 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000685 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000686 }
687}
688
689void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700690 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700691 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000692}
693
694void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700695 RTC_DCHECK_RUN_ON(network_thread_);
696
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 if (network_manager_started_ && !IsStopped()) {
698 bool disable_equivalent_phases = true;
699 DoAllocate(disable_equivalent_phases);
700 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000701
702 allocation_started_ = true;
703}
704
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700705std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700706 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700707 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700708 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800709 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700710 // If the network permission state is BLOCKED, we just act as if the flag has
711 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700712 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700713 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700714 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
715 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000716 // If the adapter enumeration is disabled, we'll just bind to any address
717 // instead of specific NIC. This is to ensure the same routing for http
718 // traffic by OS is also used here to avoid any local or public IP leakage
719 // during stun process.
720 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
721 network_manager->GetAnyAddressNetworks(&networks);
722 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700723 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000724 // If network enumeration fails, use the ANY address as a fallback, so we
725 // can at least try gathering candidates using the default route chosen by
726 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
727 // set, we'll use ANY address candidates either way.
728 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
729 network_manager->GetAnyAddressNetworks(&networks);
730 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000731 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100732 // Filter out link-local networks if needed.
733 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700734 NetworkFilter link_local_filter(
735 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
736 "link-local");
737 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100738 }
deadbeef3427f532017-07-26 16:09:33 -0700739 // Do some more filtering, depending on the network ignore mask and "disable
740 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700741 NetworkFilter ignored_filter(
742 [this](rtc::Network* network) {
743 return allocator_->network_ignore_mask() & network->type();
744 },
745 "ignored");
746 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700747 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
748 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700749 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000750 // Don't determine the lowest cost from a link-local network.
751 // On iOS, a device connected to the computer will get a link-local
752 // network for communicating with the computer, however this network can't
753 // be used to connect to a peer outside the network.
754 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800755 continue;
756 }
honghaiz60347052016-05-31 18:29:12 -0700757 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
758 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700759 NetworkFilter costly_filter(
760 [lowest_cost](rtc::Network* network) {
761 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
762 },
763 "costly");
764 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700765 }
deadbeef3427f532017-07-26 16:09:33 -0700766 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
767 // default, it's 5), remove networks to ensure that limit is satisfied.
768 //
769 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
770 // networks, we could try to choose a set that's "most likely to work". It's
771 // hard to define what that means though; it's not just "lowest cost".
772 // Alternatively, we could just focus on making our ICE pinging logic smarter
773 // such that this filtering isn't necessary in the first place.
774 int ipv6_networks = 0;
775 for (auto it = networks.begin(); it != networks.end();) {
776 if ((*it)->prefix().family() == AF_INET6) {
777 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
778 it = networks.erase(it);
779 continue;
780 } else {
781 ++ipv6_networks;
782 }
783 }
784 ++it;
785 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700786 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700787}
788
789// For each network, see if we have a sequence that covers it already. If not,
790// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700791void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700792 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700793 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700794 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000795 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100796 RTC_LOG(LS_WARNING)
797 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000798 done_signal_needed = true;
799 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100800 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700801 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200802 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200803 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000804 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
805 // If all the ports are disabled we should just fire the allocation
806 // done event and return.
807 done_signal_needed = true;
808 break;
809 }
810
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000811 if (!config || config->relays.empty()) {
812 // No relay ports specified in this config.
813 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
814 }
815
816 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000817 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 // Skip IPv6 networks unless the flag's been set.
819 continue;
820 }
821
zhihuangb09b3f92017-03-07 14:40:51 -0800822 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
823 networks[i]->GetBestIP().family() == AF_INET6 &&
824 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
825 // Skip IPv6 Wi-Fi networks unless the flag's been set.
826 continue;
827 }
828
Steve Anton300bf8e2017-07-14 10:13:10 -0700829 if (disable_equivalent) {
830 // Disable phases that would only create ports equivalent to
831 // ones that we have already made.
832 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833
Steve Anton300bf8e2017-07-14 10:13:10 -0700834 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
835 // New AllocationSequence would have nothing to do, so don't make it.
836 continue;
837 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000838 }
839
840 AllocationSequence* sequence =
841 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842 sequence->SignalPortAllocationComplete.connect(
843 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700844 sequence->Init();
845 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700847 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848 }
849 }
850 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700851 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 }
853}
854
855void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700856 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700857 std::vector<rtc::Network*> networks = GetNetworks();
858 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700859 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700860 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700861 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700862 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800863 !absl::c_linear_search(networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700864 sequence->OnNetworkFailed();
865 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700866 }
867 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700868 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
869 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100870 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
871 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000872 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700873 }
honghaiz8c404fa2015-09-28 07:59:43 -0700874
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700875 if (allocation_started_ && !IsStopped()) {
876 if (network_manager_started_) {
877 // If the network manager has started, it must be regathering.
878 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
879 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700880 bool disable_equivalent_phases = true;
881 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700882 }
883
Honghai Zhang5048f572016-08-23 15:47:33 -0700884 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100885 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700886 network_manager_started_ = true;
887 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888}
889
890void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200891 rtc::Network* network,
892 PortConfiguration* config,
893 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700894 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200895 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200896 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200897 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 sequences_[i]->DisableEquivalentPhases(network, config, flags);
899 }
900}
901
902void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200903 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700905 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 if (!port)
907 return;
908
Mirko Bonadei675513b2017-11-09 11:09:25 +0100909 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700911 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000912 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700913 if (allocator_->proxy().type != rtc::PROXY_NONE)
914 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700915 port->set_send_retransmit_count_attribute(
916 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 PortData data(port, seq);
919 ports_.push_back(data);
920
921 port->SignalCandidateReady.connect(
922 this, &BasicPortAllocatorSession::OnCandidateReady);
Eldar Relloda13ea22019-06-01 12:23:43 +0300923 port->SignalCandidateError.connect(
924 this, &BasicPortAllocatorSession::OnCandidateError);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000925 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200926 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200928 &BasicPortAllocatorSession::OnPortDestroyed);
929 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
930 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000931
932 if (prepare_address)
933 port->PrepareAddress();
934}
935
936void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700937 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000938 allocation_sequences_created_ = true;
939 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000940 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941}
942
Yves Gerey665174f2018-06-19 15:03:05 +0200943void BasicPortAllocatorSession::OnCandidateReady(Port* port,
944 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700945 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000947 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200948 RTC_LOG(LS_INFO) << port->ToString()
949 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000950 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700951 // already done with gathering.
952 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100953 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700954 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700955 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700956 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700957
danilchapf4e8cf02016-06-30 01:55:03 -0700958 // Mark that the port has a pairable candidate, either because we have a
959 // usable candidate from the port, or simply because the port is bound to the
960 // any address and therefore has no host candidate. This will trigger the port
961 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700962 // checks. If port has already been marked as having a pairable candidate,
963 // do nothing here.
964 // Note: We should check whether any candidates may become ready after this
965 // because there we will check whether the candidate is generated by the ready
966 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700967 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700968 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700969 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700970
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700971 if (port->Type() == RELAY_PORT_TYPE) {
972 if (turn_port_prune_policy_ == webrtc::KEEP_FIRST_READY) {
973 pruned = PruneNewlyPairableTurnPort(data);
974 } else if (turn_port_prune_policy_ == webrtc::PRUNE_BASED_ON_PRIORITY) {
975 pruned = PruneTurnPorts(port);
976 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700977 }
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700978
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700979 // If the current port is not pruned yet, SignalPortReady.
980 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000981 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
982 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700983 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700984 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700985 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700986
deadbeef1c5e6d02017-09-15 17:46:56 -0700987 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000988 std::vector<Candidate> candidates;
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700989 candidates.push_back(allocator_->SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000990 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700991 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100992 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700993 }
994
995 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700996 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000997 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700998 }
999}
1000
Eldar Relloda13ea22019-06-01 12:23:43 +03001001void BasicPortAllocatorSession::OnCandidateError(
1002 Port* port,
1003 const IceCandidateErrorEvent& event) {
1004 RTC_DCHECK_RUN_ON(network_thread_);
1005 RTC_DCHECK(FindPort(port));
1006
1007 SignalCandidateError(this, event);
1008}
1009
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001010Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
1011 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -07001012 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001013 Port* best_turn_port = nullptr;
1014 for (const PortData& data : ports_) {
1015 if (data.port()->Network()->name() == network_name &&
1016 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1017 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
1018 best_turn_port = data.port();
1019 }
1020 }
1021 return best_turn_port;
1022}
1023
Honghai Zhangf8998cf2019-10-14 11:27:50 -07001024bool BasicPortAllocatorSession::PruneNewlyPairableTurnPort(
1025 PortData* newly_pairable_port_data) {
1026 RTC_DCHECK_RUN_ON(network_thread_);
1027 RTC_DCHECK(newly_pairable_port_data->port()->Type() == RELAY_PORT_TYPE);
1028 // If an existing turn port is ready on the same network, prune the newly
1029 // pairable port.
1030 const std::string& network_name =
1031 newly_pairable_port_data->port()->Network()->name();
1032
1033 for (PortData& data : ports_) {
1034 if (data.port()->Network()->name() == network_name &&
1035 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1036 &data != newly_pairable_port_data) {
1037 RTC_LOG(LS_INFO) << "Port pruned: "
1038 << newly_pairable_port_data->port()->ToString();
1039 newly_pairable_port_data->Prune();
1040 return true;
1041 }
1042 }
1043 return false;
1044}
1045
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001046bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -07001047 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001048 // Note: We determine the same network based only on their network names. So
1049 // if an IPv4 address and an IPv6 address have the same network name, they
1050 // are considered the same network here.
1051 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1052 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1053 // |port| is already in the list of ports, so the best port cannot be nullptr.
1054 RTC_CHECK(best_turn_port != nullptr);
1055
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001056 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001057 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001058 for (PortData& data : ports_) {
1059 if (data.port()->Network()->name() == network_name &&
1060 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1061 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001062 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001063 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001064 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001065 ports_to_prune.push_back(&data);
1066 } else {
1067 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001068 }
1069 }
1070 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001071
1072 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001073 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1074 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001075 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001076 }
1077 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001078}
1079
Honghai Zhanga74363c2016-07-28 18:06:15 -07001080void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001081 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001082 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001083 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001084 }
1085}
1086
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001087void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001088 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001089 RTC_LOG(LS_INFO) << port->ToString()
1090 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001091 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001092 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093
1094 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001095 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001096 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001097 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001098
1099 // Moving to COMPLETE state.
Qingsi Wangc129c352019-04-18 10:41:58 -07001100 data->set_state(PortData::STATE_COMPLETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001101 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001102 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001103}
1104
1105void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001106 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001107 RTC_LOG(LS_INFO) << port->ToString()
1108 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001110 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001112 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001113 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001114 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001115
1116 // SignalAddressError is currently sent from StunPort/TurnPort.
1117 // But this signal itself is generic.
Qingsi Wangc129c352019-04-18 10:41:58 -07001118 data->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001119 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001120 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121}
1122
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001123bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001124 RTC_DCHECK_RUN_ON(network_thread_);
1125
Qingsi Wangc129c352019-04-18 10:41:58 -07001126 return IsAllowedByCandidateFilter(c, candidate_filter_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001127}
1128
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001129bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1130 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001131 RTC_DCHECK_RUN_ON(network_thread_);
1132
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001133 bool candidate_signalable = CheckCandidateFilter(c);
1134
1135 // When device enumeration is disabled (to prevent non-default IP addresses
1136 // from leaking), we ping from some local candidates even though we don't
1137 // signal them. However, if host candidates are also disabled (for example, to
1138 // prevent even default IP addresses from leaking), we still don't want to
1139 // ping from them, even if device enumeration is disabled. Thus, we check for
1140 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001141 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001142 bool can_ping_from_candidate =
1143 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1144 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1145
1146 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001147 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001148 !host_candidates_disabled);
1149}
1150
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001151void BasicPortAllocatorSession::OnPortAllocationComplete(
1152 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001153 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001155 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001156}
1157
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001158void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001159 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001160 if (CandidatesAllocationDone()) {
1161 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001162 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001163 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001164 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1165 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001166 }
1167 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169}
1170
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001171void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001172 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001173 for (std::vector<PortData>::iterator iter = ports_.begin();
1174 iter != ports_.end(); ++iter) {
1175 if (port == iter->port()) {
1176 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001177 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001178 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001179 return;
1180 }
1181 }
nissec80e7412017-01-11 05:56:46 -08001182 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001183}
1184
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001185BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1186 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001187 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001188 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1189 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001190 if (it->port() == port) {
1191 return &*it;
1192 }
1193 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001194 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001195}
1196
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001197std::vector<BasicPortAllocatorSession::PortData*>
1198BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001199 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001200 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001201 std::vector<PortData*> unpruned_ports;
1202 for (PortData& port : ports_) {
1203 if (!port.pruned() &&
Steve Antonae226f62019-01-29 12:47:38 -08001204 absl::c_linear_search(networks, port.sequence()->network())) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001205 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001206 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001207 }
1208 return unpruned_ports;
1209}
1210
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001211void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001212 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001213 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001214 std::vector<PortInterface*> pruned_ports;
1215 std::vector<Candidate> removed_candidates;
1216 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001217 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001218 data->Prune();
1219 pruned_ports.push_back(data->port());
1220 if (data->has_pairable_candidate()) {
1221 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001222 // Mark the port as having no pairable candidates so that its candidates
1223 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001224 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001225 }
1226 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001227 if (!pruned_ports.empty()) {
1228 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001229 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001230 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001231 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1232 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001233 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001234 }
1235}
1236
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237// AllocationSequence
1238
1239AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1240 rtc::Network* network,
1241 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001242 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243 : session_(session),
1244 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001245 config_(config),
1246 state_(kInit),
1247 flags_(flags),
1248 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001249 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001250 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001251
Honghai Zhang5048f572016-08-23 15:47:33 -07001252void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1254 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001255 rtc::SocketAddress(network_->GetBestIP(), 0),
1256 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001257 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001258 udp_socket_->SignalReadPacket.connect(this,
1259 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001260 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001261 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1262 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001263 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001264}
1265
1266void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001267 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001268 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001269}
1270
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001271void AllocationSequence::OnNetworkFailed() {
1272 RTC_DCHECK(!network_failed_);
1273 network_failed_ = true;
1274 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001275 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001276}
1277
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001278AllocationSequence::~AllocationSequence() {
1279 session_->network_thread()->Clear(this);
1280}
1281
1282void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001283 PortConfiguration* config,
1284 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001285 if (network_failed_) {
1286 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001287 // it won't be equivalent to the new network.
1288 return;
1289 }
1290
deadbeef5c3c1042017-08-04 15:01:57 -07001291 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001292 // Different network setup; nothing is equivalent.
1293 return;
1294 }
1295
1296 // Else turn off the stuff that we've already got covered.
1297
deadbeef1c46a352017-09-27 11:24:05 -07001298 // Every config implicitly specifies local, so turn that off right away if we
1299 // already have a port of the corresponding type. Look for a port that
1300 // matches this AllocationSequence's network, is the right protocol, and
1301 // hasn't encountered an error.
1302 // TODO(deadbeef): This doesn't take into account that there may be another
1303 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1304 // This can happen if, say, there's a network change event right before an
1305 // application-triggered ICE restart. Hopefully this problem will just go
1306 // away if we get rid of the gathering "phases" though, which is planned.
Qingsi Wangc129c352019-04-18 10:41:58 -07001307 //
1308 //
1309 // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1310 // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1311 // to disable the gathering of these candidates just becaue of an existing
1312 // Port over PROTO_UDP, namely a TurnPort over UDP.
Steve Antonae226f62019-01-29 12:47:38 -08001313 if (absl::c_any_of(session_->ports_,
1314 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001315 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001316 p.port()->GetProtocol() == PROTO_UDP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001317 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001318 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001319 *flags |= PORTALLOCATOR_DISABLE_UDP;
1320 }
Qingsi Wangc129c352019-04-18 10:41:58 -07001321 // Similarly we need to check both the protocol used by an existing Port and
1322 // its type.
Steve Antonae226f62019-01-29 12:47:38 -08001323 if (absl::c_any_of(session_->ports_,
1324 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001325 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001326 p.port()->GetProtocol() == PROTO_TCP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001327 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001328 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001329 *flags |= PORTALLOCATOR_DISABLE_TCP;
1330 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001331
1332 if (config_ && config) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001333 // We need to regather srflx candidates if either of the following
1334 // conditions occurs:
1335 // 1. The STUN servers are different from the previous gathering.
1336 // 2. We will regather host candidates, hence possibly inducing new NAT
1337 // bindings.
1338 if (config_->StunServers() == config->StunServers() &&
1339 (*flags & PORTALLOCATOR_DISABLE_UDP)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001340 // Already got this STUN servers covered.
1341 *flags |= PORTALLOCATOR_DISABLE_STUN;
1342 }
1343 if (!config_->relays.empty()) {
1344 // Already got relays covered.
1345 // NOTE: This will even skip a _different_ set of relay servers if we
1346 // were to be given one, but that never happens in our codebase. Should
1347 // probably get rid of the list in PortConfiguration and just keep a
1348 // single relay server in each one.
1349 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1350 }
1351 }
1352}
1353
1354void AllocationSequence::Start() {
1355 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001356 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001357 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1358 // called next time, we enable all phases if the best IP has since changed.
1359 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001360}
1361
1362void AllocationSequence::Stop() {
1363 // If the port is completed, don't set it to stopped.
1364 if (state_ == kRunning) {
1365 state_ = kStopped;
1366 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1367 }
1368}
1369
1370void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001371 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1372 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001373
deadbeef1c5e6d02017-09-15 17:46:56 -07001374 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001375
1376 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001377 RTC_LOG(LS_INFO) << network_->ToString()
1378 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379
1380 switch (phase_) {
1381 case PHASE_UDP:
1382 CreateUDPPorts();
1383 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 break;
1385
1386 case PHASE_RELAY:
1387 CreateRelayPorts();
1388 break;
1389
1390 case PHASE_TCP:
1391 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001392 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001393 break;
1394
1395 default:
nissec80e7412017-01-11 05:56:46 -08001396 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001397 }
1398
1399 if (state() == kRunning) {
1400 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001401 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1402 session_->allocator()->step_delay(),
1403 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001404 } else {
1405 // If all phases in AllocationSequence are completed, no allocation
1406 // steps needed further. Canceling pending signal.
1407 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1408 SignalPortAllocationComplete(this);
1409 }
1410}
1411
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412void AllocationSequence::CreateUDPPorts() {
1413 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001414 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001415 return;
1416 }
1417
1418 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1419 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001420 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001421 bool emit_local_candidate_for_anyaddress =
1422 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001423 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001424 port = UDPPort::Create(
1425 session_->network_thread(), session_->socket_factory(), network_,
1426 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001427 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1428 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001430 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001431 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001432 session_->allocator()->min_port(), session_->allocator()->max_port(),
1433 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001434 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1435 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001436 }
1437
1438 if (port) {
1439 // If shared socket is enabled, STUN candidate will be allocated by the
1440 // UDPPort.
1441 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001442 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001443 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001444
1445 // If STUN is not disabled, setting stun server address to port.
1446 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001447 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001448 RTC_LOG(LS_INFO)
1449 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001450 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001451 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001452 }
1453 }
1454 }
1455
Steve Antona8f1e562018-10-10 11:29:44 -07001456 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457 }
1458}
1459
1460void AllocationSequence::CreateTCPPorts() {
1461 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001462 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463 return;
1464 }
1465
Steve Antona8f1e562018-10-10 11:29:44 -07001466 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001467 session_->network_thread(), session_->socket_factory(), network_,
1468 session_->allocator()->min_port(), session_->allocator()->max_port(),
1469 session_->username(), session_->password(),
1470 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001471 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001472 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001473 // Since TCPPort is not created using shared socket, |port| will not be
1474 // added to the dequeue.
1475 }
1476}
1477
1478void AllocationSequence::CreateStunPorts() {
1479 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001480 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001481 return;
1482 }
1483
1484 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1485 return;
1486 }
1487
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001488 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001489 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001490 << "AllocationSequence: No STUN server configured, skipping.";
1491 return;
1492 }
1493
Steve Antona8f1e562018-10-10 11:29:44 -07001494 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001495 session_->network_thread(), session_->socket_factory(), network_,
1496 session_->allocator()->min_port(), session_->allocator()->max_port(),
1497 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001498 session_->allocator()->origin(),
1499 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001500 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001501 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001502 // Since StunPort is not created using shared socket, |port| will not be
1503 // added to the dequeue.
1504 }
1505}
1506
1507void AllocationSequence::CreateRelayPorts() {
1508 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001509 RTC_LOG(LS_VERBOSE)
1510 << "AllocationSequence: Relay ports disabled, skipping.";
1511 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001512 }
1513
1514 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1515 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001516 RTC_DCHECK(config_);
1517 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001518 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001519 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001520 << "AllocationSequence: No relay server configured, skipping.";
1521 return;
1522 }
1523
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001524 for (RelayServerConfig& relay : config_->relays) {
1525 if (relay.type == RELAY_GTURN) {
1526 CreateGturnPort(relay);
1527 } else if (relay.type == RELAY_TURN) {
1528 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001529 } else {
nissec80e7412017-01-11 05:56:46 -08001530 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001531 }
1532 }
1533}
1534
1535void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1536 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001537 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001538 session_->network_thread(), session_->socket_factory(), network_,
1539 session_->allocator()->min_port(), session_->allocator()->max_port(),
1540 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001541 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001542 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001543 // Since RelayPort is not created using shared socket, |port| will not be
1544 // added to the dequeue.
1545 // Note: We must add the allocated port before we add addresses because
1546 // the latter will create candidates that need name and preference
1547 // settings. However, we also can't prepare the address (normally
1548 // done by AddAllocatedPort) until we have these addresses. So we
1549 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001550 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001551
1552 // Add the addresses of this protocol.
1553 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001554 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001555 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001556 port_ptr->AddServerAddress(*relay_port);
1557 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001558 }
1559 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001560 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001561 }
1562}
1563
1564void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1565 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001566 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1567 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001568 // Skip UDP connections to relay servers if it's disallowed.
1569 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1570 relay_port->proto == PROTO_UDP) {
1571 continue;
1572 }
1573
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001574 // Do not create a port if the server address family is known and does
1575 // not match the local IP address family.
1576 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001577 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001578 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001579 RTC_LOG(LS_INFO)
1580 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001581 "Server address: "
Qingsi Wang20232a92019-09-06 12:51:17 -07001582 << relay_port->address.ipaddr().ToSensitiveString()
1583 << " Local address: " << network_->GetBestIP().ToSensitiveString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001584 continue;
1585 }
1586
Jonas Oreland202994c2017-12-18 12:10:43 +01001587 CreateRelayPortArgs args;
1588 args.network_thread = session_->network_thread();
1589 args.socket_factory = session_->socket_factory();
1590 args.network = network_;
1591 args.username = session_->username();
1592 args.password = session_->password();
1593 args.server_address = &(*relay_port);
1594 args.config = &config;
1595 args.origin = session_->allocator()->origin();
1596 args.turn_customizer = session_->allocator()->turn_customizer();
1597
1598 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001599 // Shared socket mode must be enabled only for UDP based ports. Hence
1600 // don't pass shared socket for ports which will create TCP sockets.
1601 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1602 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1603 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001604 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001605 port = session_->allocator()->relay_port_factory()->Create(
1606 args, udp_socket_.get());
1607
1608 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001609 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
Qingsi Wang20232a92019-09-06 12:51:17 -07001610 << args.server_address->address.ToSensitiveString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001611 continue;
1612 }
1613
1614 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001615 // Listen to the port destroyed signal, to allow AllocationSequence to
1616 // remove entrt from it's map.
1617 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1618 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001619 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001620 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001621 session_->allocator()->max_port());
1622
1623 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001624 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
Qingsi Wang20232a92019-09-06 12:51:17 -07001625 << args.server_address->address.ToSensitiveString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001626 continue;
1627 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001628 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001629 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001630 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001631 }
1632}
1633
Yves Gerey665174f2018-06-19 15:03:05 +02001634void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1635 const char* data,
1636 size_t size,
1637 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001638 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001639 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001640
1641 bool turn_port_found = false;
1642
1643 // Try to find the TurnPort that matches the remote address. Note that the
1644 // message could be a STUN binding response if the TURN server is also used as
1645 // a STUN server. We don't want to parse every message here to check if it is
1646 // a STUN binding response, so we pass the message to TurnPort regardless of
1647 // the message type. The TurnPort will just ignore the message since it will
1648 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001649 for (auto* port : relay_ports_) {
1650 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001651 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001652 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001653 return;
1654 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001655 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001656 }
1657 }
1658
1659 if (udp_port_) {
1660 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1661
1662 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1663 // the TURN server is also a STUN server.
1664 if (!turn_port_found ||
1665 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001666 RTC_DCHECK(udp_port_->SharedSocket());
1667 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001668 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001669 }
1670 }
1671}
1672
1673void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1674 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001675 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001676 return;
1677 }
1678
Steve Antonae226f62019-01-29 12:47:38 -08001679 auto it = absl::c_find(relay_ports_, port);
Jonas Oreland202994c2017-12-18 12:10:43 +01001680 if (it != relay_ports_.end()) {
1681 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001682 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001683 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001684 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001685 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001686}
1687
1688// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001689PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1690 const std::string& username,
1691 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001692 : stun_address(stun_address), username(username), password(password) {
1693 if (!stun_address.IsNil())
1694 stun_servers.insert(stun_address);
1695}
1696
1697PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1698 const std::string& username,
1699 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001700 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001701 if (!stun_servers.empty())
1702 stun_address = *(stun_servers.begin());
Honghai Zhang6981fb52019-10-29 12:45:34 -07001703 // Note that this won't change once the config is initialized.
1704 use_turn_server_as_stun_server_disabled =
1705 webrtc::field_trial::IsDisabled("WebRTC-UseTurnServerAsStunServer");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001706}
1707
Steve Anton7995d8c2017-10-30 16:23:38 -07001708PortConfiguration::~PortConfiguration() = default;
1709
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001710ServerAddresses PortConfiguration::StunServers() {
1711 if (!stun_address.IsNil() &&
1712 stun_servers.find(stun_address) == stun_servers.end()) {
1713 stun_servers.insert(stun_address);
1714 }
Honghai Zhang6981fb52019-10-29 12:45:34 -07001715
1716 if (!stun_servers.empty() && use_turn_server_as_stun_server_disabled) {
1717 return stun_servers;
1718 }
1719
1720 // Every UDP TURN server should also be used as a STUN server if
1721 // use_turn_server_as_stun_server is not disabled or the stun servers are
1722 // empty.
deadbeefc5d0d952015-07-16 10:22:21 -07001723 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1724 for (const rtc::SocketAddress& turn_server : turn_servers) {
1725 if (stun_servers.find(turn_server) == stun_servers.end()) {
1726 stun_servers.insert(turn_server);
1727 }
1728 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001729 return stun_servers;
1730}
1731
1732void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1733 relays.push_back(config);
1734}
1735
Yves Gerey665174f2018-06-19 15:03:05 +02001736bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1737 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001738 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001739 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1740 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001741 if (relay_port->proto == type)
1742 return true;
1743 }
1744 return false;
1745}
1746
1747bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1748 ProtocolType type) const {
1749 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001750 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001751 return true;
1752 }
1753 return false;
1754}
1755
1756ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001757 RelayType turn_type,
1758 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001759 ServerAddresses servers;
1760 for (size_t i = 0; i < relays.size(); ++i) {
1761 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1762 servers.insert(relays[i].ports.front().address);
1763 }
1764 }
1765 return servers;
1766}
1767
1768} // namespace cricket