blob: 5b48f5e9d79b5d5376898b1861032a951eb8e06f [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),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000265 network_thread_(NULL),
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() {
277 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000278 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279 network_thread_->Clear(this);
280
Peter Boström0c4e06b2015-10-07 12:23:21 +0200281 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282 // AllocationSequence should clear it's map entry for turn ports before
283 // ports are destroyed.
284 sequences_[i]->Clear();
285 }
286
287 std::vector<PortData>::iterator it;
288 for (it = ports_.begin(); it != ports_.end(); it++)
289 delete it->port();
290
Peter Boström0c4e06b2015-10-07 12:23:21 +0200291 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 delete configs_[i];
293
Peter Boström0c4e06b2015-10-07 12:23:21 +0200294 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 delete sequences_[i];
296}
297
Steve Anton7995d8c2017-10-30 16:23:38 -0700298BasicPortAllocator* BasicPortAllocatorSession::allocator() {
299 return allocator_;
300}
301
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700302void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
303 if (filter == candidate_filter_) {
304 return;
305 }
306 // We assume the filter will only change from "ALL" to something else.
307 RTC_DCHECK(candidate_filter_ == CF_ALL);
308 candidate_filter_ = filter;
309 for (PortData& port : ports_) {
310 if (!port.has_pairable_candidate()) {
311 continue;
312 }
313 const auto& candidates = port.port()->Candidates();
314 // Setting a filter may cause a ready port to become non-ready
315 // if it no longer has any pairable candidates.
316 if (!std::any_of(candidates.begin(), candidates.end(),
317 [this, &port](const Candidate& candidate) {
318 return CandidatePairable(candidate, port.port());
319 })) {
320 port.set_has_pairable_candidate(false);
321 }
322 }
323}
324
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000325void BasicPortAllocatorSession::StartGettingPorts() {
326 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700327 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328 if (!socket_factory_) {
329 owned_socket_factory_.reset(
330 new rtc::BasicPacketSocketFactory(network_thread_));
331 socket_factory_ = owned_socket_factory_.get();
332 }
333
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700334 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700335
Mirko Bonadei675513b2017-11-09 11:09:25 +0100336 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
337 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000338}
339
340void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800341 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700342 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700343 // Note: this must be called after ClearGettingPorts because both may set the
344 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700345 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700346}
347
348void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800349 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000350 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700351 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700353 }
deadbeefb60a8192016-08-24 15:15:00 -0700354 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700355 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700356}
357
Steve Anton7995d8c2017-10-30 16:23:38 -0700358bool BasicPortAllocatorSession::IsGettingPorts() {
359 return state_ == SessionState::GATHERING;
360}
361
362bool BasicPortAllocatorSession::IsCleared() const {
363 return state_ == SessionState::CLEARED;
364}
365
366bool BasicPortAllocatorSession::IsStopped() const {
367 return state_ == SessionState::STOPPED;
368}
369
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700370std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
371 std::vector<rtc::Network*> networks = GetNetworks();
372
373 // A network interface may have both IPv4 and IPv6 networks. Only if
374 // neither of the networks has any connections, the network interface
375 // is considered failed and need to be regathered on.
376 std::set<std::string> networks_with_connection;
377 for (const PortData& data : ports_) {
378 Port* port = data.port();
379 if (!port->connections().empty()) {
380 networks_with_connection.insert(port->Network()->name());
381 }
382 }
383
384 networks.erase(
385 std::remove_if(networks.begin(), networks.end(),
386 [networks_with_connection](rtc::Network* network) {
387 // If a network does not have any connection, it is
388 // considered failed.
389 return networks_with_connection.find(network->name()) !=
390 networks_with_connection.end();
391 }),
392 networks.end());
393 return networks;
394}
395
396void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
397 // Find the list of networks that have no connection.
398 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
399 if (failed_networks.empty()) {
400 return;
401 }
402
Mirko Bonadei675513b2017-11-09 11:09:25 +0100403 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700404
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700405 // Mark a sequence as "network failed" if its network is in the list of failed
406 // networks, so that it won't be considered as equivalent when the session
407 // regathers ports and candidates.
408 for (AllocationSequence* sequence : sequences_) {
409 if (!sequence->network_failed() &&
410 std::find(failed_networks.begin(), failed_networks.end(),
411 sequence->network()) != failed_networks.end()) {
412 sequence->set_network_failed();
413 }
414 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700415
416 bool disable_equivalent_phases = true;
417 Regather(failed_networks, disable_equivalent_phases,
418 IceRegatheringReason::NETWORK_FAILURE);
419}
420
421void BasicPortAllocatorSession::RegatherOnAllNetworks() {
422 std::vector<rtc::Network*> networks = GetNetworks();
423 if (networks.empty()) {
424 return;
425 }
426
Mirko Bonadei675513b2017-11-09 11:09:25 +0100427 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700428
429 // We expect to generate candidates that are equivalent to what we have now.
430 // Force DoAllocate to generate them instead of skipping.
431 bool disable_equivalent_phases = false;
432 Regather(networks, disable_equivalent_phases,
433 IceRegatheringReason::OCCASIONAL_REFRESH);
434}
435
436void BasicPortAllocatorSession::Regather(
437 const std::vector<rtc::Network*>& networks,
438 bool disable_equivalent_phases,
439 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700440 // Remove ports from being used locally and send signaling to remove
441 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700442 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700443 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100444 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000445 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700446 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700447
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700448 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700449 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700450
Steve Anton300bf8e2017-07-14 10:13:10 -0700451 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700452 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453}
454
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800455void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200456 const absl::optional<int>& stun_keepalive_interval) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800457 auto ports = ReadyPorts();
458 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800459 // The port type and protocol can be used to identify different subclasses
460 // of Port in the current implementation. Note that a TCPPort has the type
461 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
462 if (port->Type() == STUN_PORT_TYPE ||
463 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800464 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
465 stun_keepalive_interval);
466 }
467 }
468}
469
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700470std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
471 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700472 for (const PortData& data : ports_) {
473 if (data.ready()) {
474 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700475 }
476 }
477 return ret;
478}
479
480std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
481 std::vector<Candidate> candidates;
482 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700483 if (!data.ready()) {
484 continue;
485 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700486 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700487 }
488 return candidates;
489}
490
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700491void BasicPortAllocatorSession::GetCandidatesFromPort(
492 const PortData& data,
493 std::vector<Candidate>* candidates) const {
494 RTC_CHECK(candidates != nullptr);
495 for (const Candidate& candidate : data.port()->Candidates()) {
496 if (!CheckCandidateFilter(candidate)) {
497 continue;
498 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700499 candidates->push_back(SanitizeRelatedAddress(candidate));
500 }
501}
502
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700503Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
504 const Candidate& c) const {
505 Candidate copy = c;
506 // If adapter enumeration is disabled or host candidates are disabled,
507 // clear the raddr of STUN candidates to avoid local address leakage.
508 bool filter_stun_related_address =
509 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
510 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
511 !(candidate_filter_ & CF_HOST);
512 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
513 // to avoid reflexive address leakage.
514 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
515 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
516 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
517 copy.set_related_address(
518 rtc::EmptySocketAddressWithFamily(copy.address().family()));
519 }
520 return copy;
521}
522
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700523bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
524 // Done only if all required AllocationSequence objects
525 // are created.
526 if (!allocation_sequences_created_) {
527 return false;
528 }
529
530 // Check that all port allocation sequences are complete (not running).
531 if (std::any_of(sequences_.begin(), sequences_.end(),
532 [](const AllocationSequence* sequence) {
533 return sequence->state() == AllocationSequence::kRunning;
534 })) {
535 return false;
536 }
537
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700538 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700539 // expected candidates. Session will trigger candidates allocation complete
540 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700541 return std::none_of(ports_.begin(), ports_.end(),
542 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700543}
544
Yves Gerey665174f2018-06-19 15:03:05 +0200545void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000546 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200547 case MSG_CONFIG_START:
548 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
549 GetPortConfigurations();
550 break;
551 case MSG_CONFIG_READY:
552 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
553 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
554 break;
555 case MSG_ALLOCATE:
556 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
557 OnAllocate();
558 break;
559 case MSG_SEQUENCEOBJECTS_CREATED:
560 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
561 OnAllocationSequenceObjectsCreated();
562 break;
563 case MSG_CONFIG_STOP:
564 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
565 OnConfigStop();
566 break;
567 default:
568 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 }
570}
571
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700572void BasicPortAllocatorSession::UpdateIceParametersInternal() {
573 for (PortData& port : ports_) {
574 port.port()->set_content_name(content_name());
575 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
576 }
577}
578
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000579void BasicPortAllocatorSession::GetPortConfigurations() {
Yves Gerey665174f2018-06-19 15:03:05 +0200580 PortConfiguration* config =
581 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582
deadbeef653b8e02015-11-11 12:55:10 -0800583 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
584 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000585 }
586 ConfigReady(config);
587}
588
589void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700590 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000591}
592
593// Adds a configuration to the list.
594void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800595 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000596 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800597 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598
599 AllocatePorts();
600}
601
602void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800603 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604
605 // If any of the allocated ports have not completed the candidates allocation,
606 // mark those as error. Since session doesn't need any new candidates
607 // at this stage of the allocation, it's safe to discard any new candidates.
608 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200609 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
610 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700611 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612 // Updating port state to error, which didn't finish allocating candidates
613 // yet.
614 it->set_error();
615 send_signal = true;
616 }
617 }
618
619 // Did we stop any running sequences?
620 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
621 it != sequences_.end() && !send_signal; ++it) {
622 if ((*it)->state() == AllocationSequence::kStopped) {
623 send_signal = true;
624 }
625 }
626
627 // If we stopped anything that was running, send a done signal now.
628 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000629 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000630 }
631}
632
633void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800634 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700635 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636}
637
638void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 if (network_manager_started_ && !IsStopped()) {
640 bool disable_equivalent_phases = true;
641 DoAllocate(disable_equivalent_phases);
642 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000643
644 allocation_started_ = true;
645}
646
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700647std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
648 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700649 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800650 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700651 // If the network permission state is BLOCKED, we just act as if the flag has
652 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700653 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700654 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700655 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
656 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000657 // If the adapter enumeration is disabled, we'll just bind to any address
658 // instead of specific NIC. This is to ensure the same routing for http
659 // traffic by OS is also used here to avoid any local or public IP leakage
660 // during stun process.
661 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
662 network_manager->GetAnyAddressNetworks(&networks);
663 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700664 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000665 // If network enumeration fails, use the ANY address as a fallback, so we
666 // can at least try gathering candidates using the default route chosen by
667 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
668 // set, we'll use ANY address candidates either way.
669 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
670 network_manager->GetAnyAddressNetworks(&networks);
671 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000672 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100673 // Filter out link-local networks if needed.
674 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700675 NetworkFilter link_local_filter(
676 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
677 "link-local");
678 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100679 }
deadbeef3427f532017-07-26 16:09:33 -0700680 // Do some more filtering, depending on the network ignore mask and "disable
681 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700682 NetworkFilter ignored_filter(
683 [this](rtc::Network* network) {
684 return allocator_->network_ignore_mask() & network->type();
685 },
686 "ignored");
687 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700688 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
689 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700690 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000691 // Don't determine the lowest cost from a link-local network.
692 // On iOS, a device connected to the computer will get a link-local
693 // network for communicating with the computer, however this network can't
694 // be used to connect to a peer outside the network.
695 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800696 continue;
697 }
honghaiz60347052016-05-31 18:29:12 -0700698 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
699 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700700 NetworkFilter costly_filter(
701 [lowest_cost](rtc::Network* network) {
702 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
703 },
704 "costly");
705 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700706 }
deadbeef3427f532017-07-26 16:09:33 -0700707 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
708 // default, it's 5), remove networks to ensure that limit is satisfied.
709 //
710 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
711 // networks, we could try to choose a set that's "most likely to work". It's
712 // hard to define what that means though; it's not just "lowest cost".
713 // Alternatively, we could just focus on making our ICE pinging logic smarter
714 // such that this filtering isn't necessary in the first place.
715 int ipv6_networks = 0;
716 for (auto it = networks.begin(); it != networks.end();) {
717 if ((*it)->prefix().family() == AF_INET6) {
718 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
719 it = networks.erase(it);
720 continue;
721 } else {
722 ++ipv6_networks;
723 }
724 }
725 ++it;
726 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700727 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700728}
729
730// For each network, see if we have a sequence that covers it already. If not,
731// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700732void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700733 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700734 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000735 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100736 RTC_LOG(LS_WARNING)
737 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 done_signal_needed = true;
739 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700741 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200742 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200743 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000744 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
745 // If all the ports are disabled we should just fire the allocation
746 // done event and return.
747 done_signal_needed = true;
748 break;
749 }
750
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000751 if (!config || config->relays.empty()) {
752 // No relay ports specified in this config.
753 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
754 }
755
756 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758 // Skip IPv6 networks unless the flag's been set.
759 continue;
760 }
761
zhihuangb09b3f92017-03-07 14:40:51 -0800762 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
763 networks[i]->GetBestIP().family() == AF_INET6 &&
764 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
765 // Skip IPv6 Wi-Fi networks unless the flag's been set.
766 continue;
767 }
768
Steve Anton300bf8e2017-07-14 10:13:10 -0700769 if (disable_equivalent) {
770 // Disable phases that would only create ports equivalent to
771 // ones that we have already made.
772 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000773
Steve Anton300bf8e2017-07-14 10:13:10 -0700774 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
775 // New AllocationSequence would have nothing to do, so don't make it.
776 continue;
777 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000778 }
779
780 AllocationSequence* sequence =
781 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782 sequence->SignalPortAllocationComplete.connect(
783 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700784 sequence->Init();
785 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700787 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000788 }
789 }
790 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700791 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000792 }
793}
794
795void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700796 std::vector<rtc::Network*> networks = GetNetworks();
797 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700798 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700799 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700800 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700801 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700802 std::find(networks.begin(), networks.end(), sequence->network()) ==
803 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700804 sequence->OnNetworkFailed();
805 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700806 }
807 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700808 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
809 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100810 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
811 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000812 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700813 }
honghaiz8c404fa2015-09-28 07:59:43 -0700814
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700815 if (allocation_started_ && !IsStopped()) {
816 if (network_manager_started_) {
817 // If the network manager has started, it must be regathering.
818 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
819 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700820 bool disable_equivalent_phases = true;
821 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700822 }
823
Honghai Zhang5048f572016-08-23 15:47:33 -0700824 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100825 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700826 network_manager_started_ = true;
827 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828}
829
830void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200831 rtc::Network* network,
832 PortConfiguration* config,
833 uint32_t* flags) {
834 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200835 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200836 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837 sequences_[i]->DisableEquivalentPhases(network, config, flags);
838 }
839}
840
841void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200842 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000843 bool prepare_address) {
844 if (!port)
845 return;
846
Mirko Bonadei675513b2017-11-09 11:09:25 +0100847 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700849 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700851 if (allocator_->proxy().type != rtc::PROXY_NONE)
852 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 port->set_send_retransmit_count_attribute(
854 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000855
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000856 PortData data(port, seq);
857 ports_.push_back(data);
858
859 port->SignalCandidateReady.connect(
860 this, &BasicPortAllocatorSession::OnCandidateReady);
861 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200862 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200864 &BasicPortAllocatorSession::OnPortDestroyed);
865 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
866 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000867
868 if (prepare_address)
869 port->PrepareAddress();
870}
871
872void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
873 allocation_sequences_created_ = true;
874 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000875 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876}
877
Yves Gerey665174f2018-06-19 15:03:05 +0200878void BasicPortAllocatorSession::OnCandidateReady(Port* port,
879 const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800880 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000882 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200883 RTC_LOG(LS_INFO) << port->ToString()
884 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700886 // already done with gathering.
887 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100888 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700889 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700890 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700891 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700892
danilchapf4e8cf02016-06-30 01:55:03 -0700893 // Mark that the port has a pairable candidate, either because we have a
894 // usable candidate from the port, or simply because the port is bound to the
895 // any address and therefore has no host candidate. This will trigger the port
896 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700897 // checks. If port has already been marked as having a pairable candidate,
898 // do nothing here.
899 // Note: We should check whether any candidates may become ready after this
900 // because there we will check whether the candidate is generated by the ready
901 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700902 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700903 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700904 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700905
906 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700907 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700908 }
909 // If the current port is not pruned yet, SignalPortReady.
910 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000911 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
912 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700913 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700914 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700915 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700916
deadbeef1c5e6d02017-09-15 17:46:56 -0700917 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000918 std::vector<Candidate> candidates;
919 candidates.push_back(SanitizeRelatedAddress(c));
920 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700921 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100922 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700923 }
924
925 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700926 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000927 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700928 }
929}
930
931Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
932 const std::string& network_name) const {
933 Port* best_turn_port = nullptr;
934 for (const PortData& data : ports_) {
935 if (data.port()->Network()->name() == network_name &&
936 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
937 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
938 best_turn_port = data.port();
939 }
940 }
941 return best_turn_port;
942}
943
944bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700945 // Note: We determine the same network based only on their network names. So
946 // if an IPv4 address and an IPv6 address have the same network name, they
947 // are considered the same network here.
948 const std::string& network_name = newly_pairable_turn_port->Network()->name();
949 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
950 // |port| is already in the list of ports, so the best port cannot be nullptr.
951 RTC_CHECK(best_turn_port != nullptr);
952
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700953 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700954 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700955 for (PortData& data : ports_) {
956 if (data.port()->Network()->name() == network_name &&
957 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
958 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700959 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700960 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000961 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700962 ports_to_prune.push_back(&data);
963 } else {
964 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700965 }
966 }
967 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700968
969 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100970 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
971 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000972 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700973 }
974 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975}
976
Honghai Zhanga74363c2016-07-28 18:06:15 -0700977void BasicPortAllocatorSession::PruneAllPorts() {
978 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700979 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700980 }
981}
982
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000983void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800984 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200985 RTC_LOG(LS_INFO) << port->ToString()
986 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000987 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000988 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000989
990 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700991 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000992 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700993 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000994
995 // Moving to COMPLETE state.
996 data->set_complete();
997 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000998 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000999}
1000
1001void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -08001002 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001003 RTC_LOG(LS_INFO) << port->ToString()
1004 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001005 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001006 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001007 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001008 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001010 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001011
1012 // SignalAddressError is currently sent from StunPort/TurnPort.
1013 // But this signal itself is generic.
1014 data->set_error();
1015 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001016 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001017}
1018
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001019bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001020 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001021
1022 // When binding to any address, before sending packets out, the getsockname
1023 // returns all 0s, but after sending packets, it'll be the NIC used to
1024 // send. All 0s is not a valid ICE candidate address and should be filtered
1025 // out.
1026 if (c.address().IsAnyIP()) {
1027 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001028 }
1029
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001030 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001031 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001032 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001033 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001034 } else if (c.type() == LOCAL_PORT_TYPE) {
1035 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1036 // We allow host candidates if the filter allows server-reflexive
1037 // candidates and the candidate is a public IP. Because we don't generate
1038 // server-reflexive candidates if they have the same IP as the host
1039 // candidate (i.e. when the host candidate is a public IP), filtering to
1040 // only server-reflexive candidates won't work right when the host
1041 // candidates have public IPs.
1042 return true;
1043 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001044
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +00001045 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +00001046 }
1047 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048}
1049
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001050bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1051 const Port* port) const {
1052 bool candidate_signalable = CheckCandidateFilter(c);
1053
1054 // When device enumeration is disabled (to prevent non-default IP addresses
1055 // from leaking), we ping from some local candidates even though we don't
1056 // signal them. However, if host candidates are also disabled (for example, to
1057 // prevent even default IP addresses from leaking), we still don't want to
1058 // ping from them, even if device enumeration is disabled. Thus, we check for
1059 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001060 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001061 bool can_ping_from_candidate =
1062 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1063 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1064
1065 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001066 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001067 !host_candidates_disabled);
1068}
1069
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001070void BasicPortAllocatorSession::OnPortAllocationComplete(
1071 AllocationSequence* seq) {
1072 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001073 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001074}
1075
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001076void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001077 if (CandidatesAllocationDone()) {
1078 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001079 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001080 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001081 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1082 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001083 }
1084 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001085 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086}
1087
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001088void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001089 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001090 for (std::vector<PortData>::iterator iter = ports_.begin();
1091 iter != ports_.end(); ++iter) {
1092 if (port == iter->port()) {
1093 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001094 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001095 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001096 return;
1097 }
1098 }
nissec80e7412017-01-11 05:56:46 -08001099 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100}
1101
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001102BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1103 Port* port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001104 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1105 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106 if (it->port() == port) {
1107 return &*it;
1108 }
1109 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001110 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111}
1112
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001113std::vector<BasicPortAllocatorSession::PortData*>
1114BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001115 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001116 std::vector<PortData*> unpruned_ports;
1117 for (PortData& port : ports_) {
1118 if (!port.pruned() &&
1119 std::find(networks.begin(), networks.end(),
1120 port.sequence()->network()) != networks.end()) {
1121 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001122 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001123 }
1124 return unpruned_ports;
1125}
1126
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001127void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001128 const std::vector<PortData*>& port_data_list) {
1129 std::vector<PortInterface*> pruned_ports;
1130 std::vector<Candidate> removed_candidates;
1131 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001132 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001133 data->Prune();
1134 pruned_ports.push_back(data->port());
1135 if (data->has_pairable_candidate()) {
1136 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001137 // Mark the port as having no pairable candidates so that its candidates
1138 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001139 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001140 }
1141 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001142 if (!pruned_ports.empty()) {
1143 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001144 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001145 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001146 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1147 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001148 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001149 }
1150}
1151
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001152// AllocationSequence
1153
1154AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1155 rtc::Network* network,
1156 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001157 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001158 : session_(session),
1159 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001160 config_(config),
1161 state_(kInit),
1162 flags_(flags),
1163 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001164 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001165 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001166
Honghai Zhang5048f572016-08-23 15:47:33 -07001167void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1169 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001170 rtc::SocketAddress(network_->GetBestIP(), 0),
1171 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001172 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001173 udp_socket_->SignalReadPacket.connect(this,
1174 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001175 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001176 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1177 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001179}
1180
1181void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001182 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001183 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001184}
1185
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001186void AllocationSequence::OnNetworkFailed() {
1187 RTC_DCHECK(!network_failed_);
1188 network_failed_ = true;
1189 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001190 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001191}
1192
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001193AllocationSequence::~AllocationSequence() {
1194 session_->network_thread()->Clear(this);
1195}
1196
1197void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001198 PortConfiguration* config,
1199 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001200 if (network_failed_) {
1201 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001202 // it won't be equivalent to the new network.
1203 return;
1204 }
1205
deadbeef5c3c1042017-08-04 15:01:57 -07001206 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001207 // Different network setup; nothing is equivalent.
1208 return;
1209 }
1210
1211 // Else turn off the stuff that we've already got covered.
1212
deadbeef1c46a352017-09-27 11:24:05 -07001213 // Every config implicitly specifies local, so turn that off right away if we
1214 // already have a port of the corresponding type. Look for a port that
1215 // matches this AllocationSequence's network, is the right protocol, and
1216 // hasn't encountered an error.
1217 // TODO(deadbeef): This doesn't take into account that there may be another
1218 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1219 // This can happen if, say, there's a network change event right before an
1220 // application-triggered ICE restart. Hopefully this problem will just go
1221 // away if we get rid of the gathering "phases" though, which is planned.
1222 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1223 [this](const BasicPortAllocatorSession::PortData& p) {
1224 return p.port()->Network() == network_ &&
1225 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1226 })) {
1227 *flags |= PORTALLOCATOR_DISABLE_UDP;
1228 }
1229 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1230 [this](const BasicPortAllocatorSession::PortData& p) {
1231 return p.port()->Network() == network_ &&
1232 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1233 })) {
1234 *flags |= PORTALLOCATOR_DISABLE_TCP;
1235 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001236
1237 if (config_ && config) {
1238 if (config_->StunServers() == config->StunServers()) {
1239 // Already got this STUN servers covered.
1240 *flags |= PORTALLOCATOR_DISABLE_STUN;
1241 }
1242 if (!config_->relays.empty()) {
1243 // Already got relays covered.
1244 // NOTE: This will even skip a _different_ set of relay servers if we
1245 // were to be given one, but that never happens in our codebase. Should
1246 // probably get rid of the list in PortConfiguration and just keep a
1247 // single relay server in each one.
1248 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1249 }
1250 }
1251}
1252
1253void AllocationSequence::Start() {
1254 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001255 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001256 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1257 // called next time, we enable all phases if the best IP has since changed.
1258 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259}
1260
1261void AllocationSequence::Stop() {
1262 // If the port is completed, don't set it to stopped.
1263 if (state_ == kRunning) {
1264 state_ = kStopped;
1265 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1266 }
1267}
1268
1269void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001270 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1271 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001272
deadbeef1c5e6d02017-09-15 17:46:56 -07001273 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001274
1275 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001276 RTC_LOG(LS_INFO) << network_->ToString()
1277 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001278
1279 switch (phase_) {
1280 case PHASE_UDP:
1281 CreateUDPPorts();
1282 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001283 break;
1284
1285 case PHASE_RELAY:
1286 CreateRelayPorts();
1287 break;
1288
1289 case PHASE_TCP:
1290 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001291 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001292 break;
1293
1294 default:
nissec80e7412017-01-11 05:56:46 -08001295 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001296 }
1297
1298 if (state() == kRunning) {
1299 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001300 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1301 session_->allocator()->step_delay(),
1302 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001303 } else {
1304 // If all phases in AllocationSequence are completed, no allocation
1305 // steps needed further. Canceling pending signal.
1306 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1307 SignalPortAllocationComplete(this);
1308 }
1309}
1310
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001311void AllocationSequence::CreateUDPPorts() {
1312 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001313 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314 return;
1315 }
1316
1317 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1318 // is enabled completely.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001319 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001320 bool emit_local_candidate_for_anyaddress =
1321 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001323 port = UDPPort::Create(
1324 session_->network_thread(), session_->socket_factory(), network_,
1325 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001326 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1327 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001328 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001329 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001330 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001331 session_->allocator()->min_port(), session_->allocator()->max_port(),
1332 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001333 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1334 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001335 }
1336
1337 if (port) {
1338 // If shared socket is enabled, STUN candidate will be allocated by the
1339 // UDPPort.
1340 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1341 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001342 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001343
1344 // If STUN is not disabled, setting stun server address to port.
1345 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001346 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001347 RTC_LOG(LS_INFO)
1348 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001349 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001351 }
1352 }
1353 }
1354
1355 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001356 }
1357}
1358
1359void AllocationSequence::CreateTCPPorts() {
1360 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001361 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001362 return;
1363 }
1364
deadbeef5c3c1042017-08-04 15:01:57 -07001365 Port* port = TCPPort::Create(
1366 session_->network_thread(), session_->socket_factory(), network_,
1367 session_->allocator()->min_port(), session_->allocator()->max_port(),
1368 session_->username(), session_->password(),
1369 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370 if (port) {
1371 session_->AddAllocatedPort(port, this, true);
1372 // Since TCPPort is not created using shared socket, |port| will not be
1373 // added to the dequeue.
1374 }
1375}
1376
1377void AllocationSequence::CreateStunPorts() {
1378 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001379 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001380 return;
1381 }
1382
1383 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1384 return;
1385 }
1386
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001387 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001388 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001389 << "AllocationSequence: No STUN server configured, skipping.";
1390 return;
1391 }
1392
deadbeef5c3c1042017-08-04 15:01:57 -07001393 StunPort* port = StunPort::Create(
1394 session_->network_thread(), session_->socket_factory(), network_,
1395 session_->allocator()->min_port(), session_->allocator()->max_port(),
1396 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001397 session_->allocator()->origin(),
1398 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001399 if (port) {
1400 session_->AddAllocatedPort(port, this, true);
1401 // Since StunPort is not created using shared socket, |port| will not be
1402 // added to the dequeue.
1403 }
1404}
1405
1406void AllocationSequence::CreateRelayPorts() {
1407 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001408 RTC_LOG(LS_VERBOSE)
1409 << "AllocationSequence: Relay ports disabled, skipping.";
1410 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001411 }
1412
1413 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1414 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001415 RTC_DCHECK(config_);
1416 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001418 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001419 << "AllocationSequence: No relay server configured, skipping.";
1420 return;
1421 }
1422
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001423 for (RelayServerConfig& relay : config_->relays) {
1424 if (relay.type == RELAY_GTURN) {
1425 CreateGturnPort(relay);
1426 } else if (relay.type == RELAY_TURN) {
1427 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001428 } else {
nissec80e7412017-01-11 05:56:46 -08001429 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001430 }
1431 }
1432}
1433
1434void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1435 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001436 RelayPort* port = RelayPort::Create(
1437 session_->network_thread(), session_->socket_factory(), network_,
1438 session_->allocator()->min_port(), session_->allocator()->max_port(),
1439 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001440 if (port) {
1441 // Since RelayPort is not created using shared socket, |port| will not be
1442 // added to the dequeue.
1443 // Note: We must add the allocated port before we add addresses because
1444 // the latter will create candidates that need name and preference
1445 // settings. However, we also can't prepare the address (normally
1446 // done by AddAllocatedPort) until we have these addresses. So we
1447 // wait to do that until below.
1448 session_->AddAllocatedPort(port, this, false);
1449
1450 // Add the addresses of this protocol.
1451 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001452 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001453 ++relay_port) {
1454 port->AddServerAddress(*relay_port);
1455 port->AddExternalAddress(*relay_port);
1456 }
1457 // Start fetching an address for this port.
1458 port->PrepareAddress();
1459 }
1460}
1461
1462void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1463 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001464 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1465 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001466 // Skip UDP connections to relay servers if it's disallowed.
1467 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1468 relay_port->proto == PROTO_UDP) {
1469 continue;
1470 }
1471
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001472 // Do not create a port if the server address family is known and does
1473 // not match the local IP address family.
1474 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001475 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001476 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001477 RTC_LOG(LS_INFO)
1478 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001479 "Server address: "
1480 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001481 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001482 continue;
1483 }
1484
Jonas Oreland202994c2017-12-18 12:10:43 +01001485 CreateRelayPortArgs args;
1486 args.network_thread = session_->network_thread();
1487 args.socket_factory = session_->socket_factory();
1488 args.network = network_;
1489 args.username = session_->username();
1490 args.password = session_->password();
1491 args.server_address = &(*relay_port);
1492 args.config = &config;
1493 args.origin = session_->allocator()->origin();
1494 args.turn_customizer = session_->allocator()->turn_customizer();
1495
1496 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001497 // Shared socket mode must be enabled only for UDP based ports. Hence
1498 // don't pass shared socket for ports which will create TCP sockets.
1499 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1500 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1501 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001502 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001503 port = session_->allocator()->relay_port_factory()->Create(
1504 args, udp_socket_.get());
1505
1506 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001507 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1508 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001509 continue;
1510 }
1511
1512 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001513 // Listen to the port destroyed signal, to allow AllocationSequence to
1514 // remove entrt from it's map.
1515 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1516 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001517 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001518 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001519 session_->allocator()->max_port());
1520
1521 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001522 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1523 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001524 continue;
1525 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001526 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001527 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001528 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001529 }
1530}
1531
Yves Gerey665174f2018-06-19 15:03:05 +02001532void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1533 const char* data,
1534 size_t size,
1535 const rtc::SocketAddress& remote_addr,
1536 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001537 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001538
1539 bool turn_port_found = false;
1540
1541 // Try to find the TurnPort that matches the remote address. Note that the
1542 // message could be a STUN binding response if the TURN server is also used as
1543 // a STUN server. We don't want to parse every message here to check if it is
1544 // a STUN binding response, so we pass the message to TurnPort regardless of
1545 // the message type. The TurnPort will just ignore the message since it will
1546 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001547 for (auto* port : relay_ports_) {
1548 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001549 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1550 packet_time)) {
1551 return;
1552 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001553 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001554 }
1555 }
1556
1557 if (udp_port_) {
1558 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1559
1560 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1561 // the TURN server is also a STUN server.
1562 if (!turn_port_found ||
1563 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001564 RTC_DCHECK(udp_port_->SharedSocket());
1565 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1566 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001567 }
1568 }
1569}
1570
1571void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1572 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001573 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001574 return;
1575 }
1576
Jonas Oreland202994c2017-12-18 12:10:43 +01001577 auto it = std::find(relay_ports_.begin(), relay_ports_.end(), port);
1578 if (it != relay_ports_.end()) {
1579 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001580 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001582 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001583 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001584}
1585
1586// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001587PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1588 const std::string& username,
1589 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001590 : stun_address(stun_address), username(username), password(password) {
1591 if (!stun_address.IsNil())
1592 stun_servers.insert(stun_address);
1593}
1594
1595PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1596 const std::string& username,
1597 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001598 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001599 if (!stun_servers.empty())
1600 stun_address = *(stun_servers.begin());
1601}
1602
Steve Anton7995d8c2017-10-30 16:23:38 -07001603PortConfiguration::~PortConfiguration() = default;
1604
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001605ServerAddresses PortConfiguration::StunServers() {
1606 if (!stun_address.IsNil() &&
1607 stun_servers.find(stun_address) == stun_servers.end()) {
1608 stun_servers.insert(stun_address);
1609 }
deadbeefc5d0d952015-07-16 10:22:21 -07001610 // Every UDP TURN server should also be used as a STUN server.
1611 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1612 for (const rtc::SocketAddress& turn_server : turn_servers) {
1613 if (stun_servers.find(turn_server) == stun_servers.end()) {
1614 stun_servers.insert(turn_server);
1615 }
1616 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001617 return stun_servers;
1618}
1619
1620void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1621 relays.push_back(config);
1622}
1623
Yves Gerey665174f2018-06-19 15:03:05 +02001624bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1625 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001626 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001627 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1628 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001629 if (relay_port->proto == type)
1630 return true;
1631 }
1632 return false;
1633}
1634
1635bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1636 ProtocolType type) const {
1637 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001638 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001639 return true;
1640 }
1641 return false;
1642}
1643
1644ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001645 RelayType turn_type,
1646 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001647 ServerAddresses servers;
1648 for (size_t i = 0; i < relays.size(); ++i) {
1649 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1650 servers.insert(relays[i].ports.front().address);
1651 }
1652 }
1653 return servers;
1654}
1655
1656} // namespace cricket