blob: 0c2fef3112605796b683c5edd5801dfe7478c677 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "p2p/client/basicportallocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
Qingsi Wang10a0e512018-05-16 13:37:03 -070014#include <functional>
Steve Anton6c38cc72017-11-29 10:25:58 -080015#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <string>
17#include <vector>
18
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "p2p/base/basicpacketsocketfactory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "p2p/base/port.h"
21#include "p2p/base/relayport.h"
22#include "p2p/base/stunport.h"
23#include "p2p/base/tcpport.h"
24#include "p2p/base/turnport.h"
25#include "p2p/base/udpport.h"
26#include "rtc_base/checks.h"
27#include "rtc_base/helpers.h"
28#include "rtc_base/logging.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070029#include "system_wrappers/include/metrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000030
31using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33namespace {
34
35enum {
36 MSG_CONFIG_START,
37 MSG_CONFIG_READY,
38 MSG_ALLOCATE,
39 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000040 MSG_SEQUENCEOBJECTS_CREATED,
41 MSG_CONFIG_STOP,
42};
43
44const int PHASE_UDP = 0;
45const int PHASE_RELAY = 1;
46const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000047
deadbeef1c5e6d02017-09-15 17:46:56 -070048const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049
zhihuang696f8ca2017-06-27 15:11:24 -070050// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070051int GetProtocolPriority(cricket::ProtocolType protocol) {
52 switch (protocol) {
53 case cricket::PROTO_UDP:
54 return 2;
55 case cricket::PROTO_TCP:
56 return 1;
57 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070058 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070059 return 0;
60 default:
nisseeb4ca4e2017-01-12 02:24:27 -080061 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070062 return 0;
63 }
64}
65// Gets address family priority: IPv6 > IPv4 > Unspecified.
66int GetAddressFamilyPriority(int ip_family) {
67 switch (ip_family) {
68 case AF_INET6:
69 return 2;
70 case AF_INET:
71 return 1;
72 default:
nisseeb4ca4e2017-01-12 02:24:27 -080073 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070074 return 0;
75 }
76}
77
78// Returns positive if a is better, negative if b is better, and 0 otherwise.
79int ComparePort(const cricket::Port* a, const cricket::Port* b) {
80 int a_protocol = GetProtocolPriority(a->GetProtocol());
81 int b_protocol = GetProtocolPriority(b->GetProtocol());
82 int cmp_protocol = a_protocol - b_protocol;
83 if (cmp_protocol != 0) {
84 return cmp_protocol;
85 }
86
87 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
88 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
89 return a_family - b_family;
90}
91
Qingsi Wang10a0e512018-05-16 13:37:03 -070092struct NetworkFilter {
93 using Predicate = std::function<bool(rtc::Network*)>;
94 NetworkFilter(Predicate pred, const std::string& description)
95 : pred(pred), description(description) {}
96 Predicate pred;
97 const std::string description;
98};
99
100using NetworkList = rtc::NetworkManager::NetworkList;
101void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
102 auto start_to_remove =
103 std::remove_if(networks->begin(), networks->end(), filter.pred);
104 if (start_to_remove == networks->end()) {
105 return;
106 }
107 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
108 for (auto it = start_to_remove; it != networks->end(); ++it) {
109 RTC_LOG(INFO) << (*it)->ToString();
110 }
111 networks->erase(start_to_remove, networks->end());
112}
113
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114} // namespace
115
116namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200117const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700118 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
119 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120
121// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200122BasicPortAllocator::BasicPortAllocator(
123 rtc::NetworkManager* network_manager,
124 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100125 webrtc::TurnCustomizer* customizer,
126 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700127 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100128 InitRelayPortFactory(relay_port_factory);
129 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800130 RTC_DCHECK(network_manager_ != nullptr);
131 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200132 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
133 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134 Construct();
135}
136
Yves Gerey665174f2018-06-19 15:03:05 +0200137BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700138 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100139 InitRelayPortFactory(nullptr);
140 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800141 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 Construct();
143}
144
Yves Gerey665174f2018-06-19 15:03:05 +0200145BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
146 rtc::PacketSocketFactory* socket_factory,
147 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700148 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100149 InitRelayPortFactory(nullptr);
150 RTC_DCHECK(relay_port_factory_ != nullptr);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000151 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200152 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
153 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 Construct();
155}
156
157BasicPortAllocator::BasicPortAllocator(
158 rtc::NetworkManager* network_manager,
159 const ServerAddresses& stun_servers,
160 const rtc::SocketAddress& relay_address_udp,
161 const rtc::SocketAddress& relay_address_tcp,
162 const rtc::SocketAddress& relay_address_ssl)
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000163 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100164 InitRelayPortFactory(nullptr);
165 RTC_DCHECK(relay_port_factory_ != nullptr);
166 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700167 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800169 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000170 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800171 }
172 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800174 }
175 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800177 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178
deadbeef653b8e02015-11-11 12:55:10 -0800179 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700180 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800181 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182
Jonas Orelandbdcee282017-10-10 14:01:40 +0200183 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 Construct();
185}
186
187void BasicPortAllocator::Construct() {
188 allow_tcp_listen_ = true;
189}
190
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700191void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
192 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700193 // If the session has not been taken by an active channel, do not report the
194 // metric.
195 for (auto& allocator_session : pooled_sessions()) {
196 if (allocator_session.get() == session) {
197 return;
198 }
199 }
200
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700201 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
202 static_cast<int>(reason),
203 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700204}
205
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700207 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800208 // Our created port allocator sessions depend on us, so destroy our remaining
209 // pooled sessions before anything else.
210 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211}
212
Steve Anton7995d8c2017-10-30 16:23:38 -0700213void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
214 // TODO(phoglund): implement support for other types than loopback.
215 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
216 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700217 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700218 network_ignore_mask_ = network_ignore_mask;
219}
220
deadbeefc5d0d952015-07-16 10:22:21 -0700221PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200222 const std::string& content_name,
223 int component,
224 const std::string& ice_ufrag,
225 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700226 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700227 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000228 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700229 session->SignalIceRegathering.connect(this,
230 &BasicPortAllocator::OnIceRegathering);
231 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232}
233
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700234void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700235 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700236 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
237 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700238 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200239 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700240}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241
Jonas Oreland202994c2017-12-18 12:10:43 +0100242void BasicPortAllocator::InitRelayPortFactory(
243 RelayPortFactoryInterface* relay_port_factory) {
244 if (relay_port_factory != nullptr) {
245 relay_port_factory_ = relay_port_factory;
246 } else {
247 default_relay_port_factory_.reset(new TurnPortFactory());
248 relay_port_factory_ = default_relay_port_factory_.get();
249 }
250}
251
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252// BasicPortAllocatorSession
253BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700254 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 const std::string& content_name,
256 int component,
257 const std::string& ice_ufrag,
258 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700259 : PortAllocatorSession(content_name,
260 component,
261 ice_ufrag,
262 ice_pwd,
263 allocator->flags()),
264 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700265 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 socket_factory_(allocator->socket_factory()),
267 allocation_started_(false),
268 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700269 allocation_sequences_created_(false),
270 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271 allocator_->network_manager()->SignalNetworksChanged.connect(
272 this, &BasicPortAllocatorSession::OnNetworksChanged);
273 allocator_->network_manager()->StartUpdating();
274}
275
276BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700277 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000278 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000279 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000280 network_thread_->Clear(this);
281
Peter Boström0c4e06b2015-10-07 12:23:21 +0200282 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 // AllocationSequence should clear it's map entry for turn ports before
284 // ports are destroyed.
285 sequences_[i]->Clear();
286 }
287
288 std::vector<PortData>::iterator it;
289 for (it = ports_.begin(); it != ports_.end(); it++)
290 delete it->port();
291
Peter Boström0c4e06b2015-10-07 12:23:21 +0200292 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 delete configs_[i];
294
Peter Boström0c4e06b2015-10-07 12:23:21 +0200295 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 delete sequences_[i];
297}
298
Steve Anton7995d8c2017-10-30 16:23:38 -0700299BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700300 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700301 return allocator_;
302}
303
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700304void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700305 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700306 if (filter == candidate_filter_) {
307 return;
308 }
309 // We assume the filter will only change from "ALL" to something else.
310 RTC_DCHECK(candidate_filter_ == CF_ALL);
311 candidate_filter_ = filter;
312 for (PortData& port : ports_) {
313 if (!port.has_pairable_candidate()) {
314 continue;
315 }
316 const auto& candidates = port.port()->Candidates();
317 // Setting a filter may cause a ready port to become non-ready
318 // if it no longer has any pairable candidates.
319 if (!std::any_of(candidates.begin(), candidates.end(),
320 [this, &port](const Candidate& candidate) {
321 return CandidatePairable(candidate, port.port());
322 })) {
323 port.set_has_pairable_candidate(false);
324 }
325 }
326}
327
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700329 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700330 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331 if (!socket_factory_) {
332 owned_socket_factory_.reset(
333 new rtc::BasicPacketSocketFactory(network_thread_));
334 socket_factory_ = owned_socket_factory_.get();
335 }
336
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700337 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700338
Mirko Bonadei675513b2017-11-09 11:09:25 +0100339 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
340 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000341}
342
343void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700344 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700345 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700346 // Note: this must be called after ClearGettingPorts because both may set the
347 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700348 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700349}
350
351void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700352 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700354 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700356 }
deadbeefb60a8192016-08-24 15:15:00 -0700357 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700358 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700359}
360
Steve Anton7995d8c2017-10-30 16:23:38 -0700361bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700362 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700363 return state_ == SessionState::GATHERING;
364}
365
366bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700367 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700368 return state_ == SessionState::CLEARED;
369}
370
371bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700372 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700373 return state_ == SessionState::STOPPED;
374}
375
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700376std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700377 RTC_DCHECK_RUN_ON(network_thread_);
378
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700379 std::vector<rtc::Network*> networks = GetNetworks();
380
381 // A network interface may have both IPv4 and IPv6 networks. Only if
382 // neither of the networks has any connections, the network interface
383 // is considered failed and need to be regathered on.
384 std::set<std::string> networks_with_connection;
385 for (const PortData& data : ports_) {
386 Port* port = data.port();
387 if (!port->connections().empty()) {
388 networks_with_connection.insert(port->Network()->name());
389 }
390 }
391
392 networks.erase(
393 std::remove_if(networks.begin(), networks.end(),
394 [networks_with_connection](rtc::Network* network) {
395 // If a network does not have any connection, it is
396 // considered failed.
397 return networks_with_connection.find(network->name()) !=
398 networks_with_connection.end();
399 }),
400 networks.end());
401 return networks;
402}
403
404void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700405 RTC_DCHECK_RUN_ON(network_thread_);
406
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700407 // Find the list of networks that have no connection.
408 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
409 if (failed_networks.empty()) {
410 return;
411 }
412
Mirko Bonadei675513b2017-11-09 11:09:25 +0100413 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700414
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700415 // Mark a sequence as "network failed" if its network is in the list of failed
416 // networks, so that it won't be considered as equivalent when the session
417 // regathers ports and candidates.
418 for (AllocationSequence* sequence : sequences_) {
419 if (!sequence->network_failed() &&
420 std::find(failed_networks.begin(), failed_networks.end(),
421 sequence->network()) != failed_networks.end()) {
422 sequence->set_network_failed();
423 }
424 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700425
426 bool disable_equivalent_phases = true;
427 Regather(failed_networks, disable_equivalent_phases,
428 IceRegatheringReason::NETWORK_FAILURE);
429}
430
431void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700432 RTC_DCHECK_RUN_ON(network_thread_);
433
Steve Anton300bf8e2017-07-14 10:13:10 -0700434 std::vector<rtc::Network*> networks = GetNetworks();
435 if (networks.empty()) {
436 return;
437 }
438
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700440
441 // We expect to generate candidates that are equivalent to what we have now.
442 // Force DoAllocate to generate them instead of skipping.
443 bool disable_equivalent_phases = false;
444 Regather(networks, disable_equivalent_phases,
445 IceRegatheringReason::OCCASIONAL_REFRESH);
446}
447
448void BasicPortAllocatorSession::Regather(
449 const std::vector<rtc::Network*>& networks,
450 bool disable_equivalent_phases,
451 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700452 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700453 // Remove ports from being used locally and send signaling to remove
454 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700455 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700456 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000458 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700459 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700460
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700461 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700462 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700463
Steve Anton300bf8e2017-07-14 10:13:10 -0700464 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700465 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466}
467
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800468void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200469 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700470 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800471 auto ports = ReadyPorts();
472 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800473 // The port type and protocol can be used to identify different subclasses
474 // of Port in the current implementation. Note that a TCPPort has the type
475 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
476 if (port->Type() == STUN_PORT_TYPE ||
477 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800478 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
479 stun_keepalive_interval);
480 }
481 }
482}
483
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700484std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700485 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700486 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700487 for (const PortData& data : ports_) {
488 if (data.ready()) {
489 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700490 }
491 }
492 return ret;
493}
494
495std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700496 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700497 std::vector<Candidate> candidates;
498 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700499 if (!data.ready()) {
500 continue;
501 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700502 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700503 }
504 return candidates;
505}
506
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700507void BasicPortAllocatorSession::GetCandidatesFromPort(
508 const PortData& data,
509 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700510 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700511 RTC_CHECK(candidates != nullptr);
512 for (const Candidate& candidate : data.port()->Candidates()) {
513 if (!CheckCandidateFilter(candidate)) {
514 continue;
515 }
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700516 auto sanitized_candidate = SanitizeCandidate(candidate);
517 candidates->push_back(sanitized_candidate);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700518 }
519}
520
Jeroen de Borst72d2ddd2018-11-27 13:20:39 -0800521bool BasicPortAllocatorSession::MdnsObfuscationEnabled() const {
522 return allocator_->network_manager()->GetMdnsResponder() != nullptr;
523}
524
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700525Candidate BasicPortAllocatorSession::SanitizeCandidate(
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700526 const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -0700527 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700528 Candidate copy = c;
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700529 // If the candidate has a generated hostname, we need to obfuscate its IP
530 // address when signaling this candidate.
531 if (!c.address().hostname().empty() && !c.address().IsUnresolvedIP()) {
532 rtc::SocketAddress hostname_only_addr(c.address().hostname(),
533 c.address().port());
534 copy.set_address(hostname_only_addr);
535 }
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700536 // If adapter enumeration is disabled or host candidates are disabled,
537 // clear the raddr of STUN candidates to avoid local address leakage.
538 bool filter_stun_related_address =
539 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
540 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
Jeroen de Borst72d2ddd2018-11-27 13:20:39 -0800541 !(candidate_filter_ & CF_HOST) || MdnsObfuscationEnabled();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700542 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
543 // to avoid reflexive address leakage.
544 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
545 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
546 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
547 copy.set_related_address(
548 rtc::EmptySocketAddressWithFamily(copy.address().family()));
549 }
550 return copy;
551}
552
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700553bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700554 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700555 // Done only if all required AllocationSequence objects
556 // are created.
557 if (!allocation_sequences_created_) {
558 return false;
559 }
560
561 // Check that all port allocation sequences are complete (not running).
562 if (std::any_of(sequences_.begin(), sequences_.end(),
563 [](const AllocationSequence* sequence) {
564 return sequence->state() == AllocationSequence::kRunning;
565 })) {
566 return false;
567 }
568
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700569 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700570 // expected candidates. Session will trigger candidates allocation complete
571 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700572 return std::none_of(ports_.begin(), ports_.end(),
573 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700574}
575
Yves Gerey665174f2018-06-19 15:03:05 +0200576void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000577 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200578 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200579 GetPortConfigurations();
580 break;
581 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200582 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
583 break;
584 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200585 OnAllocate();
586 break;
587 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200588 OnAllocationSequenceObjectsCreated();
589 break;
590 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200591 OnConfigStop();
592 break;
593 default:
594 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595 }
596}
597
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700598void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700599 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700600 for (PortData& port : ports_) {
601 port.port()->set_content_name(content_name());
602 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
603 }
604}
605
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000606void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700607 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +0200608 PortConfiguration* config =
609 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000610
deadbeef653b8e02015-11-11 12:55:10 -0800611 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
612 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 }
614 ConfigReady(config);
615}
616
617void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700618 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700619 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000620}
621
622// Adds a configuration to the list.
623void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700624 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800625 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800627 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000628
629 AllocatePorts();
630}
631
632void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700633 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634
635 // If any of the allocated ports have not completed the candidates allocation,
636 // mark those as error. Since session doesn't need any new candidates
637 // at this stage of the allocation, it's safe to discard any new candidates.
638 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200639 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
640 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700641 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000642 // Updating port state to error, which didn't finish allocating candidates
643 // yet.
644 it->set_error();
645 send_signal = true;
646 }
647 }
648
649 // Did we stop any running sequences?
650 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
651 it != sequences_.end() && !send_signal; ++it) {
652 if ((*it)->state() == AllocationSequence::kStopped) {
653 send_signal = true;
654 }
655 }
656
657 // If we stopped anything that was running, send a done signal now.
658 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000659 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 }
661}
662
663void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700664 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700665 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000666}
667
668void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700669 RTC_DCHECK_RUN_ON(network_thread_);
670
Steve Anton300bf8e2017-07-14 10:13:10 -0700671 if (network_manager_started_ && !IsStopped()) {
672 bool disable_equivalent_phases = true;
673 DoAllocate(disable_equivalent_phases);
674 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000675
676 allocation_started_ = true;
677}
678
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700679std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700680 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700681 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700682 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800683 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700684 // If the network permission state is BLOCKED, we just act as if the flag has
685 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700686 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700687 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700688 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
689 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000690 // If the adapter enumeration is disabled, we'll just bind to any address
691 // instead of specific NIC. This is to ensure the same routing for http
692 // traffic by OS is also used here to avoid any local or public IP leakage
693 // during stun process.
694 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
695 network_manager->GetAnyAddressNetworks(&networks);
696 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700697 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000698 // If network enumeration fails, use the ANY address as a fallback, so we
699 // can at least try gathering candidates using the default route chosen by
700 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
701 // set, we'll use ANY address candidates either way.
702 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
703 network_manager->GetAnyAddressNetworks(&networks);
704 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000705 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100706 // Filter out link-local networks if needed.
707 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700708 NetworkFilter link_local_filter(
709 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
710 "link-local");
711 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100712 }
deadbeef3427f532017-07-26 16:09:33 -0700713 // Do some more filtering, depending on the network ignore mask and "disable
714 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700715 NetworkFilter ignored_filter(
716 [this](rtc::Network* network) {
717 return allocator_->network_ignore_mask() & network->type();
718 },
719 "ignored");
720 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700721 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
722 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700723 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000724 // Don't determine the lowest cost from a link-local network.
725 // On iOS, a device connected to the computer will get a link-local
726 // network for communicating with the computer, however this network can't
727 // be used to connect to a peer outside the network.
728 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800729 continue;
730 }
honghaiz60347052016-05-31 18:29:12 -0700731 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
732 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700733 NetworkFilter costly_filter(
734 [lowest_cost](rtc::Network* network) {
735 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
736 },
737 "costly");
738 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700739 }
deadbeef3427f532017-07-26 16:09:33 -0700740 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
741 // default, it's 5), remove networks to ensure that limit is satisfied.
742 //
743 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
744 // networks, we could try to choose a set that's "most likely to work". It's
745 // hard to define what that means though; it's not just "lowest cost".
746 // Alternatively, we could just focus on making our ICE pinging logic smarter
747 // such that this filtering isn't necessary in the first place.
748 int ipv6_networks = 0;
749 for (auto it = networks.begin(); it != networks.end();) {
750 if ((*it)->prefix().family() == AF_INET6) {
751 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
752 it = networks.erase(it);
753 continue;
754 } else {
755 ++ipv6_networks;
756 }
757 }
758 ++it;
759 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700760 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700761}
762
763// For each network, see if we have a sequence that covers it already. If not,
764// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700765void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700766 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700767 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700768 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000769 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100770 RTC_LOG(LS_WARNING)
771 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000772 done_signal_needed = true;
773 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100774 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700775 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200776 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200777 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000778 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
779 // If all the ports are disabled we should just fire the allocation
780 // done event and return.
781 done_signal_needed = true;
782 break;
783 }
784
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000785 if (!config || config->relays.empty()) {
786 // No relay ports specified in this config.
787 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
788 }
789
790 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792 // Skip IPv6 networks unless the flag's been set.
793 continue;
794 }
795
zhihuangb09b3f92017-03-07 14:40:51 -0800796 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
797 networks[i]->GetBestIP().family() == AF_INET6 &&
798 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
799 // Skip IPv6 Wi-Fi networks unless the flag's been set.
800 continue;
801 }
802
Steve Anton300bf8e2017-07-14 10:13:10 -0700803 if (disable_equivalent) {
804 // Disable phases that would only create ports equivalent to
805 // ones that we have already made.
806 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000807
Steve Anton300bf8e2017-07-14 10:13:10 -0700808 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
809 // New AllocationSequence would have nothing to do, so don't make it.
810 continue;
811 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812 }
813
814 AllocationSequence* sequence =
815 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000816 sequence->SignalPortAllocationComplete.connect(
817 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700818 sequence->Init();
819 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000820 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700821 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000822 }
823 }
824 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700825 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000826 }
827}
828
829void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700830 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700831 std::vector<rtc::Network*> networks = GetNetworks();
832 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700833 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700834 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700835 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700836 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700837 std::find(networks.begin(), networks.end(), sequence->network()) ==
838 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700839 sequence->OnNetworkFailed();
840 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700841 }
842 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700843 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
844 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100845 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
846 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000847 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700848 }
honghaiz8c404fa2015-09-28 07:59:43 -0700849
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700850 if (allocation_started_ && !IsStopped()) {
851 if (network_manager_started_) {
852 // If the network manager has started, it must be regathering.
853 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
854 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700855 bool disable_equivalent_phases = true;
856 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700857 }
858
Honghai Zhang5048f572016-08-23 15:47:33 -0700859 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100860 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700861 network_manager_started_ = true;
862 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863}
864
865void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200866 rtc::Network* network,
867 PortConfiguration* config,
868 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700869 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200870 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200871 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200872 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000873 sequences_[i]->DisableEquivalentPhases(network, config, flags);
874 }
875}
876
877void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200878 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700880 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 if (!port)
882 return;
883
Mirko Bonadei675513b2017-11-09 11:09:25 +0100884 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700886 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700888 if (allocator_->proxy().type != rtc::PROXY_NONE)
889 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700890 port->set_send_retransmit_count_attribute(
891 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 PortData data(port, seq);
894 ports_.push_back(data);
895
896 port->SignalCandidateReady.connect(
897 this, &BasicPortAllocatorSession::OnCandidateReady);
898 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200899 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200901 &BasicPortAllocatorSession::OnPortDestroyed);
902 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
903 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904
905 if (prepare_address)
906 port->PrepareAddress();
907}
908
909void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700910 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911 allocation_sequences_created_ = true;
912 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000913 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914}
915
Yves Gerey665174f2018-06-19 15:03:05 +0200916void BasicPortAllocatorSession::OnCandidateReady(Port* port,
917 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700918 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000919 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000920 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200921 RTC_LOG(LS_INFO) << port->ToString()
922 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700924 // already done with gathering.
925 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100926 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700927 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700928 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700929 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700930
danilchapf4e8cf02016-06-30 01:55:03 -0700931 // Mark that the port has a pairable candidate, either because we have a
932 // usable candidate from the port, or simply because the port is bound to the
933 // any address and therefore has no host candidate. This will trigger the port
934 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700935 // checks. If port has already been marked as having a pairable candidate,
936 // do nothing here.
937 // Note: We should check whether any candidates may become ready after this
938 // because there we will check whether the candidate is generated by the ready
939 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700940 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700941 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700942 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700943
944 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700945 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700946 }
947 // If the current port is not pruned yet, SignalPortReady.
948 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000949 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
950 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700951 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700952 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700953 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700954
deadbeef1c5e6d02017-09-15 17:46:56 -0700955 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000956 std::vector<Candidate> candidates;
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700957 candidates.push_back(SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000958 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700959 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100960 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700961 }
962
963 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700964 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000965 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700966 }
967}
968
969Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
970 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -0700971 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700972 Port* best_turn_port = nullptr;
973 for (const PortData& data : ports_) {
974 if (data.port()->Network()->name() == network_name &&
975 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
976 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
977 best_turn_port = data.port();
978 }
979 }
980 return best_turn_port;
981}
982
983bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -0700984 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700985 // Note: We determine the same network based only on their network names. So
986 // if an IPv4 address and an IPv6 address have the same network name, they
987 // are considered the same network here.
988 const std::string& network_name = newly_pairable_turn_port->Network()->name();
989 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
990 // |port| is already in the list of ports, so the best port cannot be nullptr.
991 RTC_CHECK(best_turn_port != nullptr);
992
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700993 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700994 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700995 for (PortData& data : ports_) {
996 if (data.port()->Network()->name() == network_name &&
997 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
998 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700999 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001000 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001001 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001002 ports_to_prune.push_back(&data);
1003 } else {
1004 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001005 }
1006 }
1007 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001008
1009 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001010 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1011 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001012 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001013 }
1014 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001015}
1016
Honghai Zhanga74363c2016-07-28 18:06:15 -07001017void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001018 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001019 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001020 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001021 }
1022}
1023
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001024void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001025 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001026 RTC_LOG(LS_INFO) << port->ToString()
1027 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001028 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001029 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030
1031 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001032 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001033 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001034 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001035
1036 // Moving to COMPLETE state.
1037 data->set_complete();
1038 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001039 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040}
1041
1042void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001043 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001044 RTC_LOG(LS_INFO) << port->ToString()
1045 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001047 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001049 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001050 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001051 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001052
1053 // SignalAddressError is currently sent from StunPort/TurnPort.
1054 // But this signal itself is generic.
1055 data->set_error();
1056 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001057 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001058}
1059
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001060bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001061 RTC_DCHECK_RUN_ON(network_thread_);
1062
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001063 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001064
1065 // When binding to any address, before sending packets out, the getsockname
1066 // returns all 0s, but after sending packets, it'll be the NIC used to
1067 // send. All 0s is not a valid ICE candidate address and should be filtered
1068 // out.
1069 if (c.address().IsAnyIP()) {
1070 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001071 }
1072
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001073 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001074 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001075 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001076 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001077 } else if (c.type() == LOCAL_PORT_TYPE) {
1078 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1079 // We allow host candidates if the filter allows server-reflexive
1080 // candidates and the candidate is a public IP. Because we don't generate
1081 // server-reflexive candidates if they have the same IP as the host
1082 // candidate (i.e. when the host candidate is a public IP), filtering to
1083 // only server-reflexive candidates won't work right when the host
1084 // candidates have public IPs.
1085 return true;
1086 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001087
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001088 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001089 }
1090 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001091}
1092
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001093bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1094 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001095 RTC_DCHECK_RUN_ON(network_thread_);
1096
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001097 bool candidate_signalable = CheckCandidateFilter(c);
1098
1099 // When device enumeration is disabled (to prevent non-default IP addresses
1100 // from leaking), we ping from some local candidates even though we don't
1101 // signal them. However, if host candidates are also disabled (for example, to
1102 // prevent even default IP addresses from leaking), we still don't want to
1103 // ping from them, even if device enumeration is disabled. Thus, we check for
1104 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001105 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001106 bool can_ping_from_candidate =
1107 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1108 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1109
1110 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001111 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001112 !host_candidates_disabled);
1113}
1114
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001115void BasicPortAllocatorSession::OnPortAllocationComplete(
1116 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001117 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001118 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001119 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001120}
1121
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001122void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001123 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001124 if (CandidatesAllocationDone()) {
1125 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001126 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001127 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001128 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1129 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001130 }
1131 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133}
1134
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001135void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001136 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001137 for (std::vector<PortData>::iterator iter = ports_.begin();
1138 iter != ports_.end(); ++iter) {
1139 if (port == iter->port()) {
1140 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001141 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001142 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001143 return;
1144 }
1145 }
nissec80e7412017-01-11 05:56:46 -08001146 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001147}
1148
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001149BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1150 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001151 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001152 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1153 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154 if (it->port() == port) {
1155 return &*it;
1156 }
1157 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001158 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001159}
1160
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001161std::vector<BasicPortAllocatorSession::PortData*>
1162BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001163 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001164 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001165 std::vector<PortData*> unpruned_ports;
1166 for (PortData& port : ports_) {
1167 if (!port.pruned() &&
1168 std::find(networks.begin(), networks.end(),
1169 port.sequence()->network()) != networks.end()) {
1170 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001171 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001172 }
1173 return unpruned_ports;
1174}
1175
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001176void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001177 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001178 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001179 std::vector<PortInterface*> pruned_ports;
1180 std::vector<Candidate> removed_candidates;
1181 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001182 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001183 data->Prune();
1184 pruned_ports.push_back(data->port());
1185 if (data->has_pairable_candidate()) {
1186 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001187 // Mark the port as having no pairable candidates so that its candidates
1188 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001189 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001190 }
1191 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001192 if (!pruned_ports.empty()) {
1193 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001194 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001195 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001196 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1197 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001198 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001199 }
1200}
1201
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001202// AllocationSequence
1203
1204AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1205 rtc::Network* network,
1206 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001207 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001208 : session_(session),
1209 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001210 config_(config),
1211 state_(kInit),
1212 flags_(flags),
1213 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001214 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001215 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001216
Honghai Zhang5048f572016-08-23 15:47:33 -07001217void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1219 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001220 rtc::SocketAddress(network_->GetBestIP(), 0),
1221 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001223 udp_socket_->SignalReadPacket.connect(this,
1224 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001225 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001226 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1227 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001229}
1230
1231void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001232 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001233 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001234}
1235
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001236void AllocationSequence::OnNetworkFailed() {
1237 RTC_DCHECK(!network_failed_);
1238 network_failed_ = true;
1239 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001240 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001241}
1242
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243AllocationSequence::~AllocationSequence() {
1244 session_->network_thread()->Clear(this);
1245}
1246
1247void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001248 PortConfiguration* config,
1249 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001250 if (network_failed_) {
1251 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001252 // it won't be equivalent to the new network.
1253 return;
1254 }
1255
deadbeef5c3c1042017-08-04 15:01:57 -07001256 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001257 // Different network setup; nothing is equivalent.
1258 return;
1259 }
1260
1261 // Else turn off the stuff that we've already got covered.
1262
deadbeef1c46a352017-09-27 11:24:05 -07001263 // Every config implicitly specifies local, so turn that off right away if we
1264 // already have a port of the corresponding type. Look for a port that
1265 // matches this AllocationSequence's network, is the right protocol, and
1266 // hasn't encountered an error.
1267 // TODO(deadbeef): This doesn't take into account that there may be another
1268 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1269 // This can happen if, say, there's a network change event right before an
1270 // application-triggered ICE restart. Hopefully this problem will just go
1271 // away if we get rid of the gathering "phases" though, which is planned.
1272 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1273 [this](const BasicPortAllocatorSession::PortData& p) {
1274 return p.port()->Network() == network_ &&
1275 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1276 })) {
1277 *flags |= PORTALLOCATOR_DISABLE_UDP;
1278 }
1279 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1280 [this](const BasicPortAllocatorSession::PortData& p) {
1281 return p.port()->Network() == network_ &&
1282 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1283 })) {
1284 *flags |= PORTALLOCATOR_DISABLE_TCP;
1285 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001286
1287 if (config_ && config) {
1288 if (config_->StunServers() == config->StunServers()) {
1289 // Already got this STUN servers covered.
1290 *flags |= PORTALLOCATOR_DISABLE_STUN;
1291 }
1292 if (!config_->relays.empty()) {
1293 // Already got relays covered.
1294 // NOTE: This will even skip a _different_ set of relay servers if we
1295 // were to be given one, but that never happens in our codebase. Should
1296 // probably get rid of the list in PortConfiguration and just keep a
1297 // single relay server in each one.
1298 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1299 }
1300 }
1301}
1302
1303void AllocationSequence::Start() {
1304 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001305 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001306 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1307 // called next time, we enable all phases if the best IP has since changed.
1308 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001309}
1310
1311void AllocationSequence::Stop() {
1312 // If the port is completed, don't set it to stopped.
1313 if (state_ == kRunning) {
1314 state_ = kStopped;
1315 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1316 }
1317}
1318
1319void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001320 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1321 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322
deadbeef1c5e6d02017-09-15 17:46:56 -07001323 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001324
1325 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001326 RTC_LOG(LS_INFO) << network_->ToString()
1327 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001328
1329 switch (phase_) {
1330 case PHASE_UDP:
1331 CreateUDPPorts();
1332 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333 break;
1334
1335 case PHASE_RELAY:
1336 CreateRelayPorts();
1337 break;
1338
1339 case PHASE_TCP:
1340 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001341 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 break;
1343
1344 default:
nissec80e7412017-01-11 05:56:46 -08001345 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346 }
1347
1348 if (state() == kRunning) {
1349 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001350 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1351 session_->allocator()->step_delay(),
1352 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001353 } else {
1354 // If all phases in AllocationSequence are completed, no allocation
1355 // steps needed further. Canceling pending signal.
1356 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1357 SignalPortAllocationComplete(this);
1358 }
1359}
1360
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001361void AllocationSequence::CreateUDPPorts() {
1362 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001363 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001364 return;
1365 }
1366
1367 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1368 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001369 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001370 bool emit_local_candidate_for_anyaddress =
1371 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001373 port = UDPPort::Create(
1374 session_->network_thread(), session_->socket_factory(), network_,
1375 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001376 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1377 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001379 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001380 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001381 session_->allocator()->min_port(), session_->allocator()->max_port(),
1382 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001383 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1384 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385 }
1386
1387 if (port) {
1388 // If shared socket is enabled, STUN candidate will be allocated by the
1389 // UDPPort.
1390 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001391 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001392 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001393
1394 // If STUN is not disabled, setting stun server address to port.
1395 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001396 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001397 RTC_LOG(LS_INFO)
1398 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001399 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001400 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001401 }
1402 }
1403 }
1404
Steve Antona8f1e562018-10-10 11:29:44 -07001405 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 }
1407}
1408
1409void AllocationSequence::CreateTCPPorts() {
1410 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001411 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412 return;
1413 }
1414
Steve Antona8f1e562018-10-10 11:29:44 -07001415 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001416 session_->network_thread(), session_->socket_factory(), network_,
1417 session_->allocator()->min_port(), session_->allocator()->max_port(),
1418 session_->username(), session_->password(),
1419 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001420 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001421 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 // Since TCPPort is not created using shared socket, |port| will not be
1423 // added to the dequeue.
1424 }
1425}
1426
1427void AllocationSequence::CreateStunPorts() {
1428 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001429 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001430 return;
1431 }
1432
1433 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1434 return;
1435 }
1436
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001437 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001438 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001439 << "AllocationSequence: No STUN server configured, skipping.";
1440 return;
1441 }
1442
Steve Antona8f1e562018-10-10 11:29:44 -07001443 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001444 session_->network_thread(), session_->socket_factory(), network_,
1445 session_->allocator()->min_port(), session_->allocator()->max_port(),
1446 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001447 session_->allocator()->origin(),
1448 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001449 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001450 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001451 // Since StunPort is not created using shared socket, |port| will not be
1452 // added to the dequeue.
1453 }
1454}
1455
1456void AllocationSequence::CreateRelayPorts() {
1457 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001458 RTC_LOG(LS_VERBOSE)
1459 << "AllocationSequence: Relay ports disabled, skipping.";
1460 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001461 }
1462
1463 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1464 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001465 RTC_DCHECK(config_);
1466 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001467 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001468 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001469 << "AllocationSequence: No relay server configured, skipping.";
1470 return;
1471 }
1472
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001473 for (RelayServerConfig& relay : config_->relays) {
1474 if (relay.type == RELAY_GTURN) {
1475 CreateGturnPort(relay);
1476 } else if (relay.type == RELAY_TURN) {
1477 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001478 } else {
nissec80e7412017-01-11 05:56:46 -08001479 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001480 }
1481 }
1482}
1483
1484void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1485 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001486 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001487 session_->network_thread(), session_->socket_factory(), network_,
1488 session_->allocator()->min_port(), session_->allocator()->max_port(),
1489 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001490 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001491 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492 // Since RelayPort is not created using shared socket, |port| will not be
1493 // added to the dequeue.
1494 // Note: We must add the allocated port before we add addresses because
1495 // the latter will create candidates that need name and preference
1496 // settings. However, we also can't prepare the address (normally
1497 // done by AddAllocatedPort) until we have these addresses. So we
1498 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001499 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001500
1501 // Add the addresses of this protocol.
1502 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001503 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001504 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001505 port_ptr->AddServerAddress(*relay_port);
1506 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001507 }
1508 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001509 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001510 }
1511}
1512
1513void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1514 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001515 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1516 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001517 // Skip UDP connections to relay servers if it's disallowed.
1518 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1519 relay_port->proto == PROTO_UDP) {
1520 continue;
1521 }
1522
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001523 // Do not create a port if the server address family is known and does
1524 // not match the local IP address family.
1525 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001526 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001527 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001528 RTC_LOG(LS_INFO)
1529 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001530 "Server address: "
1531 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001532 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001533 continue;
1534 }
1535
Jonas Oreland202994c2017-12-18 12:10:43 +01001536 CreateRelayPortArgs args;
1537 args.network_thread = session_->network_thread();
1538 args.socket_factory = session_->socket_factory();
1539 args.network = network_;
1540 args.username = session_->username();
1541 args.password = session_->password();
1542 args.server_address = &(*relay_port);
1543 args.config = &config;
1544 args.origin = session_->allocator()->origin();
1545 args.turn_customizer = session_->allocator()->turn_customizer();
1546
1547 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001548 // Shared socket mode must be enabled only for UDP based ports. Hence
1549 // don't pass shared socket for ports which will create TCP sockets.
1550 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1551 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1552 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001553 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001554 port = session_->allocator()->relay_port_factory()->Create(
1555 args, udp_socket_.get());
1556
1557 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001558 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1559 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001560 continue;
1561 }
1562
1563 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001564 // Listen to the port destroyed signal, to allow AllocationSequence to
1565 // remove entrt from it's map.
1566 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1567 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001568 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001569 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001570 session_->allocator()->max_port());
1571
1572 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001573 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1574 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001575 continue;
1576 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001577 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001578 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001579 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001580 }
1581}
1582
Yves Gerey665174f2018-06-19 15:03:05 +02001583void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1584 const char* data,
1585 size_t size,
1586 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001587 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001588 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001589
1590 bool turn_port_found = false;
1591
1592 // Try to find the TurnPort that matches the remote address. Note that the
1593 // message could be a STUN binding response if the TURN server is also used as
1594 // a STUN server. We don't want to parse every message here to check if it is
1595 // a STUN binding response, so we pass the message to TurnPort regardless of
1596 // the message type. The TurnPort will just ignore the message since it will
1597 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001598 for (auto* port : relay_ports_) {
1599 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001600 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001601 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001602 return;
1603 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001604 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001605 }
1606 }
1607
1608 if (udp_port_) {
1609 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1610
1611 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1612 // the TURN server is also a STUN server.
1613 if (!turn_port_found ||
1614 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001615 RTC_DCHECK(udp_port_->SharedSocket());
1616 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001617 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001618 }
1619 }
1620}
1621
1622void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1623 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001624 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001625 return;
1626 }
1627
Jonas Oreland202994c2017-12-18 12:10:43 +01001628 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1629 if (it != relay_ports_.end()) {
1630 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001631 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001632 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001633 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001634 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001635}
1636
1637// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001638PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1639 const std::string& username,
1640 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001641 : stun_address(stun_address), username(username), password(password) {
1642 if (!stun_address.IsNil())
1643 stun_servers.insert(stun_address);
1644}
1645
1646PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1647 const std::string& username,
1648 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001649 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001650 if (!stun_servers.empty())
1651 stun_address = *(stun_servers.begin());
1652}
1653
Steve Anton7995d8c2017-10-30 16:23:38 -07001654PortConfiguration::~PortConfiguration() = default;
1655
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001656ServerAddresses PortConfiguration::StunServers() {
1657 if (!stun_address.IsNil() &&
1658 stun_servers.find(stun_address) == stun_servers.end()) {
1659 stun_servers.insert(stun_address);
1660 }
deadbeefc5d0d952015-07-16 10:22:21 -07001661 // Every UDP TURN server should also be used as a STUN server.
1662 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1663 for (const rtc::SocketAddress& turn_server : turn_servers) {
1664 if (stun_servers.find(turn_server) == stun_servers.end()) {
1665 stun_servers.insert(turn_server);
1666 }
1667 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001668 return stun_servers;
1669}
1670
1671void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1672 relays.push_back(config);
1673}
1674
Yves Gerey665174f2018-06-19 15:03:05 +02001675bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1676 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001677 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001678 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1679 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001680 if (relay_port->proto == type)
1681 return true;
1682 }
1683 return false;
1684}
1685
1686bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1687 ProtocolType type) const {
1688 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001689 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001690 return true;
1691 }
1692 return false;
1693}
1694
1695ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001696 RelayType turn_type,
1697 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001698 ServerAddresses servers;
1699 for (size_t i = 0; i < relays.size(); ++i) {
1700 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1701 servers.insert(relays[i].ports.front().address);
1702 }
1703 }
1704 return servers;
1705}
1706
1707} // namespace cricket