blob: 013173ea84c7ce220f7fde1cef41d9135d3824c7 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Steve Anton10542f22019-01-11 09:11:00 -080011#include "p2p/client/basic_port_allocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
Qingsi Wang10a0e512018-05-16 13:37:03 -070014#include <functional>
Steve Anton6c38cc72017-11-29 10:25:58 -080015#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <string>
Qingsi Wang7627fdd2019-08-19 16:07:40 -070017#include <utility>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000018#include <vector>
19
Steve Antonae226f62019-01-29 12:47:38 -080020#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "p2p/base/basic_packet_socket_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "p2p/base/port.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "p2p/base/relay_port.h"
24#include "p2p/base/stun_port.h"
25#include "p2p/base/tcp_port.h"
26#include "p2p/base/turn_port.h"
27#include "p2p/base/udp_port.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
29#include "rtc_base/helpers.h"
30#include "rtc_base/logging.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070031#include "system_wrappers/include/metrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000034
Qingsi Wangc129c352019-04-18 10:41:58 -070035namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000036namespace {
37
38enum {
39 MSG_CONFIG_START,
40 MSG_CONFIG_READY,
41 MSG_ALLOCATE,
42 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000043 MSG_SEQUENCEOBJECTS_CREATED,
44 MSG_CONFIG_STOP,
45};
46
47const int PHASE_UDP = 0;
48const int PHASE_RELAY = 1;
49const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050
deadbeef1c5e6d02017-09-15 17:46:56 -070051const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052
zhihuang696f8ca2017-06-27 15:11:24 -070053// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070054int GetProtocolPriority(cricket::ProtocolType protocol) {
55 switch (protocol) {
56 case cricket::PROTO_UDP:
57 return 2;
58 case cricket::PROTO_TCP:
59 return 1;
60 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070061 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070062 return 0;
63 default:
nisseeb4ca4e2017-01-12 02:24:27 -080064 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070065 return 0;
66 }
67}
68// Gets address family priority: IPv6 > IPv4 > Unspecified.
69int GetAddressFamilyPriority(int ip_family) {
70 switch (ip_family) {
71 case AF_INET6:
72 return 2;
73 case AF_INET:
74 return 1;
75 default:
nisseeb4ca4e2017-01-12 02:24:27 -080076 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070077 return 0;
78 }
79}
80
81// Returns positive if a is better, negative if b is better, and 0 otherwise.
82int ComparePort(const cricket::Port* a, const cricket::Port* b) {
83 int a_protocol = GetProtocolPriority(a->GetProtocol());
84 int b_protocol = GetProtocolPriority(b->GetProtocol());
85 int cmp_protocol = a_protocol - b_protocol;
86 if (cmp_protocol != 0) {
87 return cmp_protocol;
88 }
89
90 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
91 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
92 return a_family - b_family;
93}
94
Qingsi Wang10a0e512018-05-16 13:37:03 -070095struct NetworkFilter {
96 using Predicate = std::function<bool(rtc::Network*)>;
97 NetworkFilter(Predicate pred, const std::string& description)
98 : pred(pred), description(description) {}
99 Predicate pred;
100 const std::string description;
101};
102
103using NetworkList = rtc::NetworkManager::NetworkList;
104void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
105 auto start_to_remove =
106 std::remove_if(networks->begin(), networks->end(), filter.pred);
107 if (start_to_remove == networks->end()) {
108 return;
109 }
110 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
111 for (auto it = start_to_remove; it != networks->end(); ++it) {
112 RTC_LOG(INFO) << (*it)->ToString();
113 }
114 networks->erase(start_to_remove, networks->end());
115}
116
Qingsi Wangc129c352019-04-18 10:41:58 -0700117bool IsAllowedByCandidateFilter(const Candidate& c, uint32_t filter) {
118 // When binding to any address, before sending packets out, the getsockname
119 // returns all 0s, but after sending packets, it'll be the NIC used to
120 // send. All 0s is not a valid ICE candidate address and should be filtered
121 // out.
122 if (c.address().IsAnyIP()) {
123 return false;
124 }
125
126 if (c.type() == RELAY_PORT_TYPE) {
127 return ((filter & CF_RELAY) != 0);
128 } else if (c.type() == STUN_PORT_TYPE) {
129 return ((filter & CF_REFLEXIVE) != 0);
130 } else if (c.type() == LOCAL_PORT_TYPE) {
131 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
132 // We allow host candidates if the filter allows server-reflexive
133 // candidates and the candidate is a public IP. Because we don't generate
134 // server-reflexive candidates if they have the same IP as the host
135 // candidate (i.e. when the host candidate is a public IP), filtering to
136 // only server-reflexive candidates won't work right when the host
137 // candidates have public IPs.
138 return true;
139 }
140
141 return ((filter & CF_HOST) != 0);
142 }
143 return false;
144}
145
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146} // namespace
147
Peter Boström0c4e06b2015-10-07 12:23:21 +0200148const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700149 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
150 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151
152// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200153BasicPortAllocator::BasicPortAllocator(
154 rtc::NetworkManager* network_manager,
155 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100156 webrtc::TurnCustomizer* customizer,
157 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700158 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100159 InitRelayPortFactory(relay_port_factory);
160 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800161 RTC_DCHECK(network_manager_ != nullptr);
162 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200163 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
164 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 Construct();
166}
167
Yves Gerey665174f2018-06-19 15:03:05 +0200168BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700169 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100170 InitRelayPortFactory(nullptr);
171 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800172 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 Construct();
174}
175
Yves Gerey665174f2018-06-19 15:03:05 +0200176BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
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);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200188 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
189 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 Construct();
191}
192
193BasicPortAllocator::BasicPortAllocator(
194 rtc::NetworkManager* network_manager,
195 const ServerAddresses& stun_servers,
196 const rtc::SocketAddress& relay_address_udp,
197 const rtc::SocketAddress& relay_address_tcp,
198 const rtc::SocketAddress& relay_address_ssl)
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000199 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100200 InitRelayPortFactory(nullptr);
201 RTC_DCHECK(relay_port_factory_ != nullptr);
202 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700203 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800205 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800207 }
208 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800210 }
211 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800213 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214
deadbeef653b8e02015-11-11 12:55:10 -0800215 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700216 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800217 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218
Jonas Orelandbdcee282017-10-10 14:01:40 +0200219 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 Construct();
221}
222
223void BasicPortAllocator::Construct() {
224 allow_tcp_listen_ = true;
225}
226
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700227void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
228 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700229 // If the session has not been taken by an active channel, do not report the
230 // metric.
231 for (auto& allocator_session : pooled_sessions()) {
232 if (allocator_session.get() == session) {
233 return;
234 }
235 }
236
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700237 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
238 static_cast<int>(reason),
239 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700240}
241
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700243 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800244 // Our created port allocator sessions depend on us, so destroy our remaining
245 // pooled sessions before anything else.
246 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247}
248
Steve Anton7995d8c2017-10-30 16:23:38 -0700249void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
250 // TODO(phoglund): implement support for other types than loopback.
251 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
252 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700253 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700254 network_ignore_mask_ = network_ignore_mask;
255}
256
deadbeefc5d0d952015-07-16 10:22:21 -0700257PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200258 const std::string& content_name,
259 int component,
260 const std::string& ice_ufrag,
261 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700262 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700263 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700265 session->SignalIceRegathering.connect(this,
266 &BasicPortAllocator::OnIceRegathering);
267 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268}
269
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700270void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700271 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700272 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
273 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700274 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200275 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700276}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277
Jonas Oreland202994c2017-12-18 12:10:43 +0100278void BasicPortAllocator::InitRelayPortFactory(
279 RelayPortFactoryInterface* relay_port_factory) {
280 if (relay_port_factory != nullptr) {
281 relay_port_factory_ = relay_port_factory;
282 } else {
283 default_relay_port_factory_.reset(new TurnPortFactory());
284 relay_port_factory_ = default_relay_port_factory_.get();
285 }
286}
287
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288// BasicPortAllocatorSession
289BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700290 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 const std::string& content_name,
292 int component,
293 const std::string& ice_ufrag,
294 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700295 : PortAllocatorSession(content_name,
296 component,
297 ice_ufrag,
298 ice_pwd,
299 allocator->flags()),
300 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700301 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302 socket_factory_(allocator->socket_factory()),
303 allocation_started_(false),
304 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700305 allocation_sequences_created_(false),
306 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 allocator_->network_manager()->SignalNetworksChanged.connect(
308 this, &BasicPortAllocatorSession::OnNetworksChanged);
309 allocator_->network_manager()->StartUpdating();
310}
311
312BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700313 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000315 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 network_thread_->Clear(this);
317
Peter Boström0c4e06b2015-10-07 12:23:21 +0200318 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319 // AllocationSequence should clear it's map entry for turn ports before
320 // ports are destroyed.
321 sequences_[i]->Clear();
322 }
323
324 std::vector<PortData>::iterator it;
325 for (it = ports_.begin(); it != ports_.end(); it++)
326 delete it->port();
327
Peter Boström0c4e06b2015-10-07 12:23:21 +0200328 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000329 delete configs_[i];
330
Peter Boström0c4e06b2015-10-07 12:23:21 +0200331 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000332 delete sequences_[i];
333}
334
Steve Anton7995d8c2017-10-30 16:23:38 -0700335BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700336 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700337 return allocator_;
338}
339
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700340void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700341 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700342 if (filter == candidate_filter_) {
343 return;
344 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700345 uint32_t prev_filter = candidate_filter_;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700346 candidate_filter_ = filter;
Qingsi Wangc129c352019-04-18 10:41:58 -0700347 for (PortData& port_data : ports_) {
348 if (port_data.error() || port_data.pruned()) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700349 continue;
350 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700351 PortData::State cur_state = port_data.state();
352 bool found_signalable_candidate = false;
353 bool found_pairable_candidate = false;
354 cricket::Port* port = port_data.port();
355 for (const auto& c : port->Candidates()) {
356 if (!IsStopped() && !IsAllowedByCandidateFilter(c, prev_filter) &&
357 IsAllowedByCandidateFilter(c, filter)) {
358 // This candidate was not signaled because of not matching the previous
359 // filter (see OnCandidateReady below). Let the Port to fire the signal
360 // again.
361 //
362 // Note that
363 // 1) we would need the Port to enter the state of in-progress of
364 // gathering to have candidates signaled;
365 //
366 // 2) firing the signal would also let the session set the port ready
367 // if needed, so that we could form candidate pairs with candidates
368 // from this port;
369 //
370 // * See again OnCandidateReady below for 1) and 2).
371 //
372 // 3) we only try to resurface candidates if we have not stopped
373 // getting ports, which is always true for the continual gathering.
374 if (!found_signalable_candidate) {
375 found_signalable_candidate = true;
376 port_data.set_state(PortData::STATE_INPROGRESS);
377 }
378 port->SignalCandidateReady(port, c);
379 }
380
381 if (CandidatePairable(c, port)) {
382 found_pairable_candidate = true;
383 }
384 }
385 // Restore the previous state.
386 port_data.set_state(cur_state);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700387 // Setting a filter may cause a ready port to become non-ready
388 // if it no longer has any pairable candidates.
Qingsi Wangc129c352019-04-18 10:41:58 -0700389 //
390 // Note that we only set for the negative case here, since a port would be
391 // set to have pairable candidates when it signals a ready candidate, which
392 // requires the port is still in the progress of gathering/surfacing
393 // candidates, and would be done in the firing of the signal above.
394 if (!found_pairable_candidate) {
395 port_data.set_has_pairable_candidate(false);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700396 }
397 }
398}
399
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000400void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700401 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700402 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 if (!socket_factory_) {
404 owned_socket_factory_.reset(
405 new rtc::BasicPacketSocketFactory(network_thread_));
406 socket_factory_ = owned_socket_factory_.get();
407 }
408
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700409 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700410
Mirko Bonadei675513b2017-11-09 11:09:25 +0100411 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
412 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000413}
414
415void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700416 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700417 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700418 // Note: this must be called after ClearGettingPorts because both may set the
419 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700420 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700421}
422
423void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700424 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000425 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700426 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000427 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700428 }
deadbeefb60a8192016-08-24 15:15:00 -0700429 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700430 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700431}
432
Steve Anton7995d8c2017-10-30 16:23:38 -0700433bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700434 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700435 return state_ == SessionState::GATHERING;
436}
437
438bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700439 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700440 return state_ == SessionState::CLEARED;
441}
442
443bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700444 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700445 return state_ == SessionState::STOPPED;
446}
447
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700448std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700449 RTC_DCHECK_RUN_ON(network_thread_);
450
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700451 std::vector<rtc::Network*> networks = GetNetworks();
452
453 // A network interface may have both IPv4 and IPv6 networks. Only if
454 // neither of the networks has any connections, the network interface
455 // is considered failed and need to be regathered on.
456 std::set<std::string> networks_with_connection;
457 for (const PortData& data : ports_) {
458 Port* port = data.port();
459 if (!port->connections().empty()) {
460 networks_with_connection.insert(port->Network()->name());
461 }
462 }
463
464 networks.erase(
465 std::remove_if(networks.begin(), networks.end(),
466 [networks_with_connection](rtc::Network* network) {
467 // If a network does not have any connection, it is
468 // considered failed.
469 return networks_with_connection.find(network->name()) !=
470 networks_with_connection.end();
471 }),
472 networks.end());
473 return networks;
474}
475
476void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700477 RTC_DCHECK_RUN_ON(network_thread_);
478
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700479 // Find the list of networks that have no connection.
480 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
481 if (failed_networks.empty()) {
482 return;
483 }
484
Mirko Bonadei675513b2017-11-09 11:09:25 +0100485 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700486
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700487 // Mark a sequence as "network failed" if its network is in the list of failed
488 // networks, so that it won't be considered as equivalent when the session
489 // regathers ports and candidates.
490 for (AllocationSequence* sequence : sequences_) {
491 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800492 absl::c_linear_search(failed_networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700493 sequence->set_network_failed();
494 }
495 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700496
497 bool disable_equivalent_phases = true;
498 Regather(failed_networks, disable_equivalent_phases,
499 IceRegatheringReason::NETWORK_FAILURE);
500}
501
502void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700503 RTC_DCHECK_RUN_ON(network_thread_);
504
Steve Anton300bf8e2017-07-14 10:13:10 -0700505 std::vector<rtc::Network*> networks = GetNetworks();
506 if (networks.empty()) {
507 return;
508 }
509
Mirko Bonadei675513b2017-11-09 11:09:25 +0100510 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700511
512 // We expect to generate candidates that are equivalent to what we have now.
513 // Force DoAllocate to generate them instead of skipping.
514 bool disable_equivalent_phases = false;
515 Regather(networks, disable_equivalent_phases,
516 IceRegatheringReason::OCCASIONAL_REFRESH);
517}
518
519void BasicPortAllocatorSession::Regather(
520 const std::vector<rtc::Network*>& networks,
521 bool disable_equivalent_phases,
522 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700523 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700524 // Remove ports from being used locally and send signaling to remove
525 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700526 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700527 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100528 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000529 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700530 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700531
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700532 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700533 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700534
Steve Anton300bf8e2017-07-14 10:13:10 -0700535 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700536 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000537}
538
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700539void BasicPortAllocatorSession::GetCandidateStatsFromReadyPorts(
540 CandidateStatsList* candidate_stats_list) const {
541 auto ports = ReadyPorts();
542 for (auto* port : ports) {
543 auto candidates = port->Candidates();
544 for (const auto& candidate : candidates) {
545 CandidateStats candidate_stats(allocator_->SanitizeCandidate(candidate));
546 port->GetStunStats(&candidate_stats.stun_stats);
547 candidate_stats_list->push_back(std::move(candidate_stats));
548 }
549 }
550}
551
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800552void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200553 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700554 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800555 auto ports = ReadyPorts();
556 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800557 // The port type and protocol can be used to identify different subclasses
558 // of Port in the current implementation. Note that a TCPPort has the type
559 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
560 if (port->Type() == STUN_PORT_TYPE ||
561 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800562 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
563 stun_keepalive_interval);
564 }
565 }
566}
567
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700568std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700569 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700570 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700571 for (const PortData& data : ports_) {
572 if (data.ready()) {
573 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700574 }
575 }
576 return ret;
577}
578
579std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700580 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700581 std::vector<Candidate> candidates;
582 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700583 if (!data.ready()) {
584 continue;
585 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700586 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700587 }
588 return candidates;
589}
590
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700591void BasicPortAllocatorSession::GetCandidatesFromPort(
592 const PortData& data,
593 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700594 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700595 RTC_CHECK(candidates != nullptr);
596 for (const Candidate& candidate : data.port()->Candidates()) {
597 if (!CheckCandidateFilter(candidate)) {
598 continue;
599 }
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700600 candidates->push_back(allocator_->SanitizeCandidate(candidate));
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700601 }
602}
603
Qingsi Wang7627fdd2019-08-19 16:07:40 -0700604bool BasicPortAllocator::MdnsObfuscationEnabled() const {
605 return network_manager()->GetMdnsResponder() != nullptr;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700606}
607
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700608bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700609 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700610 // Done only if all required AllocationSequence objects
611 // are created.
612 if (!allocation_sequences_created_) {
613 return false;
614 }
615
616 // Check that all port allocation sequences are complete (not running).
Steve Antonae226f62019-01-29 12:47:38 -0800617 if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
618 return sequence->state() == AllocationSequence::kRunning;
619 })) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700620 return false;
621 }
622
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700623 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700624 // expected candidates. Session will trigger candidates allocation complete
625 // signal.
Steve Antonae226f62019-01-29 12:47:38 -0800626 return absl::c_none_of(
627 ports_, [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700628}
629
Yves Gerey665174f2018-06-19 15:03:05 +0200630void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200632 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200633 GetPortConfigurations();
634 break;
635 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200636 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
637 break;
638 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200639 OnAllocate();
640 break;
641 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200642 OnAllocationSequenceObjectsCreated();
643 break;
644 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200645 OnConfigStop();
646 break;
647 default:
648 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000649 }
650}
651
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700652void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700653 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700654 for (PortData& port : ports_) {
655 port.port()->set_content_name(content_name());
656 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
657 }
658}
659
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700661 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangc129c352019-04-18 10:41:58 -0700662
Yves Gerey665174f2018-06-19 15:03:05 +0200663 PortConfiguration* config =
664 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000665
deadbeef653b8e02015-11-11 12:55:10 -0800666 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
667 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000668 }
669 ConfigReady(config);
670}
671
672void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700673 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700674 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000675}
676
677// Adds a configuration to the list.
678void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700679 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800680 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000681 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800682 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000683
684 AllocatePorts();
685}
686
687void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700688 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689
690 // If any of the allocated ports have not completed the candidates allocation,
691 // mark those as error. Since session doesn't need any new candidates
692 // at this stage of the allocation, it's safe to discard any new candidates.
693 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200694 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
695 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700696 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000697 // Updating port state to error, which didn't finish allocating candidates
698 // yet.
Qingsi Wangc129c352019-04-18 10:41:58 -0700699 it->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000700 send_signal = true;
701 }
702 }
703
704 // Did we stop any running sequences?
705 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
706 it != sequences_.end() && !send_signal; ++it) {
707 if ((*it)->state() == AllocationSequence::kStopped) {
708 send_signal = true;
709 }
710 }
711
712 // If we stopped anything that was running, send a done signal now.
713 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000714 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000715 }
716}
717
718void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700719 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700720 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721}
722
723void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700724 RTC_DCHECK_RUN_ON(network_thread_);
725
Steve Anton300bf8e2017-07-14 10:13:10 -0700726 if (network_manager_started_ && !IsStopped()) {
727 bool disable_equivalent_phases = true;
728 DoAllocate(disable_equivalent_phases);
729 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000730
731 allocation_started_ = true;
732}
733
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700734std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700735 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700736 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700737 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800738 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700739 // If the network permission state is BLOCKED, we just act as if the flag has
740 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700741 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700742 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700743 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
744 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000745 // If the adapter enumeration is disabled, we'll just bind to any address
746 // instead of specific NIC. This is to ensure the same routing for http
747 // traffic by OS is also used here to avoid any local or public IP leakage
748 // during stun process.
749 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
750 network_manager->GetAnyAddressNetworks(&networks);
751 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700752 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000753 // If network enumeration fails, use the ANY address as a fallback, so we
754 // can at least try gathering candidates using the default route chosen by
755 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
756 // set, we'll use ANY address candidates either way.
757 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
758 network_manager->GetAnyAddressNetworks(&networks);
759 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000760 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100761 // Filter out link-local networks if needed.
762 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700763 NetworkFilter link_local_filter(
764 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
765 "link-local");
766 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100767 }
deadbeef3427f532017-07-26 16:09:33 -0700768 // Do some more filtering, depending on the network ignore mask and "disable
769 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700770 NetworkFilter ignored_filter(
771 [this](rtc::Network* network) {
772 return allocator_->network_ignore_mask() & network->type();
773 },
774 "ignored");
775 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700776 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
777 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700778 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000779 // Don't determine the lowest cost from a link-local network.
780 // On iOS, a device connected to the computer will get a link-local
781 // network for communicating with the computer, however this network can't
782 // be used to connect to a peer outside the network.
783 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800784 continue;
785 }
honghaiz60347052016-05-31 18:29:12 -0700786 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
787 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700788 NetworkFilter costly_filter(
789 [lowest_cost](rtc::Network* network) {
790 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
791 },
792 "costly");
793 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700794 }
deadbeef3427f532017-07-26 16:09:33 -0700795 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
796 // default, it's 5), remove networks to ensure that limit is satisfied.
797 //
798 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
799 // networks, we could try to choose a set that's "most likely to work". It's
800 // hard to define what that means though; it's not just "lowest cost".
801 // Alternatively, we could just focus on making our ICE pinging logic smarter
802 // such that this filtering isn't necessary in the first place.
803 int ipv6_networks = 0;
804 for (auto it = networks.begin(); it != networks.end();) {
805 if ((*it)->prefix().family() == AF_INET6) {
806 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
807 it = networks.erase(it);
808 continue;
809 } else {
810 ++ipv6_networks;
811 }
812 }
813 ++it;
814 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700815 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700816}
817
818// For each network, see if we have a sequence that covers it already. If not,
819// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700820void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700821 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700822 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700823 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000824 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100825 RTC_LOG(LS_WARNING)
826 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827 done_signal_needed = true;
828 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100829 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700830 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200831 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200832 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
834 // If all the ports are disabled we should just fire the allocation
835 // done event and return.
836 done_signal_needed = true;
837 break;
838 }
839
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840 if (!config || config->relays.empty()) {
841 // No relay ports specified in this config.
842 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
843 }
844
845 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 // Skip IPv6 networks unless the flag's been set.
848 continue;
849 }
850
zhihuangb09b3f92017-03-07 14:40:51 -0800851 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
852 networks[i]->GetBestIP().family() == AF_INET6 &&
853 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
854 // Skip IPv6 Wi-Fi networks unless the flag's been set.
855 continue;
856 }
857
Steve Anton300bf8e2017-07-14 10:13:10 -0700858 if (disable_equivalent) {
859 // Disable phases that would only create ports equivalent to
860 // ones that we have already made.
861 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862
Steve Anton300bf8e2017-07-14 10:13:10 -0700863 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
864 // New AllocationSequence would have nothing to do, so don't make it.
865 continue;
866 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000867 }
868
869 AllocationSequence* sequence =
870 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000871 sequence->SignalPortAllocationComplete.connect(
872 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700873 sequence->Init();
874 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000875 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700876 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877 }
878 }
879 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700880 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 }
882}
883
884void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700885 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700886 std::vector<rtc::Network*> networks = GetNetworks();
887 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700888 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700889 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700890 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700891 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800892 !absl::c_linear_search(networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700893 sequence->OnNetworkFailed();
894 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700895 }
896 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700897 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
898 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
900 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000901 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700902 }
honghaiz8c404fa2015-09-28 07:59:43 -0700903
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700904 if (allocation_started_ && !IsStopped()) {
905 if (network_manager_started_) {
906 // If the network manager has started, it must be regathering.
907 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
908 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700909 bool disable_equivalent_phases = true;
910 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700911 }
912
Honghai Zhang5048f572016-08-23 15:47:33 -0700913 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100914 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700915 network_manager_started_ = true;
916 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917}
918
919void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200920 rtc::Network* network,
921 PortConfiguration* config,
922 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700923 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200924 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200925 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200926 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 sequences_[i]->DisableEquivalentPhases(network, config, flags);
928 }
929}
930
931void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200932 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700934 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000935 if (!port)
936 return;
937
Mirko Bonadei675513b2017-11-09 11:09:25 +0100938 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700940 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700942 if (allocator_->proxy().type != rtc::PROXY_NONE)
943 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700944 port->set_send_retransmit_count_attribute(
945 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947 PortData data(port, seq);
948 ports_.push_back(data);
949
950 port->SignalCandidateReady.connect(
951 this, &BasicPortAllocatorSession::OnCandidateReady);
Eldar Relloda13ea22019-06-01 12:23:43 +0300952 port->SignalCandidateError.connect(
953 this, &BasicPortAllocatorSession::OnCandidateError);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000954 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200955 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000956 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200957 &BasicPortAllocatorSession::OnPortDestroyed);
958 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
959 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000960
961 if (prepare_address)
962 port->PrepareAddress();
963}
964
965void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700966 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967 allocation_sequences_created_ = true;
968 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000969 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970}
971
Yves Gerey665174f2018-06-19 15:03:05 +0200972void BasicPortAllocatorSession::OnCandidateReady(Port* port,
973 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700974 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000976 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200977 RTC_LOG(LS_INFO) << port->ToString()
978 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700980 // already done with gathering.
981 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100982 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700983 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700984 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700985 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700986
danilchapf4e8cf02016-06-30 01:55:03 -0700987 // Mark that the port has a pairable candidate, either because we have a
988 // usable candidate from the port, or simply because the port is bound to the
989 // any address and therefore has no host candidate. This will trigger the port
990 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700991 // checks. If port has already been marked as having a pairable candidate,
992 // do nothing here.
993 // Note: We should check whether any candidates may become ready after this
994 // because there we will check whether the candidate is generated by the ready
995 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700996 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700997 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700998 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700999
1000 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001001 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001002 }
1003 // If the current port is not pruned yet, SignalPortReady.
1004 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001005 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
1006 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001007 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001008 }
Honghai Zhang17aac052016-06-29 21:41:53 -07001009 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001010
deadbeef1c5e6d02017-09-15 17:46:56 -07001011 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001012 std::vector<Candidate> candidates;
Qingsi Wang7627fdd2019-08-19 16:07:40 -07001013 candidates.push_back(allocator_->SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001014 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -07001015 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001016 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001017 }
1018
1019 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001020 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001021 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001022 }
1023}
1024
Eldar Relloda13ea22019-06-01 12:23:43 +03001025void BasicPortAllocatorSession::OnCandidateError(
1026 Port* port,
1027 const IceCandidateErrorEvent& event) {
1028 RTC_DCHECK_RUN_ON(network_thread_);
1029 RTC_DCHECK(FindPort(port));
1030
1031 SignalCandidateError(this, event);
1032}
1033
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001034Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
1035 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -07001036 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001037 Port* best_turn_port = nullptr;
1038 for (const PortData& data : ports_) {
1039 if (data.port()->Network()->name() == network_name &&
1040 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
1041 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
1042 best_turn_port = data.port();
1043 }
1044 }
1045 return best_turn_port;
1046}
1047
1048bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -07001049 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001050 // Note: We determine the same network based only on their network names. So
1051 // if an IPv4 address and an IPv6 address have the same network name, they
1052 // are considered the same network here.
1053 const std::string& network_name = newly_pairable_turn_port->Network()->name();
1054 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
1055 // |port| is already in the list of ports, so the best port cannot be nullptr.
1056 RTC_CHECK(best_turn_port != nullptr);
1057
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001058 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001059 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001060 for (PortData& data : ports_) {
1061 if (data.port()->Network()->name() == network_name &&
1062 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
1063 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001064 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001065 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001066 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001067 ports_to_prune.push_back(&data);
1068 } else {
1069 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001070 }
1071 }
1072 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001073
1074 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001075 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1076 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001077 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001078 }
1079 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080}
1081
Honghai Zhanga74363c2016-07-28 18:06:15 -07001082void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001083 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001084 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001085 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001086 }
1087}
1088
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001089void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001090 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001091 RTC_LOG(LS_INFO) << port->ToString()
1092 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001094 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001095
1096 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001097 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001098 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001099 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100
1101 // Moving to COMPLETE state.
Qingsi Wangc129c352019-04-18 10:41:58 -07001102 data->set_state(PortData::STATE_COMPLETE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001103 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001104 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001105}
1106
1107void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001108 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001109 RTC_LOG(LS_INFO) << port->ToString()
1110 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001112 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001113 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001114 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001115 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001116 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001117
1118 // SignalAddressError is currently sent from StunPort/TurnPort.
1119 // But this signal itself is generic.
Qingsi Wangc129c352019-04-18 10:41:58 -07001120 data->set_state(PortData::STATE_ERROR);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001122 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001123}
1124
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001125bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001126 RTC_DCHECK_RUN_ON(network_thread_);
1127
Qingsi Wangc129c352019-04-18 10:41:58 -07001128 return IsAllowedByCandidateFilter(c, candidate_filter_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001129}
1130
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001131bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1132 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001133 RTC_DCHECK_RUN_ON(network_thread_);
1134
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001135 bool candidate_signalable = CheckCandidateFilter(c);
1136
1137 // When device enumeration is disabled (to prevent non-default IP addresses
1138 // from leaking), we ping from some local candidates even though we don't
1139 // signal them. However, if host candidates are also disabled (for example, to
1140 // prevent even default IP addresses from leaking), we still don't want to
1141 // ping from them, even if device enumeration is disabled. Thus, we check for
1142 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001143 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001144 bool can_ping_from_candidate =
1145 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1146 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1147
1148 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001149 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001150 !host_candidates_disabled);
1151}
1152
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001153void BasicPortAllocatorSession::OnPortAllocationComplete(
1154 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001155 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001156 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001157 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001158}
1159
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001160void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001161 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001162 if (CandidatesAllocationDone()) {
1163 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001164 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001165 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001166 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1167 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001168 }
1169 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001171}
1172
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001173void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001174 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001175 for (std::vector<PortData>::iterator iter = ports_.begin();
1176 iter != ports_.end(); ++iter) {
1177 if (port == iter->port()) {
1178 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001179 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001180 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001181 return;
1182 }
1183 }
nissec80e7412017-01-11 05:56:46 -08001184 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001185}
1186
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1188 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001189 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001190 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1191 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001192 if (it->port() == port) {
1193 return &*it;
1194 }
1195 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001196 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001197}
1198
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001199std::vector<BasicPortAllocatorSession::PortData*>
1200BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001201 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001202 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001203 std::vector<PortData*> unpruned_ports;
1204 for (PortData& port : ports_) {
1205 if (!port.pruned() &&
Steve Antonae226f62019-01-29 12:47:38 -08001206 absl::c_linear_search(networks, port.sequence()->network())) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001207 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001208 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001209 }
1210 return unpruned_ports;
1211}
1212
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001213void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001214 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001215 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001216 std::vector<PortInterface*> pruned_ports;
1217 std::vector<Candidate> removed_candidates;
1218 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001219 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001220 data->Prune();
1221 pruned_ports.push_back(data->port());
1222 if (data->has_pairable_candidate()) {
1223 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001224 // Mark the port as having no pairable candidates so that its candidates
1225 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001226 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001227 }
1228 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001229 if (!pruned_ports.empty()) {
1230 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001231 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001232 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001233 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1234 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001235 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001236 }
1237}
1238
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001239// AllocationSequence
1240
1241AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1242 rtc::Network* network,
1243 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001244 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001245 : session_(session),
1246 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001247 config_(config),
1248 state_(kInit),
1249 flags_(flags),
1250 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001251 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001252 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253
Honghai Zhang5048f572016-08-23 15:47:33 -07001254void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001255 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1256 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001257 rtc::SocketAddress(network_->GetBestIP(), 0),
1258 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001260 udp_socket_->SignalReadPacket.connect(this,
1261 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001262 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001263 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1264 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001265 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266}
1267
1268void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001269 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001270 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001271}
1272
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001273void AllocationSequence::OnNetworkFailed() {
1274 RTC_DCHECK(!network_failed_);
1275 network_failed_ = true;
1276 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001277 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001278}
1279
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001280AllocationSequence::~AllocationSequence() {
1281 session_->network_thread()->Clear(this);
1282}
1283
1284void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001285 PortConfiguration* config,
1286 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001287 if (network_failed_) {
1288 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001289 // it won't be equivalent to the new network.
1290 return;
1291 }
1292
deadbeef5c3c1042017-08-04 15:01:57 -07001293 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001294 // Different network setup; nothing is equivalent.
1295 return;
1296 }
1297
1298 // Else turn off the stuff that we've already got covered.
1299
deadbeef1c46a352017-09-27 11:24:05 -07001300 // Every config implicitly specifies local, so turn that off right away if we
1301 // already have a port of the corresponding type. Look for a port that
1302 // matches this AllocationSequence's network, is the right protocol, and
1303 // hasn't encountered an error.
1304 // TODO(deadbeef): This doesn't take into account that there may be another
1305 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1306 // This can happen if, say, there's a network change event right before an
1307 // application-triggered ICE restart. Hopefully this problem will just go
1308 // away if we get rid of the gathering "phases" though, which is planned.
Qingsi Wangc129c352019-04-18 10:41:58 -07001309 //
1310 //
1311 // PORTALLOCATOR_DISABLE_UDP is used to disable a Port from gathering the host
1312 // candidate (and srflx candidate if Port::SharedSocket()), and we do not want
1313 // to disable the gathering of these candidates just becaue of an existing
1314 // Port over PROTO_UDP, namely a TurnPort over UDP.
Steve Antonae226f62019-01-29 12:47:38 -08001315 if (absl::c_any_of(session_->ports_,
1316 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001317 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001318 p.port()->GetProtocol() == PROTO_UDP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001319 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001320 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001321 *flags |= PORTALLOCATOR_DISABLE_UDP;
1322 }
Qingsi Wangc129c352019-04-18 10:41:58 -07001323 // Similarly we need to check both the protocol used by an existing Port and
1324 // its type.
Steve Antonae226f62019-01-29 12:47:38 -08001325 if (absl::c_any_of(session_->ports_,
1326 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001327 return !p.pruned() && p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001328 p.port()->GetProtocol() == PROTO_TCP &&
Qingsi Wangc129c352019-04-18 10:41:58 -07001329 p.port()->Type() == LOCAL_PORT_TYPE && !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001330 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001331 *flags |= PORTALLOCATOR_DISABLE_TCP;
1332 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333
1334 if (config_ && config) {
Qingsi Wangc129c352019-04-18 10:41:58 -07001335 // We need to regather srflx candidates if either of the following
1336 // conditions occurs:
1337 // 1. The STUN servers are different from the previous gathering.
1338 // 2. We will regather host candidates, hence possibly inducing new NAT
1339 // bindings.
1340 if (config_->StunServers() == config->StunServers() &&
1341 (*flags & PORTALLOCATOR_DISABLE_UDP)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 // Already got this STUN servers covered.
1343 *flags |= PORTALLOCATOR_DISABLE_STUN;
1344 }
1345 if (!config_->relays.empty()) {
1346 // Already got relays covered.
1347 // NOTE: This will even skip a _different_ set of relay servers if we
1348 // were to be given one, but that never happens in our codebase. Should
1349 // probably get rid of the list in PortConfiguration and just keep a
1350 // single relay server in each one.
1351 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1352 }
1353 }
1354}
1355
1356void AllocationSequence::Start() {
1357 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001358 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001359 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1360 // called next time, we enable all phases if the best IP has since changed.
1361 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001362}
1363
1364void AllocationSequence::Stop() {
1365 // If the port is completed, don't set it to stopped.
1366 if (state_ == kRunning) {
1367 state_ = kStopped;
1368 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1369 }
1370}
1371
1372void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001373 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1374 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001375
deadbeef1c5e6d02017-09-15 17:46:56 -07001376 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001377
1378 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001379 RTC_LOG(LS_INFO) << network_->ToString()
1380 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001381
1382 switch (phase_) {
1383 case PHASE_UDP:
1384 CreateUDPPorts();
1385 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001386 break;
1387
1388 case PHASE_RELAY:
1389 CreateRelayPorts();
1390 break;
1391
1392 case PHASE_TCP:
1393 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001394 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001395 break;
1396
1397 default:
nissec80e7412017-01-11 05:56:46 -08001398 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001399 }
1400
1401 if (state() == kRunning) {
1402 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001403 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1404 session_->allocator()->step_delay(),
1405 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 } else {
1407 // If all phases in AllocationSequence are completed, no allocation
1408 // steps needed further. Canceling pending signal.
1409 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1410 SignalPortAllocationComplete(this);
1411 }
1412}
1413
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001414void AllocationSequence::CreateUDPPorts() {
1415 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001416 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417 return;
1418 }
1419
1420 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1421 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001422 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001423 bool emit_local_candidate_for_anyaddress =
1424 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001425 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001426 port = UDPPort::Create(
1427 session_->network_thread(), session_->socket_factory(), network_,
1428 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001429 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1430 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001431 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001432 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001433 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001434 session_->allocator()->min_port(), session_->allocator()->max_port(),
1435 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001436 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1437 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001438 }
1439
1440 if (port) {
1441 // If shared socket is enabled, STUN candidate will be allocated by the
1442 // UDPPort.
1443 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001444 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001445 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001446
1447 // If STUN is not disabled, setting stun server address to port.
1448 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001449 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001450 RTC_LOG(LS_INFO)
1451 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001452 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001453 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001454 }
1455 }
1456 }
1457
Steve Antona8f1e562018-10-10 11:29:44 -07001458 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001459 }
1460}
1461
1462void AllocationSequence::CreateTCPPorts() {
1463 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001464 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001465 return;
1466 }
1467
Steve Antona8f1e562018-10-10 11:29:44 -07001468 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001469 session_->network_thread(), session_->socket_factory(), network_,
1470 session_->allocator()->min_port(), session_->allocator()->max_port(),
1471 session_->username(), session_->password(),
1472 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001473 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001474 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001475 // Since TCPPort is not created using shared socket, |port| will not be
1476 // added to the dequeue.
1477 }
1478}
1479
1480void AllocationSequence::CreateStunPorts() {
1481 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001482 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001483 return;
1484 }
1485
1486 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1487 return;
1488 }
1489
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001490 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001491 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492 << "AllocationSequence: No STUN server configured, skipping.";
1493 return;
1494 }
1495
Steve Antona8f1e562018-10-10 11:29:44 -07001496 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001497 session_->network_thread(), session_->socket_factory(), network_,
1498 session_->allocator()->min_port(), session_->allocator()->max_port(),
1499 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001500 session_->allocator()->origin(),
1501 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001502 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001503 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001504 // Since StunPort is not created using shared socket, |port| will not be
1505 // added to the dequeue.
1506 }
1507}
1508
1509void AllocationSequence::CreateRelayPorts() {
1510 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001511 RTC_LOG(LS_VERBOSE)
1512 << "AllocationSequence: Relay ports disabled, skipping.";
1513 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001514 }
1515
1516 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1517 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001518 RTC_DCHECK(config_);
1519 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001520 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001521 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001522 << "AllocationSequence: No relay server configured, skipping.";
1523 return;
1524 }
1525
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001526 for (RelayServerConfig& relay : config_->relays) {
1527 if (relay.type == RELAY_GTURN) {
1528 CreateGturnPort(relay);
1529 } else if (relay.type == RELAY_TURN) {
1530 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001531 } else {
nissec80e7412017-01-11 05:56:46 -08001532 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001533 }
1534 }
1535}
1536
1537void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1538 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001539 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001540 session_->network_thread(), session_->socket_factory(), network_,
1541 session_->allocator()->min_port(), session_->allocator()->max_port(),
1542 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001543 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001544 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001545 // Since RelayPort is not created using shared socket, |port| will not be
1546 // added to the dequeue.
1547 // Note: We must add the allocated port before we add addresses because
1548 // the latter will create candidates that need name and preference
1549 // settings. However, we also can't prepare the address (normally
1550 // done by AddAllocatedPort) until we have these addresses. So we
1551 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001552 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001553
1554 // Add the addresses of this protocol.
1555 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001556 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001557 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001558 port_ptr->AddServerAddress(*relay_port);
1559 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001560 }
1561 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001562 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001563 }
1564}
1565
1566void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1567 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001568 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1569 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001570 // Skip UDP connections to relay servers if it's disallowed.
1571 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1572 relay_port->proto == PROTO_UDP) {
1573 continue;
1574 }
1575
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001576 // Do not create a port if the server address family is known and does
1577 // not match the local IP address family.
1578 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001579 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001580 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG(LS_INFO)
1582 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001583 "Server address: "
1584 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001585 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001586 continue;
1587 }
1588
Jonas Oreland202994c2017-12-18 12:10:43 +01001589 CreateRelayPortArgs args;
1590 args.network_thread = session_->network_thread();
1591 args.socket_factory = session_->socket_factory();
1592 args.network = network_;
1593 args.username = session_->username();
1594 args.password = session_->password();
1595 args.server_address = &(*relay_port);
1596 args.config = &config;
1597 args.origin = session_->allocator()->origin();
1598 args.turn_customizer = session_->allocator()->turn_customizer();
1599
1600 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001601 // Shared socket mode must be enabled only for UDP based ports. Hence
1602 // don't pass shared socket for ports which will create TCP sockets.
1603 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1604 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1605 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001606 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001607 port = session_->allocator()->relay_port_factory()->Create(
1608 args, udp_socket_.get());
1609
1610 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001611 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1612 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001613 continue;
1614 }
1615
1616 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001617 // Listen to the port destroyed signal, to allow AllocationSequence to
1618 // remove entrt from it's map.
1619 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1620 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001621 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001622 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001623 session_->allocator()->max_port());
1624
1625 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001626 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1627 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001628 continue;
1629 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001630 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001631 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001632 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001633 }
1634}
1635
Yves Gerey665174f2018-06-19 15:03:05 +02001636void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1637 const char* data,
1638 size_t size,
1639 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001640 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001641 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001642
1643 bool turn_port_found = false;
1644
1645 // Try to find the TurnPort that matches the remote address. Note that the
1646 // message could be a STUN binding response if the TURN server is also used as
1647 // a STUN server. We don't want to parse every message here to check if it is
1648 // a STUN binding response, so we pass the message to TurnPort regardless of
1649 // the message type. The TurnPort will just ignore the message since it will
1650 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001651 for (auto* port : relay_ports_) {
1652 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001653 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001654 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001655 return;
1656 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001657 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001658 }
1659 }
1660
1661 if (udp_port_) {
1662 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1663
1664 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1665 // the TURN server is also a STUN server.
1666 if (!turn_port_found ||
1667 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001668 RTC_DCHECK(udp_port_->SharedSocket());
1669 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001670 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001671 }
1672 }
1673}
1674
1675void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1676 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001677 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001678 return;
1679 }
1680
Steve Antonae226f62019-01-29 12:47:38 -08001681 auto it = absl::c_find(relay_ports_, port);
Jonas Oreland202994c2017-12-18 12:10:43 +01001682 if (it != relay_ports_.end()) {
1683 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001684 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001685 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001686 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001687 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001688}
1689
1690// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001691PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1692 const std::string& username,
1693 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001694 : stun_address(stun_address), username(username), password(password) {
1695 if (!stun_address.IsNil())
1696 stun_servers.insert(stun_address);
1697}
1698
1699PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1700 const std::string& username,
1701 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001702 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001703 if (!stun_servers.empty())
1704 stun_address = *(stun_servers.begin());
1705}
1706
Steve Anton7995d8c2017-10-30 16:23:38 -07001707PortConfiguration::~PortConfiguration() = default;
1708
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001709ServerAddresses PortConfiguration::StunServers() {
1710 if (!stun_address.IsNil() &&
1711 stun_servers.find(stun_address) == stun_servers.end()) {
1712 stun_servers.insert(stun_address);
1713 }
deadbeefc5d0d952015-07-16 10:22:21 -07001714 // Every UDP TURN server should also be used as a STUN server.
1715 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1716 for (const rtc::SocketAddress& turn_server : turn_servers) {
1717 if (stun_servers.find(turn_server) == stun_servers.end()) {
1718 stun_servers.insert(turn_server);
1719 }
1720 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001721 return stun_servers;
1722}
1723
1724void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1725 relays.push_back(config);
1726}
1727
Yves Gerey665174f2018-06-19 15:03:05 +02001728bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1729 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001730 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001731 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1732 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001733 if (relay_port->proto == type)
1734 return true;
1735 }
1736 return false;
1737}
1738
1739bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1740 ProtocolType type) const {
1741 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001742 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001743 return true;
1744 }
1745 return false;
1746}
1747
1748ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001749 RelayType turn_type,
1750 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001751 ServerAddresses servers;
1752 for (size_t i = 0; i < relays.size(); ++i) {
1753 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1754 servers.insert(relays[i].ports.front().address);
1755 }
1756 }
1757 return servers;
1758}
1759
1760} // namespace cricket