blob: b49e2f842bb3f603da11fea3c79c62c92166f42e [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "p2p/client/basic_port_allocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
Qingsi Wang10a0e512018-05-16 13:37:03 -070014#include <functional>
Steve Anton6c38cc72017-11-29 10:25:58 -080015#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <string>
Qingsi Wang7627fdd2019-08-19 16:07:40 -070017#include <utility>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000018#include <vector>
19
Steve Antonae226f62019-01-29 12:47:38 -080020#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "p2p/base/basic_packet_socket_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "p2p/base/port.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "p2p/base/relay_port.h"
24#include "p2p/base/stun_port.h"
25#include "p2p/base/tcp_port.h"
26#include "p2p/base/turn_port.h"
27#include "p2p/base/udp_port.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
29#include "rtc_base/helpers.h"
30#include "rtc_base/logging.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070031#include "system_wrappers/include/metrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000034
Qingsi Wangc129c352019-04-18 10:41:58 -070035namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036namespace {
37
38enum {
39 MSG_CONFIG_START,
40 MSG_CONFIG_READY,
41 MSG_ALLOCATE,
42 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000043 MSG_SEQUENCEOBJECTS_CREATED,
44 MSG_CONFIG_STOP,
45};
46
47const int PHASE_UDP = 0;
48const int PHASE_RELAY = 1;
49const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050
deadbeef1c5e6d02017-09-15 17:46:56 -070051const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052
zhihuang696f8ca2017-06-27 15:11:24 -070053// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070054int GetProtocolPriority(cricket::ProtocolType protocol) {
55 switch (protocol) {
56 case cricket::PROTO_UDP:
57 return 2;
58 case cricket::PROTO_TCP:
59 return 1;
60 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070061 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070062 return 0;
63 default:
nisseeb4ca4e2017-01-12 02:24:27 -080064 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070065 return 0;
66 }
67}
68// Gets address family priority: IPv6 > IPv4 > Unspecified.
69int GetAddressFamilyPriority(int ip_family) {
70 switch (ip_family) {
71 case AF_INET6:
72 return 2;
73 case AF_INET:
74 return 1;
75 default:
nisseeb4ca4e2017-01-12 02:24:27 -080076 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070077 return 0;
78 }
79}
80
81// Returns positive if a is better, negative if b is better, and 0 otherwise.
82int ComparePort(const cricket::Port* a, const cricket::Port* b) {
83 int a_protocol = GetProtocolPriority(a->GetProtocol());
84 int b_protocol = GetProtocolPriority(b->GetProtocol());
85 int cmp_protocol = a_protocol - b_protocol;
86 if (cmp_protocol != 0) {
87 return cmp_protocol;
88 }
89
90 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
91 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
92 return a_family - b_family;
93}
94
Qingsi Wang10a0e512018-05-16 13:37:03 -070095struct NetworkFilter {
96 using Predicate = std::function<bool(rtc::Network*)>;
97 NetworkFilter(Predicate pred, const std::string& description)
98 : pred(pred), description(description) {}
99 Predicate pred;
100 const std::string description;
101};
102
103using NetworkList = rtc::NetworkManager::NetworkList;
104void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
105 auto start_to_remove =
106 std::remove_if(networks->begin(), networks->end(), filter.pred);
107 if (start_to_remove == networks->end()) {
108 return;
109 }
110 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
111 for (auto it = start_to_remove; it != networks->end(); ++it) {
112 RTC_LOG(INFO) << (*it)->ToString();
113 }
114 networks->erase(start_to_remove, networks->end());
115}
116
Qingsi Wangc129c352019-04-18 10:41:58 -0700117bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) {
118 // When binding to any address, before sending packets out, the getsockname
119 // returns all 0s, but after sending packets, it'll be the NIC used to
120 // send. All 0s is not a valid ICE candidate address and should be filtered
121 // out.
122 if (c.address().IsAnyIP()) {
123 return false;
124 }
125
126 if (c.type() == RELAY_PORT_TYPE) {
127 return ((filter & CF_RELAY) != 0);
128 } else if (c.type() == STUN_PORT_TYPE) {
129 return ((filter & CF_REFLEXIVE) != 0);
130 } else if (c.type() == LOCAL_PORT_TYPE) {
131 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
132 // We allow host candidates if the filter allows server-reflexive
133 // candidates and the candidate is a public IP. Because we don't generate
134 // server-reflexive candidates if they have the same IP as the host
135 // candidate (i.e. when the host candidate is a public IP), filtering to
136 // only server-reflexive candidates won't work right when the host
137 // candidates have public IPs.
138 return true;
139 }
140
141 return ((filter & CF_HOST) != 0);
142 }
143 return false;
144}
145
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146} // namespace
147
Peter Boström0c4e06b2015-10-07 12:23:21 +0200148const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700149 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
150 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151
152// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200153BasicPortAllocator::BasicPortAllocator(
154 rtc::NetworkManager* network_manager,
155 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100156 webrtc::TurnCustomizer* customizer,
157 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700158 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100159 InitRelayPortFactory(relay_port_factory);
160 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800161 RTC_DCHECK(network_manager_ != nullptr);
162 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200163 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700164 webrtc::NO_PRUNE, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 Construct();
166}
167
Yves Gerey665174f2018-06-19 15:03:05 +0200168BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700169 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100170 InitRelayPortFactory(nullptr);
171 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800172 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 Construct();
174}
175
Yves Gerey665174f2018-06-19 15:03:05 +0200176BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
Niels Möllera3baf2a2019-09-06 10:29:50 +0200177 const ServerAddresses& stun_servers)
178 : BasicPortAllocator(network_manager,
179 /*socket_factory=*/nullptr,
180 stun_servers) {}
181
182BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
Yves Gerey665174f2018-06-19 15:03:05 +0200183 rtc::PacketSocketFactory* socket_factory,
184 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700185 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100186 InitRelayPortFactory(nullptr);
187 RTC_DCHECK(relay_port_factory_ != nullptr);
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700188 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0,
189 webrtc::NO_PRUNE, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 Construct();
191}
192
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193void BasicPortAllocator::Construct() {
194 allow_tcp_listen_ = true;
195}
196
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700197void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
198 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700199 // If the session has not been taken by an active channel, do not report the
200 // metric.
201 for (auto& allocator_session : pooled_sessions()) {
202 if (allocator_session.get() == session) {
203 return;
204 }
205 }
206
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700207 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
208 static_cast<int>(reason),
209 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700210}
211
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700213 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800214 // Our created port allocator sessions depend on us, so destroy our remaining
215 // pooled sessions before anything else.
216 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217}
218
Steve Anton7995d8c2017-10-30 16:23:38 -0700219void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
220 // TODO(phoglund): implement support for other types than loopback.
221 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
222 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700223 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700224 network_ignore_mask_ = network_ignore_mask;
225}
226
deadbeefc5d0d952015-07-16 10:22:21 -0700227PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200228 const std::string& content_name,
229 int component,
230 const std::string& ice_ufrag,
231 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700232 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700233 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700235 session->SignalIceRegathering.connect(this,
236 &BasicPortAllocator::OnIceRegathering);
237 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238}
239
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700240void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700241 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700242 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
243 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700244 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700245 turn_port_prune_policy(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700246}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247
Jonas Oreland202994c2017-12-18 12:10:43 +0100248void BasicPortAllocator::InitRelayPortFactory(
249 RelayPortFactoryInterface* relay_port_factory) {
250 if (relay_port_factory != nullptr) {
251 relay_port_factory_ = relay_port_factory;
252 } else {
253 default_relay_port_factory_.reset(new TurnPortFactory());
254 relay_port_factory_ = default_relay_port_factory_.get();
255 }
256}
257
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000258// BasicPortAllocatorSession
259BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700260 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 const std::string& content_name,
262 int component,
263 const std::string& ice_ufrag,
264 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700265 : PortAllocatorSession(content_name,
266 component,
267 ice_ufrag,
268 ice_pwd,
269 allocator->flags()),
270 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700271 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000272 socket_factory_(allocator->socket_factory()),
273 allocation_started_(false),
274 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700275 allocation_sequences_created_(false),
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700276 turn_port_prune_policy_(allocator->turn_port_prune_policy()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277 allocator_->network_manager()->SignalNetworksChanged.connect(
278 this, &BasicPortAllocatorSession::OnNetworksChanged);
279 allocator_->network_manager()->StartUpdating();
280}
281
282BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700283 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000284 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000285 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 network_thread_->Clear(this);
287
Peter Boström0c4e06b2015-10-07 12:23:21 +0200288 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289 // AllocationSequence should clear it's map entry for turn ports before
290 // ports are destroyed.
291 sequences_[i]->Clear();
292 }
293
294 std::vector<PortData>::iterator it;
295 for (it = ports_.begin(); it != ports_.end(); it++)
296 delete it->port();
297
Peter Boström0c4e06b2015-10-07 12:23:21 +0200298 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 delete configs_[i];
300
Peter Boström0c4e06b2015-10-07 12:23:21 +0200301 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302 delete sequences_[i];
303}
304
Steve Anton7995d8c2017-10-30 16:23:38 -0700305BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700306 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700307 return allocator_;
308}
309
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700310void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700311 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700312 if (filter == candidate_filter_) {
313 return;
314 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700315 uint32_t prev_filter = candidate_filter_;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700316 candidate_filter_ = filter;
Qingsi Wangc129c352019-04-18 10:41:58 -0700317 for (PortData& port_data : ports_) {
318 if (port_data.error() || port_data.pruned()) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700319 continue;
320 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700321 PortData::State cur_state = port_data.state();
322 bool found_signalable_candidate = false;
323 bool found_pairable_candidate = false;
324 cricket::Port* port = port_data.port();
325 for (const auto& c : port->Candidates()) {
326 if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) &&
327 IsAllowedByCandidateFilter(c, filter)) {
328 // This candidate was not signaled because of not matching the previous
329 // filter (see OnCandidateReady below). Let the Port to fire the signal
330 // again.
331 //
332 // Note that
333 // 1) we would need the Port to enter the state of in-progress of
334 // gathering to have candidates signaled;
335 //
336 // 2) firing the signal would also let the session set the port ready
337 // if needed, so that we could form candidate pairs with candidates
338 // from this port;
339 //
340 // * See again OnCandidateReady below for 1) and 2).
341 //
342 // 3) we only try to resurface candidates if we have not stopped
343 // getting ports, which is always true for the continual gathering.
344 if (!found_signalable_candidate) {
345 found_signalable_candidate = true;
346 port_data.set_state(PortData::STATE_INPROGRESS);
347 }
348 port->SignalCandidateReady(port, c);
349 }
350
351 if (CandidatePairable(c, port)) {
352 found_pairable_candidate = true;
353 }
354 }
355 // Restore the previous state.
356 port_data.set_state(cur_state);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700357 // Setting a filter may cause a ready port to become non-ready
358 // if it no longer has any pairable candidates.
Qingsi Wangc129c352019-04-18 10:41:58 -0700359 //
360 // Note that we only set for the negative case here, since a port would be
361 // set to have pairable candidates when it signals a ready candidate, which
362 // requires the port is still in the progress of gathering/surfacing
363 // candidates, and would be done in the firing of the signal above.
364 if (!found_pairable_candidate) {
365 port_data.set_has_pairable_candidate(false);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700366 }
367 }
368}
369
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700371 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700372 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373 if (!socket_factory_) {
374 owned_socket_factory_.reset(
375 new rtc::BasicPacketSocketFactory(network_thread_));
376 socket_factory_ = owned_socket_factory_.get();
377 }
378
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700379 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700380
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700381 RTC_LOG(LS_INFO) << "Start getting ports with turn_port_prune_policy "
382 << turn_port_prune_policy_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000383}
384
385void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700386 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700387 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700388 // Note: this must be called after ClearGettingPorts because both may set the
389 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700390 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700391}
392
393void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700394 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700396 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000397 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700398 }
deadbeefb60a8192016-08-24 15:15:00 -0700399 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700400 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700401}
402
Steve Anton7995d8c2017-10-30 16:23:38 -0700403bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700404 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700405 return state_ == SessionState::GATHERING;
406}
407
408bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700409 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700410 return state_ == SessionState::CLEARED;
411}
412
413bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700414 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700415 return state_ == SessionState::STOPPED;
416}
417
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700418std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700419 RTC_DCHECK_RUN_ON(network_thread_);
420
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700421 std::vector<rtc::Network*> networks = GetNetworks();
422
423 // A network interface may have both IPv4 and IPv6 networks. Only if
424 // neither of the networks has any connections, the network interface
425 // is considered failed and need to be regathered on.
426 std::set<std::string> networks_with_connection;
427 for (const PortData& data : ports_) {
428 Port* port = data.port();
429 if (!port->connections().empty()) {
430 networks_with_connection.insert(port->Network()->name());
431 }
432 }
433
434 networks.erase(
435 std::remove_if(networks.begin(), networks.end(),
436 [networks_with_connection](rtc::Network* network) {
437 // If a network does not have any connection, it is
438 // considered failed.
439 return networks_with_connection.find(network->name()) !=
440 networks_with_connection.end();
441 }),
442 networks.end());
443 return networks;
444}
445
446void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700447 RTC_DCHECK_RUN_ON(network_thread_);
448
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700449 // Find the list of networks that have no connection.
450 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
451 if (failed_networks.empty()) {
452 return;
453 }
454
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700456
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700457 // Mark a sequence as "network failed" if its network is in the list of failed
458 // networks, so that it won't be considered as equivalent when the session
459 // regathers ports and candidates.
460 for (AllocationSequence* sequence : sequences_) {
461 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800462 absl::c_linear_search(failed_networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700463 sequence->set_network_failed();
464 }
465 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700466
467 bool disable_equivalent_phases = true;
468 Regather(failed_networks, disable_equivalent_phases,
469 IceRegatheringReason::NETWORK_FAILURE);
470}
471
472void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700473 RTC_DCHECK_RUN_ON(network_thread_);
474
Steve Anton300bf8e2017-07-14 10:13:10 -0700475 std::vector<rtc::Network*> networks = GetNetworks();
476 if (networks.empty()) {
477 return;
478 }
479
Mirko Bonadei675513b2017-11-09 11:09:25 +0100480 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700481
482 // We expect to generate candidates that are equivalent to what we have now.
483 // Force DoAllocate to generate them instead of skipping.
484 bool disable_equivalent_phases = false;
485 Regather(networks, disable_equivalent_phases,
486 IceRegatheringReason::OCCASIONAL_REFRESH);
487}
488
489void BasicPortAllocatorSession::Regather(
490 const std::vector<rtc::Network*>& networks,
491 bool disable_equivalent_phases,
492 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700493 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700494 // Remove ports from being used locally and send signaling to remove
495 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700496 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700497 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000499 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700500 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700501
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700502 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700503 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700504
Steve Anton300bf8e2017-07-14 10:13:10 -0700505 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700506 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000507}
508
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700509void BasicPortAllocatorSession::GetCandidateStatsFromReadyPorts(
510 CandidateStatsList* candidate_stats_list) const {
511 auto ports = ReadyPorts();
512 for (auto* port : ports) {
513 auto candidates = port->Candidates();
514 for (const auto& candidate : candidates) {
515 CandidateStats candidate_stats(allocator_->SanitizeCandidate(candidate));
516 port->GetStunStats(&candidate_stats.stun_stats);
517 candidate_stats_list->push_back(std::move(candidate_stats));
518 }
519 }
520}
521
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800522void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200523 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700524 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800525 auto ports = ReadyPorts();
526 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800527 // The port type and protocol can be used to identify different subclasses
528 // of Port in the current implementation. Note that a TCPPort has the type
529 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
530 if (port->Type() == STUN_PORT_TYPE ||
531 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800532 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
533 stun_keepalive_interval);
534 }
535 }
536}
537
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700538std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700539 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700540 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700541 for (const PortData& data : ports_) {
542 if (data.ready()) {
543 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700544 }
545 }
546 return ret;
547}
548
549std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700550 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700551 std::vector<Candidate> candidates;
552 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700553 if (!data.ready()) {
554 continue;
555 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700556 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700557 }
558 return candidates;
559}
560
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700561void BasicPortAllocatorSession::GetCandidatesFromPort(
562 const PortData& data,
563 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700564 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700565 RTC_CHECK(candidates != nullptr);
566 for (const Candidate& candidate : data.port()->Candidates()) {
567 if (!CheckCandidateFilter(candidate)) {
568 continue;
569 }
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700570 candidates->push_back(allocator_->SanitizeCandidate(candidate));
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700571 }
572}
573
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700574bool BasicPortAllocator::MdnsObfuscationEnabled() const {
575 return network_manager()->GetMdnsResponder() != nullptr;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700576}
577
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700578bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700579 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700580 // Done only if all required AllocationSequence objects
581 // are created.
582 if (!allocation_sequences_created_) {
583 return false;
584 }
585
586 // Check that all port allocation sequences are complete (not running).
Steve Antonae226f62019-01-29 12:47:38 -0800587 if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
588 return sequence->state() == AllocationSequence::kRunning;
589 })) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700590 return false;
591 }
592
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700593 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700594 // expected candidates. Session will trigger candidates allocation complete
595 // signal.
Steve Antonae226f62019-01-29 12:47:38 -0800596 return absl::c_none_of(
597 ports_, [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700598}
599
Yves Gerey665174f2018-06-19 15:03:05 +0200600void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000601 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200602 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200603 GetPortConfigurations();
604 break;
605 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200606 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
607 break;
608 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200609 OnAllocate();
610 break;
611 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200612 OnAllocationSequenceObjectsCreated();
613 break;
614 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200615 OnConfigStop();
616 break;
617 default:
618 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000619 }
620}
621
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700622void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700623 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700624 for (PortData& port : ports_) {
625 port.port()->set_content_name(content_name());
626 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
627 }
628}
629
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000630void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700631 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangc129c352019-04-18 10:41:58 -0700632
Yves Gerey665174f2018-06-19 15:03:05 +0200633 PortConfiguration* config =
634 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635
deadbeef653b8e02015-11-11 12:55:10 -0800636 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
637 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000638 }
639 ConfigReady(config);
640}
641
642void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700643 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700644 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645}
646
647// Adds a configuration to the list.
648void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700649 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800650 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800652 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653
654 AllocatePorts();
655}
656
657void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700658 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000659
660 // If any of the allocated ports have not completed the candidates allocation,
661 // mark those as error. Since session doesn't need any new candidates
662 // at this stage of the allocation, it's safe to discard any new candidates.
663 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200664 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
665 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700666 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000667 // Updating port state to error, which didn't finish allocating candidates
668 // yet.
Qingsi Wangc129c352019-04-18 10:41:58 -0700669 it->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670 send_signal = true;
671 }
672 }
673
674 // Did we stop any running sequences?
675 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
676 it != sequences_.end() && !send_signal; ++it) {
677 if ((*it)->state() == AllocationSequence::kStopped) {
678 send_signal = true;
679 }
680 }
681
682 // If we stopped anything that was running, send a done signal now.
683 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000684 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 }
686}
687
688void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700689 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700690 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691}
692
693void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700694 RTC_DCHECK_RUN_ON(network_thread_);
695
Steve Anton300bf8e2017-07-14 10:13:10 -0700696 if (network_manager_started_ && !IsStopped()) {
697 bool disable_equivalent_phases = true;
698 DoAllocate(disable_equivalent_phases);
699 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000700
701 allocation_started_ = true;
702}
703
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700704std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700705 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700706 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700707 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800708 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700709 // If the network permission state is BLOCKED, we just act as if the flag has
710 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700711 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700712 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700713 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
714 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000715 // If the adapter enumeration is disabled, we'll just bind to any address
716 // instead of specific NIC. This is to ensure the same routing for http
717 // traffic by OS is also used here to avoid any local or public IP leakage
718 // during stun process.
719 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
720 network_manager->GetAnyAddressNetworks(&networks);
721 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700722 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000723 // If network enumeration fails, use the ANY address as a fallback, so we
724 // can at least try gathering candidates using the default route chosen by
725 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
726 // set, we'll use ANY address candidates either way.
727 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
728 network_manager->GetAnyAddressNetworks(&networks);
729 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000730 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100731 // Filter out link-local networks if needed.
732 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700733 NetworkFilter link_local_filter(
734 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
735 "link-local");
736 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100737 }
deadbeef3427f532017-07-26 16:09:33 -0700738 // Do some more filtering, depending on the network ignore mask and "disable
739 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700740 NetworkFilter ignored_filter(
741 [this](rtc::Network* network) {
742 return allocator_->network_ignore_mask() & network->type();
743 },
744 "ignored");
745 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700746 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
747 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700748 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000749 // Don't determine the lowest cost from a link-local network.
750 // On iOS, a device connected to the computer will get a link-local
751 // network for communicating with the computer, however this network can't
752 // be used to connect to a peer outside the network.
753 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800754 continue;
755 }
honghaiz60347052016-05-31 18:29:12 -0700756 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
757 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700758 NetworkFilter costly_filter(
759 [lowest_cost](rtc::Network* network) {
760 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
761 },
762 "costly");
763 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700764 }
deadbeef3427f532017-07-26 16:09:33 -0700765 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
766 // default, it's 5), remove networks to ensure that limit is satisfied.
767 //
768 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
769 // networks, we could try to choose a set that's "most likely to work". It's
770 // hard to define what that means though; it's not just "lowest cost".
771 // Alternatively, we could just focus on making our ICE pinging logic smarter
772 // such that this filtering isn't necessary in the first place.
773 int ipv6_networks = 0;
774 for (auto it = networks.begin(); it != networks.end();) {
775 if ((*it)->prefix().family() == AF_INET6) {
776 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
777 it = networks.erase(it);
778 continue;
779 } else {
780 ++ipv6_networks;
781 }
782 }
783 ++it;
784 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700785 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700786}
787
788// For each network, see if we have a sequence that covers it already. If not,
789// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700790void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700791 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700792 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700793 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000794 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100795 RTC_LOG(LS_WARNING)
796 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000797 done_signal_needed = true;
798 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100799 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700800 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200801 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200802 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000803 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
804 // If all the ports are disabled we should just fire the allocation
805 // done event and return.
806 done_signal_needed = true;
807 break;
808 }
809
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000810 if (!config || config->relays.empty()) {
811 // No relay ports specified in this config.
812 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
813 }
814
815 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000816 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000817 // Skip IPv6 networks unless the flag's been set.
818 continue;
819 }
820
zhihuangb09b3f92017-03-07 14:40:51 -0800821 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
822 networks[i]->GetBestIP().family() == AF_INET6 &&
823 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
824 // Skip IPv6 Wi-Fi networks unless the flag's been set.
825 continue;
826 }
827
Steve Anton300bf8e2017-07-14 10:13:10 -0700828 if (disable_equivalent) {
829 // Disable phases that would only create ports equivalent to
830 // ones that we have already made.
831 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832
Steve Anton300bf8e2017-07-14 10:13:10 -0700833 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
834 // New AllocationSequence would have nothing to do, so don't make it.
835 continue;
836 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837 }
838
839 AllocationSequence* sequence =
840 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 sequence->SignalPortAllocationComplete.connect(
842 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700843 sequence->Init();
844 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700846 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 }
848 }
849 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700850 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 }
852}
853
854void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700855 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700856 std::vector<rtc::Network*> networks = GetNetworks();
857 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700858 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700859 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700860 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700861 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800862 !absl::c_linear_search(networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700863 sequence->OnNetworkFailed();
864 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700865 }
866 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700867 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
868 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100869 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
870 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000871 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700872 }
honghaiz8c404fa2015-09-28 07:59:43 -0700873
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700874 if (allocation_started_ && !IsStopped()) {
875 if (network_manager_started_) {
876 // If the network manager has started, it must be regathering.
877 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
878 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700879 bool disable_equivalent_phases = true;
880 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700881 }
882
Honghai Zhang5048f572016-08-23 15:47:33 -0700883 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100884 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700885 network_manager_started_ = true;
886 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887}
888
889void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200890 rtc::Network* network,
891 PortConfiguration* config,
892 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700893 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200894 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200895 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200896 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 sequences_[i]->DisableEquivalentPhases(network, config, flags);
898 }
899}
900
901void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200902 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700904 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905 if (!port)
906 return;
907
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700910 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700912 if (allocator_->proxy().type != rtc::PROXY_NONE)
913 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700914 port->set_send_retransmit_count_attribute(
915 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917 PortData data(port, seq);
918 ports_.push_back(data);
919
920 port->SignalCandidateReady.connect(
921 this, &BasicPortAllocatorSession::OnCandidateReady);
Eldar Relloda13ea22019-06-01 12:23:43 +0300922 port->SignalCandidateError.connect(
923 this, &BasicPortAllocatorSession::OnCandidateError);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200925 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200927 &BasicPortAllocatorSession::OnPortDestroyed);
928 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
929 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930
931 if (prepare_address)
932 port->PrepareAddress();
933}
934
935void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700936 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937 allocation_sequences_created_ = true;
938 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000939 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940}
941
Yves Gerey665174f2018-06-19 15:03:05 +0200942void BasicPortAllocatorSession::OnCandidateReady(Port* port,
943 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700944 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000945 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000946 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200947 RTC_LOG(LS_INFO) << port->ToString()
948 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700950 // already done with gathering.
951 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100952 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700953 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700954 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700955 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700956
danilchapf4e8cf02016-06-30 01:55:03 -0700957 // Mark that the port has a pairable candidate, either because we have a
958 // usable candidate from the port, or simply because the port is bound to the
959 // any address and therefore has no host candidate. This will trigger the port
960 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700961 // checks. If port has already been marked as having a pairable candidate,
962 // do nothing here.
963 // Note: We should check whether any candidates may become ready after this
964 // because there we will check whether the candidate is generated by the ready
965 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700966 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700967 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700968 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700969
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700970 if (port->Type() == RELAY_PORT_TYPE) {
971 if (turn_port_prune_policy_ == webrtc::KEEP_FIRST_READY) {
972 pruned = PruneNewlyPairableTurnPort(data);
973 } else if (turn_port_prune_policy_ == webrtc::PRUNE_BASED_ON_PRIORITY) {
974 pruned = PruneTurnPorts(port);
975 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700976 }
Honghai Zhangf8998cf2019-10-14 11:27:50 -0700977
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700978 // If the current port is not pruned yet, SignalPortReady.
979 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000980 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
981 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700982 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700983 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700984 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700985
deadbeef1c5e6d02017-09-15 17:46:56 -0700986 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000987 std::vector<Candidate> candidates;
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700988 candidates.push_back(allocator_->SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000989 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700990 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100991 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700992 }
993
994 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700995 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000996 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700997 }
998}
999
Eldar Relloda13ea22019-06-01 12:23:43 +03001000void BasicPortAllocatorSession::OnCandidateError(
1001 Port* port,
1002 const IceCandidateErrorEvent& event) {
1003 RTC_DCHECK_RUN_ON(network_thread_);
1004 RTC_DCHECK(FindPort(port));
1005
1006 SignalCandidateError(this, event);
1007}
1008
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001009Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
1010 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -07001011 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001012 Port* best_turn_port = nullptr;
1013 for (const PortData& data : ports_) {
1014 if (data.port()->Network()->name() == network_name &&
1015 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1016 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
1017 best_turn_port = data.port();
1018 }
1019 }
1020 return best_turn_port;
1021}
1022
Honghai Zhangf8998cf2019-10-14 11:27:50 -07001023bool BasicPortAllocatorSession::PruneNewlyPairableTurnPort(
1024 PortData* newly_pairable_port_data) {
1025 RTC_DCHECK_RUN_ON(network_thread_);
1026 RTC_DCHECK(newly_pairable_port_data->port()->Type() == RELAY_PORT_TYPE);
1027 // If an existing turn port is ready on the same network, prune the newly
1028 // pairable port.
1029 const std::string& network_name =
1030 newly_pairable_port_data->port()->Network()->name();
1031
1032 for (PortData& data : ports_) {
1033 if (data.port()->Network()->name() == network_name &&
1034 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1035 &data != newly_pairable_port_data) {
1036 RTC_LOG(LS_INFO) << "Port pruned: "
1037 << newly_pairable_port_data->port()->ToString();
1038 newly_pairable_port_data->Prune();
1039 return true;
1040 }
1041 }
1042 return false;
1043}
1044
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001045bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -07001046 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001047 // Note: We determine the same network based only on their network names. So
1048 // if an IPv4 address and an IPv6 address have the same network name, they
1049 // are considered the same network here.
1050 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1051 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1052 // |port| is already in the list of ports, so the best port cannot be nullptr.
1053 RTC_CHECK(best_turn_port != nullptr);
1054
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001055 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001056 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001057 for (PortData& data : ports_) {
1058 if (data.port()->Network()->name() == network_name &&
1059 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1060 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001061 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001062 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001063 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001064 ports_to_prune.push_back(&data);
1065 } else {
1066 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001067 }
1068 }
1069 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001070
1071 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001072 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1073 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001074 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001075 }
1076 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001077}
1078
Honghai Zhanga74363c2016-07-28 18:06:15 -07001079void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001080 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001081 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001082 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001083 }
1084}
1085
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001087 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001088 RTC_LOG(LS_INFO) << port->ToString()
1089 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001090 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001091 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001092
1093 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001094 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001095 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001096 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097
1098 // Moving to COMPLETE state.
Qingsi Wangc129c352019-04-18 10:41:58 -07001099 data->set_state(PortData::STATE_COMPLETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001101 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001102}
1103
1104void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001105 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001106 RTC_LOG(LS_INFO) << port->ToString()
1107 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001109 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001111 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001113 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001114
1115 // SignalAddressError is currently sent from StunPort/TurnPort.
1116 // But this signal itself is generic.
Qingsi Wangc129c352019-04-18 10:41:58 -07001117 data->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001118 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001119 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001120}
1121
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001122bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001123 RTC_DCHECK_RUN_ON(network_thread_);
1124
Qingsi Wangc129c352019-04-18 10:41:58 -07001125 return IsAllowedByCandidateFilter(c, candidate_filter_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001126}
1127
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001128bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1129 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001130 RTC_DCHECK_RUN_ON(network_thread_);
1131
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001132 bool candidate_signalable = CheckCandidateFilter(c);
1133
1134 // When device enumeration is disabled (to prevent non-default IP addresses
1135 // from leaking), we ping from some local candidates even though we don't
1136 // signal them. However, if host candidates are also disabled (for example, to
1137 // prevent even default IP addresses from leaking), we still don't want to
1138 // ping from them, even if device enumeration is disabled. Thus, we check for
1139 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001140 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001141 bool can_ping_from_candidate =
1142 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1143 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1144
1145 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001146 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001147 !host_candidates_disabled);
1148}
1149
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001150void BasicPortAllocatorSession::OnPortAllocationComplete(
1151 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001152 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001153 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001154 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001155}
1156
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001157void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001158 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001159 if (CandidatesAllocationDone()) {
1160 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001161 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001162 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001163 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1164 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001165 }
1166 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001167 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168}
1169
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001170void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001171 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001172 for (std::vector<PortData>::iterator iter = ports_.begin();
1173 iter != ports_.end(); ++iter) {
1174 if (port == iter->port()) {
1175 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001176 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001177 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 return;
1179 }
1180 }
nissec80e7412017-01-11 05:56:46 -08001181 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001182}
1183
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001184BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1185 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001186 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001187 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1188 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001189 if (it->port() == port) {
1190 return &*it;
1191 }
1192 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001193 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001194}
1195
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001196std::vector<BasicPortAllocatorSession::PortData*>
1197BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001198 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001199 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001200 std::vector<PortData*> unpruned_ports;
1201 for (PortData& port : ports_) {
1202 if (!port.pruned() &&
Steve Antonae226f62019-01-29 12:47:38 -08001203 absl::c_linear_search(networks, port.sequence()->network())) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001204 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001205 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001206 }
1207 return unpruned_ports;
1208}
1209
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001210void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001211 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001212 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001213 std::vector<PortInterface*> pruned_ports;
1214 std::vector<Candidate> removed_candidates;
1215 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001216 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001217 data->Prune();
1218 pruned_ports.push_back(data->port());
1219 if (data->has_pairable_candidate()) {
1220 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001221 // Mark the port as having no pairable candidates so that its candidates
1222 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001223 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001224 }
1225 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001226 if (!pruned_ports.empty()) {
1227 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001228 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001229 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001230 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1231 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001232 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001233 }
1234}
1235
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001236// AllocationSequence
1237
1238AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1239 rtc::Network* network,
1240 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001241 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001242 : session_(session),
1243 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 config_(config),
1245 state_(kInit),
1246 flags_(flags),
1247 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001248 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001249 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001250
Honghai Zhang5048f572016-08-23 15:47:33 -07001251void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001252 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1253 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001254 rtc::SocketAddress(network_->GetBestIP(), 0),
1255 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001256 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001257 udp_socket_->SignalReadPacket.connect(this,
1258 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001260 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1261 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001262 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001263}
1264
1265void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001266 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001267 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001268}
1269
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001270void AllocationSequence::OnNetworkFailed() {
1271 RTC_DCHECK(!network_failed_);
1272 network_failed_ = true;
1273 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001274 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001275}
1276
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277AllocationSequence::~AllocationSequence() {
1278 session_->network_thread()->Clear(this);
1279}
1280
1281void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001282 PortConfiguration* config,
1283 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001284 if (network_failed_) {
1285 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001286 // it won't be equivalent to the new network.
1287 return;
1288 }
1289
deadbeef5c3c1042017-08-04 15:01:57 -07001290 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001291 // Different network setup; nothing is equivalent.
1292 return;
1293 }
1294
1295 // Else turn off the stuff that we've already got covered.
1296
deadbeef1c46a352017-09-27 11:24:05 -07001297 // Every config implicitly specifies local, so turn that off right away if we
1298 // already have a port of the corresponding type. Look for a port that
1299 // matches this AllocationSequence's network, is the right protocol, and
1300 // hasn't encountered an error.
1301 // TODO(deadbeef): This doesn't take into account that there may be another
1302 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1303 // This can happen if, say, there's a network change event right before an
1304 // application-triggered ICE restart. Hopefully this problem will just go
1305 // away if we get rid of the gathering "phases" though, which is planned.
Qingsi Wangc129c352019-04-18 10:41:58 -07001306 //
1307 //
1308 // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1309 // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1310 // to disable the gathering of these candidates just becaue of an existing
1311 // Port over PROTO_UDP, namely a TurnPort over UDP.
Steve Antonae226f62019-01-29 12:47:38 -08001312 if (absl::c_any_of(session_->ports_,
1313 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001314 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001315 p.port()->GetProtocol() == PROTO_UDP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001316 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001317 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001318 *flags |= PORTALLOCATOR_DISABLE_UDP;
1319 }
Qingsi Wangc129c352019-04-18 10:41:58 -07001320 // Similarly we need to check both the protocol used by an existing Port and
1321 // its type.
Steve Antonae226f62019-01-29 12:47:38 -08001322 if (absl::c_any_of(session_->ports_,
1323 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001324 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001325 p.port()->GetProtocol() == PROTO_TCP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001326 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001327 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001328 *flags |= PORTALLOCATOR_DISABLE_TCP;
1329 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330
1331 if (config_ && config) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001332 // We need to regather srflx candidates if either of the following
1333 // conditions occurs:
1334 // 1. The STUN servers are different from the previous gathering.
1335 // 2. We will regather host candidates, hence possibly inducing new NAT
1336 // bindings.
1337 if (config_->StunServers() == config->StunServers() &&
1338 (*flags & PORTALLOCATOR_DISABLE_UDP)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001339 // Already got this STUN servers covered.
1340 *flags |= PORTALLOCATOR_DISABLE_STUN;
1341 }
1342 if (!config_->relays.empty()) {
1343 // Already got relays covered.
1344 // NOTE: This will even skip a _different_ set of relay servers if we
1345 // were to be given one, but that never happens in our codebase. Should
1346 // probably get rid of the list in PortConfiguration and just keep a
1347 // single relay server in each one.
1348 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1349 }
1350 }
1351}
1352
1353void AllocationSequence::Start() {
1354 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001355 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001356 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1357 // called next time, we enable all phases if the best IP has since changed.
1358 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001359}
1360
1361void AllocationSequence::Stop() {
1362 // If the port is completed, don't set it to stopped.
1363 if (state_ == kRunning) {
1364 state_ = kStopped;
1365 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1366 }
1367}
1368
1369void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001370 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1371 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372
deadbeef1c5e6d02017-09-15 17:46:56 -07001373 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001374
1375 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001376 RTC_LOG(LS_INFO) << network_->ToString()
1377 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378
1379 switch (phase_) {
1380 case PHASE_UDP:
1381 CreateUDPPorts();
1382 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001383 break;
1384
1385 case PHASE_RELAY:
1386 CreateRelayPorts();
1387 break;
1388
1389 case PHASE_TCP:
1390 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001391 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001392 break;
1393
1394 default:
nissec80e7412017-01-11 05:56:46 -08001395 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001396 }
1397
1398 if (state() == kRunning) {
1399 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001400 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1401 session_->allocator()->step_delay(),
1402 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001403 } else {
1404 // If all phases in AllocationSequence are completed, no allocation
1405 // steps needed further. Canceling pending signal.
1406 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1407 SignalPortAllocationComplete(this);
1408 }
1409}
1410
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001411void AllocationSequence::CreateUDPPorts() {
1412 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001413 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001414 return;
1415 }
1416
1417 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1418 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001419 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001420 bool emit_local_candidate_for_anyaddress =
1421 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001423 port = UDPPort::Create(
1424 session_->network_thread(), session_->socket_factory(), network_,
1425 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001426 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1427 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001428 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001429 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001430 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001431 session_->allocator()->min_port(), session_->allocator()->max_port(),
1432 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001433 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1434 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001435 }
1436
1437 if (port) {
1438 // If shared socket is enabled, STUN candidate will be allocated by the
1439 // UDPPort.
1440 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001441 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001442 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001443
1444 // If STUN is not disabled, setting stun server address to port.
1445 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001446 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001447 RTC_LOG(LS_INFO)
1448 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001449 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001450 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001451 }
1452 }
1453 }
1454
Steve Antona8f1e562018-10-10 11:29:44 -07001455 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001456 }
1457}
1458
1459void AllocationSequence::CreateTCPPorts() {
1460 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001461 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462 return;
1463 }
1464
Steve Antona8f1e562018-10-10 11:29:44 -07001465 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001466 session_->network_thread(), session_->socket_factory(), network_,
1467 session_->allocator()->min_port(), session_->allocator()->max_port(),
1468 session_->username(), session_->password(),
1469 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001470 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001471 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001472 // Since TCPPort is not created using shared socket, |port| will not be
1473 // added to the dequeue.
1474 }
1475}
1476
1477void AllocationSequence::CreateStunPorts() {
1478 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001479 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001480 return;
1481 }
1482
1483 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1484 return;
1485 }
1486
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001487 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001488 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001489 << "AllocationSequence: No STUN server configured, skipping.";
1490 return;
1491 }
1492
Steve Antona8f1e562018-10-10 11:29:44 -07001493 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001494 session_->network_thread(), session_->socket_factory(), network_,
1495 session_->allocator()->min_port(), session_->allocator()->max_port(),
1496 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001497 session_->allocator()->origin(),
1498 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001499 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001500 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001501 // Since StunPort is not created using shared socket, |port| will not be
1502 // added to the dequeue.
1503 }
1504}
1505
1506void AllocationSequence::CreateRelayPorts() {
1507 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001508 RTC_LOG(LS_VERBOSE)
1509 << "AllocationSequence: Relay ports disabled, skipping.";
1510 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001511 }
1512
1513 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1514 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001515 RTC_DCHECK(config_);
1516 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001517 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001518 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001519 << "AllocationSequence: No relay server configured, skipping.";
1520 return;
1521 }
1522
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001523 for (RelayServerConfig& relay : config_->relays) {
1524 if (relay.type == RELAY_GTURN) {
1525 CreateGturnPort(relay);
1526 } else if (relay.type == RELAY_TURN) {
1527 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001528 } else {
nissec80e7412017-01-11 05:56:46 -08001529 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001530 }
1531 }
1532}
1533
1534void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1535 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001536 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001537 session_->network_thread(), session_->socket_factory(), network_,
1538 session_->allocator()->min_port(), session_->allocator()->max_port(),
1539 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001540 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001541 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001542 // Since RelayPort is not created using shared socket, |port| will not be
1543 // added to the dequeue.
1544 // Note: We must add the allocated port before we add addresses because
1545 // the latter will create candidates that need name and preference
1546 // settings. However, we also can't prepare the address (normally
1547 // done by AddAllocatedPort) until we have these addresses. So we
1548 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001549 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001550
1551 // Add the addresses of this protocol.
1552 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001553 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001554 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001555 port_ptr->AddServerAddress(*relay_port);
1556 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001557 }
1558 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001559 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001560 }
1561}
1562
1563void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1564 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001565 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1566 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001567 // Skip UDP connections to relay servers if it's disallowed.
1568 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1569 relay_port->proto == PROTO_UDP) {
1570 continue;
1571 }
1572
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001573 // Do not create a port if the server address family is known and does
1574 // not match the local IP address family.
1575 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001576 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001577 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001578 RTC_LOG(LS_INFO)
1579 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001580 "Server address: "
Qingsi Wang20232a92019-09-06 12:51:17 -07001581 << relay_port->address.ipaddr().ToSensitiveString()
1582 << " Local address: " << network_->GetBestIP().ToSensitiveString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001583 continue;
1584 }
1585
Jonas Oreland202994c2017-12-18 12:10:43 +01001586 CreateRelayPortArgs args;
1587 args.network_thread = session_->network_thread();
1588 args.socket_factory = session_->socket_factory();
1589 args.network = network_;
1590 args.username = session_->username();
1591 args.password = session_->password();
1592 args.server_address = &(*relay_port);
1593 args.config = &config;
1594 args.origin = session_->allocator()->origin();
1595 args.turn_customizer = session_->allocator()->turn_customizer();
1596
1597 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001598 // Shared socket mode must be enabled only for UDP based ports. Hence
1599 // don't pass shared socket for ports which will create TCP sockets.
1600 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1601 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1602 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001603 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001604 port = session_->allocator()->relay_port_factory()->Create(
1605 args, udp_socket_.get());
1606
1607 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001608 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
Qingsi Wang20232a92019-09-06 12:51:17 -07001609 << args.server_address->address.ToSensitiveString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001610 continue;
1611 }
1612
1613 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001614 // Listen to the port destroyed signal, to allow AllocationSequence to
1615 // remove entrt from it's map.
1616 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1617 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001618 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001619 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001620 session_->allocator()->max_port());
1621
1622 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001623 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
Qingsi Wang20232a92019-09-06 12:51:17 -07001624 << args.server_address->address.ToSensitiveString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001625 continue;
1626 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001627 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001628 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001629 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001630 }
1631}
1632
Yves Gerey665174f2018-06-19 15:03:05 +02001633void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1634 const char* data,
1635 size_t size,
1636 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001637 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001638 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001639
1640 bool turn_port_found = false;
1641
1642 // Try to find the TurnPort that matches the remote address. Note that the
1643 // message could be a STUN binding response if the TURN server is also used as
1644 // a STUN server. We don't want to parse every message here to check if it is
1645 // a STUN binding response, so we pass the message to TurnPort regardless of
1646 // the message type. The TurnPort will just ignore the message since it will
1647 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001648 for (auto* port : relay_ports_) {
1649 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001650 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001651 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001652 return;
1653 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001654 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001655 }
1656 }
1657
1658 if (udp_port_) {
1659 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1660
1661 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1662 // the TURN server is also a STUN server.
1663 if (!turn_port_found ||
1664 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001665 RTC_DCHECK(udp_port_->SharedSocket());
1666 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001667 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001668 }
1669 }
1670}
1671
1672void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1673 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001674 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001675 return;
1676 }
1677
Steve Antonae226f62019-01-29 12:47:38 -08001678 auto it = absl::c_find(relay_ports_, port);
Jonas Oreland202994c2017-12-18 12:10:43 +01001679 if (it != relay_ports_.end()) {
1680 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001681 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001683 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001684 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001685}
1686
1687// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001688PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1689 const std::string& username,
1690 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001691 : stun_address(stun_address), username(username), password(password) {
1692 if (!stun_address.IsNil())
1693 stun_servers.insert(stun_address);
1694}
1695
1696PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1697 const std::string& username,
1698 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001699 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001700 if (!stun_servers.empty())
1701 stun_address = *(stun_servers.begin());
1702}
1703
Steve Anton7995d8c2017-10-30 16:23:38 -07001704PortConfiguration::~PortConfiguration() = default;
1705
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001706ServerAddresses PortConfiguration::StunServers() {
1707 if (!stun_address.IsNil() &&
1708 stun_servers.find(stun_address) == stun_servers.end()) {
1709 stun_servers.insert(stun_address);
1710 }
deadbeefc5d0d952015-07-16 10:22:21 -07001711 // Every UDP TURN server should also be used as a STUN server.
1712 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1713 for (const rtc::SocketAddress& turn_server : turn_servers) {
1714 if (stun_servers.find(turn_server) == stun_servers.end()) {
1715 stun_servers.insert(turn_server);
1716 }
1717 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001718 return stun_servers;
1719}
1720
1721void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1722 relays.push_back(config);
1723}
1724
Yves Gerey665174f2018-06-19 15:03:05 +02001725bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1726 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001727 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001728 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1729 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001730 if (relay_port->proto == type)
1731 return true;
1732 }
1733 return false;
1734}
1735
1736bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1737 ProtocolType type) const {
1738 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001739 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001740 return true;
1741 }
1742 return false;
1743}
1744
1745ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001746 RelayType turn_type,
1747 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001748 ServerAddresses servers;
1749 for (size_t i = 0; i < relays.size(); ++i) {
1750 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1751 servers.insert(relays[i].ports.front().address);
1752 }
1753 }
1754 return servers;
1755}
1756
1757} // namespace cricket