blob: b3b9e7347ae297c08548b801e3ba603c66131dea [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>
Steve Anton6c38cc72017-11-29 10:25:58 -080014#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000015#include <string>
16#include <vector>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/umametrics.h"
19#include "p2p/base/basicpacketsocketfactory.h"
20#include "p2p/base/common.h"
21#include "p2p/base/port.h"
22#include "p2p/base/relayport.h"
23#include "p2p/base/stunport.h"
24#include "p2p/base/tcpport.h"
25#include "p2p/base/turnport.h"
26#include "p2p/base/udpport.h"
27#include "rtc_base/checks.h"
28#include "rtc_base/helpers.h"
29#include "rtc_base/logging.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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092} // namespace
93
94namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020095const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070096 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
97 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098
99// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200100BasicPortAllocator::BasicPortAllocator(
101 rtc::NetworkManager* network_manager,
102 rtc::PacketSocketFactory* socket_factory,
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +0000103 webrtc::TurnCustomizer* customizer)
maxmorine9ef9072017-08-29 04:49:00 -0700104 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800105 RTC_DCHECK(network_manager_ != nullptr);
106 RTC_DCHECK(socket_factory_ != nullptr);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200107 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(),
108 0, false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000109 Construct();
110}
111
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +0000112BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700113 : network_manager_(network_manager), socket_factory_(nullptr) {
nisseede5da42017-01-12 05:15:36 -0800114 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115 Construct();
116}
117
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +0000118BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
119 rtc::PacketSocketFactory* socket_factory,
120 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700121 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800122 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200123 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
124 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000125 Construct();
126}
127
128BasicPortAllocator::BasicPortAllocator(
129 rtc::NetworkManager* network_manager,
130 const ServerAddresses& stun_servers,
131 const rtc::SocketAddress& relay_address_udp,
132 const rtc::SocketAddress& relay_address_tcp,
133 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700134 : network_manager_(network_manager), socket_factory_(NULL) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700135 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000136 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800137 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800139 }
140 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800142 }
143 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000144 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800145 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146
deadbeef653b8e02015-11-11 12:55:10 -0800147 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700148 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800149 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150
Jonas Orelandbdcee282017-10-10 14:01:40 +0200151 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 Construct();
153}
154
155void BasicPortAllocator::Construct() {
156 allow_tcp_listen_ = true;
157}
158
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700159void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
160 IceRegatheringReason reason) {
161 if (!metrics_observer()) {
162 return;
163 }
164 // If the session has not been taken by an active channel, do not report the
165 // metric.
166 for (auto& allocator_session : pooled_sessions()) {
167 if (allocator_session.get() == session) {
168 return;
169 }
170 }
171
172 metrics_observer()->IncrementEnumCounter(
173 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
174 static_cast<int>(IceRegatheringReason::MAX_VALUE));
175}
176
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000177BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800178 // Our created port allocator sessions depend on us, so destroy our remaining
179 // pooled sessions before anything else.
180 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181}
182
Steve Anton7995d8c2017-10-30 16:23:38 -0700183void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
184 // TODO(phoglund): implement support for other types than loopback.
185 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
186 // Then remove set_network_ignore_list from NetworkManager.
187 network_ignore_mask_ = network_ignore_mask;
188}
189
deadbeefc5d0d952015-07-16 10:22:21 -0700190PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191 const std::string& content_name, int component,
192 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700193 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700195 session->SignalIceRegathering.connect(this,
196 &BasicPortAllocator::OnIceRegathering);
197 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198}
199
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700200void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
201 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
202 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700203 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200204 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700205}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206
207// BasicPortAllocatorSession
208BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700209 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210 const std::string& content_name,
211 int component,
212 const std::string& ice_ufrag,
213 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700214 : PortAllocatorSession(content_name,
215 component,
216 ice_ufrag,
217 ice_pwd,
218 allocator->flags()),
219 allocator_(allocator),
220 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 socket_factory_(allocator->socket_factory()),
222 allocation_started_(false),
223 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700224 allocation_sequences_created_(false),
225 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226 allocator_->network_manager()->SignalNetworksChanged.connect(
227 this, &BasicPortAllocatorSession::OnNetworksChanged);
228 allocator_->network_manager()->StartUpdating();
229}
230
231BasicPortAllocatorSession::~BasicPortAllocatorSession() {
232 allocator_->network_manager()->StopUpdating();
233 if (network_thread_ != NULL)
234 network_thread_->Clear(this);
235
Peter Boström0c4e06b2015-10-07 12:23:21 +0200236 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237 // AllocationSequence should clear it's map entry for turn ports before
238 // ports are destroyed.
239 sequences_[i]->Clear();
240 }
241
242 std::vector<PortData>::iterator it;
243 for (it = ports_.begin(); it != ports_.end(); it++)
244 delete it->port();
245
Peter Boström0c4e06b2015-10-07 12:23:21 +0200246 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247 delete configs_[i];
248
Peter Boström0c4e06b2015-10-07 12:23:21 +0200249 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 delete sequences_[i];
251}
252
Steve Anton7995d8c2017-10-30 16:23:38 -0700253BasicPortAllocator* BasicPortAllocatorSession::allocator() {
254 return allocator_;
255}
256
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700257void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
258 if (filter == candidate_filter_) {
259 return;
260 }
261 // We assume the filter will only change from "ALL" to something else.
262 RTC_DCHECK(candidate_filter_ == CF_ALL);
263 candidate_filter_ = filter;
264 for (PortData& port : ports_) {
265 if (!port.has_pairable_candidate()) {
266 continue;
267 }
268 const auto& candidates = port.port()->Candidates();
269 // Setting a filter may cause a ready port to become non-ready
270 // if it no longer has any pairable candidates.
271 if (!std::any_of(candidates.begin(), candidates.end(),
272 [this, &port](const Candidate& candidate) {
273 return CandidatePairable(candidate, port.port());
274 })) {
275 port.set_has_pairable_candidate(false);
276 }
277 }
278}
279
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000280void BasicPortAllocatorSession::StartGettingPorts() {
281 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700282 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283 if (!socket_factory_) {
284 owned_socket_factory_.reset(
285 new rtc::BasicPacketSocketFactory(network_thread_));
286 socket_factory_ = owned_socket_factory_.get();
287 }
288
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700289 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700290
Mirko Bonadei675513b2017-11-09 11:09:25 +0100291 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
292 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293}
294
295void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800296 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700297 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700298 // Note: this must be called after ClearGettingPorts because both may set the
299 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700300 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700301}
302
303void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800304 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000305 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700306 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700308 }
deadbeefb60a8192016-08-24 15:15:00 -0700309 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700310 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700311}
312
Steve Anton7995d8c2017-10-30 16:23:38 -0700313bool BasicPortAllocatorSession::IsGettingPorts() {
314 return state_ == SessionState::GATHERING;
315}
316
317bool BasicPortAllocatorSession::IsCleared() const {
318 return state_ == SessionState::CLEARED;
319}
320
321bool BasicPortAllocatorSession::IsStopped() const {
322 return state_ == SessionState::STOPPED;
323}
324
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700325std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
326 std::vector<rtc::Network*> networks = GetNetworks();
327
328 // A network interface may have both IPv4 and IPv6 networks. Only if
329 // neither of the networks has any connections, the network interface
330 // is considered failed and need to be regathered on.
331 std::set<std::string> networks_with_connection;
332 for (const PortData& data : ports_) {
333 Port* port = data.port();
334 if (!port->connections().empty()) {
335 networks_with_connection.insert(port->Network()->name());
336 }
337 }
338
339 networks.erase(
340 std::remove_if(networks.begin(), networks.end(),
341 [networks_with_connection](rtc::Network* network) {
342 // If a network does not have any connection, it is
343 // considered failed.
344 return networks_with_connection.find(network->name()) !=
345 networks_with_connection.end();
346 }),
347 networks.end());
348 return networks;
349}
350
351void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
352 // Find the list of networks that have no connection.
353 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
354 if (failed_networks.empty()) {
355 return;
356 }
357
Mirko Bonadei675513b2017-11-09 11:09:25 +0100358 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700359
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700360 // Mark a sequence as "network failed" if its network is in the list of failed
361 // networks, so that it won't be considered as equivalent when the session
362 // regathers ports and candidates.
363 for (AllocationSequence* sequence : sequences_) {
364 if (!sequence->network_failed() &&
365 std::find(failed_networks.begin(), failed_networks.end(),
366 sequence->network()) != failed_networks.end()) {
367 sequence->set_network_failed();
368 }
369 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700370
371 bool disable_equivalent_phases = true;
372 Regather(failed_networks, disable_equivalent_phases,
373 IceRegatheringReason::NETWORK_FAILURE);
374}
375
376void BasicPortAllocatorSession::RegatherOnAllNetworks() {
377 std::vector<rtc::Network*> networks = GetNetworks();
378 if (networks.empty()) {
379 return;
380 }
381
Mirko Bonadei675513b2017-11-09 11:09:25 +0100382 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700383
384 // We expect to generate candidates that are equivalent to what we have now.
385 // Force DoAllocate to generate them instead of skipping.
386 bool disable_equivalent_phases = false;
387 Regather(networks, disable_equivalent_phases,
388 IceRegatheringReason::OCCASIONAL_REFRESH);
389}
390
391void BasicPortAllocatorSession::Regather(
392 const std::vector<rtc::Network*>& networks,
393 bool disable_equivalent_phases,
394 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700395 // Remove ports from being used locally and send signaling to remove
396 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700397 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700398 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100399 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700400 PrunePortsAndRemoveCandidates(ports_to_prune);
401 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700402
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700403 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700404 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700405
Steve Anton300bf8e2017-07-14 10:13:10 -0700406 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700407 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408}
409
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700410std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
411 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700412 for (const PortData& data : ports_) {
413 if (data.ready()) {
414 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700415 }
416 }
417 return ret;
418}
419
420std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
421 std::vector<Candidate> candidates;
422 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700423 if (!data.ready()) {
424 continue;
425 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700426 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700427 }
428 return candidates;
429}
430
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700431void BasicPortAllocatorSession::GetCandidatesFromPort(
432 const PortData& data,
433 std::vector<Candidate>* candidates) const {
434 RTC_CHECK(candidates != nullptr);
435 for (const Candidate& candidate : data.port()->Candidates()) {
436 if (!CheckCandidateFilter(candidate)) {
437 continue;
438 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700439 candidates->push_back(SanitizeRelatedAddress(candidate));
440 }
441}
442
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700443Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
444 const Candidate& c) const {
445 Candidate copy = c;
446 // If adapter enumeration is disabled or host candidates are disabled,
447 // clear the raddr of STUN candidates to avoid local address leakage.
448 bool filter_stun_related_address =
449 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
450 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
451 !(candidate_filter_ & CF_HOST);
452 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
453 // to avoid reflexive address leakage.
454 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
455 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
456 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
457 copy.set_related_address(
458 rtc::EmptySocketAddressWithFamily(copy.address().family()));
459 }
460 return copy;
461}
462
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700463bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
464 // Done only if all required AllocationSequence objects
465 // are created.
466 if (!allocation_sequences_created_) {
467 return false;
468 }
469
470 // Check that all port allocation sequences are complete (not running).
471 if (std::any_of(sequences_.begin(), sequences_.end(),
472 [](const AllocationSequence* sequence) {
473 return sequence->state() == AllocationSequence::kRunning;
474 })) {
475 return false;
476 }
477
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700478 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700479 // expected candidates. Session will trigger candidates allocation complete
480 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700481 return std::none_of(ports_.begin(), ports_.end(),
482 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700483}
484
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000485void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
486 switch (message->message_id) {
487 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800488 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 GetPortConfigurations();
490 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000491 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800492 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000493 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
494 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000495 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800496 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497 OnAllocate();
498 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000499 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800500 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000501 OnAllocationSequenceObjectsCreated();
502 break;
503 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800504 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505 OnConfigStop();
506 break;
507 default:
nissec80e7412017-01-11 05:56:46 -0800508 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 }
510}
511
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700512void BasicPortAllocatorSession::UpdateIceParametersInternal() {
513 for (PortData& port : ports_) {
514 port.port()->set_content_name(content_name());
515 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
516 }
517}
518
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000519void BasicPortAllocatorSession::GetPortConfigurations() {
520 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
521 username(),
522 password());
523
deadbeef653b8e02015-11-11 12:55:10 -0800524 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
525 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000526 }
527 ConfigReady(config);
528}
529
530void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700531 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532}
533
534// Adds a configuration to the list.
535void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800536 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000537 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800538 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000539
540 AllocatePorts();
541}
542
543void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800544 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000545
546 // If any of the allocated ports have not completed the candidates allocation,
547 // mark those as error. Since session doesn't need any new candidates
548 // at this stage of the allocation, it's safe to discard any new candidates.
549 bool send_signal = false;
550 for (std::vector<PortData>::iterator it = ports_.begin();
551 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700552 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000553 // Updating port state to error, which didn't finish allocating candidates
554 // yet.
555 it->set_error();
556 send_signal = true;
557 }
558 }
559
560 // Did we stop any running sequences?
561 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
562 it != sequences_.end() && !send_signal; ++it) {
563 if ((*it)->state() == AllocationSequence::kStopped) {
564 send_signal = true;
565 }
566 }
567
568 // If we stopped anything that was running, send a done signal now.
569 if (send_signal) {
570 MaybeSignalCandidatesAllocationDone();
571 }
572}
573
574void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800575 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700576 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000577}
578
579void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700580 if (network_manager_started_ && !IsStopped()) {
581 bool disable_equivalent_phases = true;
582 DoAllocate(disable_equivalent_phases);
583 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000584
585 allocation_started_ = true;
586}
587
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700588std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
589 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700590 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800591 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700592 // If the network permission state is BLOCKED, we just act as if the flag has
593 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700594 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700595 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700596 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
597 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000598 // If the adapter enumeration is disabled, we'll just bind to any address
599 // instead of specific NIC. This is to ensure the same routing for http
600 // traffic by OS is also used here to avoid any local or public IP leakage
601 // during stun process.
602 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700603 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000604 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700605 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800606 // If network enumeration fails, use the ANY address as a fallback, so we
607 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700608 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
609 // set, we'll use ANY address candidates either way.
610 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800611 network_manager->GetAnyAddressNetworks(&networks);
612 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000613 }
deadbeef3427f532017-07-26 16:09:33 -0700614 // Do some more filtering, depending on the network ignore mask and "disable
615 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700616 networks.erase(std::remove_if(networks.begin(), networks.end(),
617 [this](rtc::Network* network) {
618 return allocator_->network_ignore_mask() &
619 network->type();
620 }),
621 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700622 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
623 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700624 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700625 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
626 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700627 networks.erase(std::remove_if(networks.begin(), networks.end(),
628 [lowest_cost](rtc::Network* network) {
629 return network->GetCost() >
630 lowest_cost + rtc::kNetworkCostLow;
631 }),
632 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700633 }
deadbeef3427f532017-07-26 16:09:33 -0700634 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
635 // default, it's 5), remove networks to ensure that limit is satisfied.
636 //
637 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
638 // networks, we could try to choose a set that's "most likely to work". It's
639 // hard to define what that means though; it's not just "lowest cost".
640 // Alternatively, we could just focus on making our ICE pinging logic smarter
641 // such that this filtering isn't necessary in the first place.
642 int ipv6_networks = 0;
643 for (auto it = networks.begin(); it != networks.end();) {
644 if ((*it)->prefix().family() == AF_INET6) {
645 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
646 it = networks.erase(it);
647 continue;
648 } else {
649 ++ipv6_networks;
650 }
651 }
652 ++it;
653 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700654 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700655}
656
657// For each network, see if we have a sequence that covers it already. If not,
658// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700659void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700660 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700661 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100663 RTC_LOG(LS_WARNING)
664 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000665 done_signal_needed = true;
666 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100667 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700668 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200669 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200670 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000671 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
672 // If all the ports are disabled we should just fire the allocation
673 // done event and return.
674 done_signal_needed = true;
675 break;
676 }
677
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000678 if (!config || config->relays.empty()) {
679 // No relay ports specified in this config.
680 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
681 }
682
683 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 // Skip IPv6 networks unless the flag's been set.
686 continue;
687 }
688
zhihuangb09b3f92017-03-07 14:40:51 -0800689 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
690 networks[i]->GetBestIP().family() == AF_INET6 &&
691 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
692 // Skip IPv6 Wi-Fi networks unless the flag's been set.
693 continue;
694 }
695
Steve Anton300bf8e2017-07-14 10:13:10 -0700696 if (disable_equivalent) {
697 // Disable phases that would only create ports equivalent to
698 // ones that we have already made.
699 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000700
Steve Anton300bf8e2017-07-14 10:13:10 -0700701 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
702 // New AllocationSequence would have nothing to do, so don't make it.
703 continue;
704 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 }
706
707 AllocationSequence* sequence =
708 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000709 sequence->SignalPortAllocationComplete.connect(
710 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700711 sequence->Init();
712 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000713 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700714 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000715 }
716 }
717 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700718 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719 }
720}
721
722void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700723 std::vector<rtc::Network*> networks = GetNetworks();
724 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700725 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700726 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700727 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700728 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700729 std::find(networks.begin(), networks.end(), sequence->network()) ==
730 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700731 sequence->OnNetworkFailed();
732 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700733 }
734 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700735 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
736 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100737 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
738 << " ports because their networks were gone";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700739 PrunePortsAndRemoveCandidates(ports_to_prune);
740 }
honghaiz8c404fa2015-09-28 07:59:43 -0700741
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700742 if (allocation_started_ && !IsStopped()) {
743 if (network_manager_started_) {
744 // If the network manager has started, it must be regathering.
745 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
746 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700747 bool disable_equivalent_phases = true;
748 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700749 }
750
Honghai Zhang5048f572016-08-23 15:47:33 -0700751 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100752 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700753 network_manager_started_ = true;
754 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755}
756
757void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200758 rtc::Network* network,
759 PortConfiguration* config,
760 uint32_t* flags) {
761 for (uint32_t i = 0; i < sequences_.size() &&
762 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
763 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000764 sequences_[i]->DisableEquivalentPhases(network, config, flags);
765 }
766}
767
768void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
769 AllocationSequence * seq,
770 bool prepare_address) {
771 if (!port)
772 return;
773
Mirko Bonadei675513b2017-11-09 11:09:25 +0100774 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000775 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700776 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000777 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700778 if (allocator_->proxy().type != rtc::PROXY_NONE)
779 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700780 port->set_send_retransmit_count_attribute(
781 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000783 PortData data(port, seq);
784 ports_.push_back(data);
785
786 port->SignalCandidateReady.connect(
787 this, &BasicPortAllocatorSession::OnCandidateReady);
788 port->SignalPortComplete.connect(this,
789 &BasicPortAllocatorSession::OnPortComplete);
790 port->SignalDestroyed.connect(this,
791 &BasicPortAllocatorSession::OnPortDestroyed);
792 port->SignalPortError.connect(
793 this, &BasicPortAllocatorSession::OnPortError);
794 LOG_J(LS_INFO, port) << "Added port to allocator";
795
796 if (prepare_address)
797 port->PrepareAddress();
798}
799
800void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
801 allocation_sequences_created_ = true;
802 // Send candidate allocation complete signal if we have no sequences.
803 MaybeSignalCandidatesAllocationDone();
804}
805
806void BasicPortAllocatorSession::OnCandidateReady(
807 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800808 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000809 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800810 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700811 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700813 // already done with gathering.
814 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100815 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700816 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700817 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700818 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700819
danilchapf4e8cf02016-06-30 01:55:03 -0700820 // Mark that the port has a pairable candidate, either because we have a
821 // usable candidate from the port, or simply because the port is bound to the
822 // any address and therefore has no host candidate. This will trigger the port
823 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700824 // checks. If port has already been marked as having a pairable candidate,
825 // do nothing here.
826 // Note: We should check whether any candidates may become ready after this
827 // because there we will check whether the candidate is generated by the ready
828 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700829 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700830 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700831 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700832
833 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700834 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700835 }
836 // If the current port is not pruned yet, SignalPortReady.
837 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700838 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700839 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700840 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700841 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700842 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700843
deadbeef1c5e6d02017-09-15 17:46:56 -0700844 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700845 std::vector<Candidate> candidates;
846 candidates.push_back(SanitizeRelatedAddress(c));
847 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700848 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100849 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700850 }
851
852 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700853 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700854 MaybeSignalCandidatesAllocationDone();
855 }
856}
857
858Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
859 const std::string& network_name) const {
860 Port* best_turn_port = nullptr;
861 for (const PortData& data : ports_) {
862 if (data.port()->Network()->name() == network_name &&
863 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
864 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
865 best_turn_port = data.port();
866 }
867 }
868 return best_turn_port;
869}
870
871bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700872 // Note: We determine the same network based only on their network names. So
873 // if an IPv4 address and an IPv6 address have the same network name, they
874 // are considered the same network here.
875 const std::string& network_name = newly_pairable_turn_port->Network()->name();
876 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
877 // |port| is already in the list of ports, so the best port cannot be nullptr.
878 RTC_CHECK(best_turn_port != nullptr);
879
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700880 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700881 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700882 for (PortData& data : ports_) {
883 if (data.port()->Network()->name() == network_name &&
884 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
885 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700886 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700887 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700888 // These ports will be pruned in PrunePortsAndRemoveCandidates.
889 ports_to_prune.push_back(&data);
890 } else {
891 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700892 }
893 }
894 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700895
896 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
898 << " low-priority TURN ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700899 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700900 }
901 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902}
903
Honghai Zhanga74363c2016-07-28 18:06:15 -0700904void BasicPortAllocatorSession::PruneAllPorts() {
905 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700906 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700907 }
908}
909
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800911 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700912 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800914 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915
916 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700917 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700919 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920
921 // Moving to COMPLETE state.
922 data->set_complete();
923 // Send candidate allocation complete signal if this was the last port.
924 MaybeSignalCandidatesAllocationDone();
925}
926
927void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800928 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700929 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800931 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000932 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700933 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000934 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700935 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936
937 // SignalAddressError is currently sent from StunPort/TurnPort.
938 // But this signal itself is generic.
939 data->set_error();
940 // Send candidate allocation complete signal if this was the last port.
941 MaybeSignalCandidatesAllocationDone();
942}
943
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700944bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700945 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000946
947 // When binding to any address, before sending packets out, the getsockname
948 // returns all 0s, but after sending packets, it'll be the NIC used to
949 // send. All 0s is not a valid ICE candidate address and should be filtered
950 // out.
951 if (c.address().IsAnyIP()) {
952 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000953 }
954
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000955 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000956 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000957 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000958 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000959 } else if (c.type() == LOCAL_PORT_TYPE) {
960 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
961 // We allow host candidates if the filter allows server-reflexive
962 // candidates and the candidate is a public IP. Because we don't generate
963 // server-reflexive candidates if they have the same IP as the host
964 // candidate (i.e. when the host candidate is a public IP), filtering to
965 // only server-reflexive candidates won't work right when the host
966 // candidates have public IPs.
967 return true;
968 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000969
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000970 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000971 }
972 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973}
974
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700975bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
976 const Port* port) const {
977 bool candidate_signalable = CheckCandidateFilter(c);
978
979 // When device enumeration is disabled (to prevent non-default IP addresses
980 // from leaking), we ping from some local candidates even though we don't
981 // signal them. However, if host candidates are also disabled (for example, to
982 // prevent even default IP addresses from leaking), we still don't want to
983 // ping from them, even if device enumeration is disabled. Thus, we check for
984 // both device enumeration and host candidates being disabled.
985 bool network_enumeration_disabled = c.address().IsAnyIP();
986 bool can_ping_from_candidate =
987 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
988 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
989
990 return candidate_signalable ||
991 (network_enumeration_disabled && can_ping_from_candidate &&
992 !host_candidates_disabled);
993}
994
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000995void BasicPortAllocatorSession::OnPortAllocationComplete(
996 AllocationSequence* seq) {
997 // Send candidate allocation complete signal if all ports are done.
998 MaybeSignalCandidatesAllocationDone();
999}
1000
1001void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001002 if (CandidatesAllocationDone()) {
1003 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001004 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001005 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001006 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1007 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001008 }
1009 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001011}
1012
1013void BasicPortAllocatorSession::OnPortDestroyed(
1014 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001015 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001016 for (std::vector<PortData>::iterator iter = ports_.begin();
1017 iter != ports_.end(); ++iter) {
1018 if (port == iter->port()) {
1019 ports_.erase(iter);
1020 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1021 << static_cast<int>(ports_.size()) << " remaining)";
1022 return;
1023 }
1024 }
nissec80e7412017-01-11 05:56:46 -08001025 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001026}
1027
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001028BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1029 Port* port) {
1030 for (std::vector<PortData>::iterator it = ports_.begin();
1031 it != ports_.end(); ++it) {
1032 if (it->port() == port) {
1033 return &*it;
1034 }
1035 }
1036 return NULL;
1037}
1038
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001039std::vector<BasicPortAllocatorSession::PortData*>
1040BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001041 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001042 std::vector<PortData*> unpruned_ports;
1043 for (PortData& port : ports_) {
1044 if (!port.pruned() &&
1045 std::find(networks.begin(), networks.end(),
1046 port.sequence()->network()) != networks.end()) {
1047 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001048 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001049 }
1050 return unpruned_ports;
1051}
1052
1053void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1054 const std::vector<PortData*>& port_data_list) {
1055 std::vector<PortInterface*> pruned_ports;
1056 std::vector<Candidate> removed_candidates;
1057 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001058 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001059 data->Prune();
1060 pruned_ports.push_back(data->port());
1061 if (data->has_pairable_candidate()) {
1062 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001063 // Mark the port as having no pairable candidates so that its candidates
1064 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001065 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001066 }
1067 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001068 if (!pruned_ports.empty()) {
1069 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001070 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001071 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001072 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1073 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001074 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001075 }
1076}
1077
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001078// AllocationSequence
1079
1080AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1081 rtc::Network* network,
1082 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001083 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001084 : session_(session),
1085 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086 config_(config),
1087 state_(kInit),
1088 flags_(flags),
1089 udp_socket_(),
1090 udp_port_(NULL),
1091 phase_(0) {
1092}
1093
Honghai Zhang5048f572016-08-23 15:47:33 -07001094void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001095 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1096 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001097 rtc::SocketAddress(network_->GetBestIP(), 0),
1098 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001099 if (udp_socket_) {
1100 udp_socket_->SignalReadPacket.connect(
1101 this, &AllocationSequence::OnReadPacket);
1102 }
1103 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1104 // are next available options to setup a communication channel.
1105 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106}
1107
1108void AllocationSequence::Clear() {
1109 udp_port_ = NULL;
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001110 turn_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111}
1112
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001113void AllocationSequence::OnNetworkFailed() {
1114 RTC_DCHECK(!network_failed_);
1115 network_failed_ = true;
1116 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001117 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001118}
1119
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001120AllocationSequence::~AllocationSequence() {
1121 session_->network_thread()->Clear(this);
1122}
1123
1124void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001125 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001126 if (network_failed_) {
1127 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001128 // it won't be equivalent to the new network.
1129 return;
1130 }
1131
deadbeef5c3c1042017-08-04 15:01:57 -07001132 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133 // Different network setup; nothing is equivalent.
1134 return;
1135 }
1136
1137 // Else turn off the stuff that we've already got covered.
1138
deadbeef1c46a352017-09-27 11:24:05 -07001139 // Every config implicitly specifies local, so turn that off right away if we
1140 // already have a port of the corresponding type. Look for a port that
1141 // matches this AllocationSequence's network, is the right protocol, and
1142 // hasn't encountered an error.
1143 // TODO(deadbeef): This doesn't take into account that there may be another
1144 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1145 // This can happen if, say, there's a network change event right before an
1146 // application-triggered ICE restart. Hopefully this problem will just go
1147 // away if we get rid of the gathering "phases" though, which is planned.
1148 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1149 [this](const BasicPortAllocatorSession::PortData& p) {
1150 return p.port()->Network() == network_ &&
1151 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1152 })) {
1153 *flags |= PORTALLOCATOR_DISABLE_UDP;
1154 }
1155 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1156 [this](const BasicPortAllocatorSession::PortData& p) {
1157 return p.port()->Network() == network_ &&
1158 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1159 })) {
1160 *flags |= PORTALLOCATOR_DISABLE_TCP;
1161 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001162
1163 if (config_ && config) {
1164 if (config_->StunServers() == config->StunServers()) {
1165 // Already got this STUN servers covered.
1166 *flags |= PORTALLOCATOR_DISABLE_STUN;
1167 }
1168 if (!config_->relays.empty()) {
1169 // Already got relays covered.
1170 // NOTE: This will even skip a _different_ set of relay servers if we
1171 // were to be given one, but that never happens in our codebase. Should
1172 // probably get rid of the list in PortConfiguration and just keep a
1173 // single relay server in each one.
1174 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1175 }
1176 }
1177}
1178
1179void AllocationSequence::Start() {
1180 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001181 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001182 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1183 // called next time, we enable all phases if the best IP has since changed.
1184 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001185}
1186
1187void AllocationSequence::Stop() {
1188 // If the port is completed, don't set it to stopped.
1189 if (state_ == kRunning) {
1190 state_ = kStopped;
1191 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1192 }
1193}
1194
1195void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001196 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1197 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001198
deadbeef1c5e6d02017-09-15 17:46:56 -07001199 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001200
1201 // Perform all of the phases in the current step.
1202 LOG_J(LS_INFO, network_) << "Allocation Phase="
1203 << PHASE_NAMES[phase_];
1204
1205 switch (phase_) {
1206 case PHASE_UDP:
1207 CreateUDPPorts();
1208 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001209 break;
1210
1211 case PHASE_RELAY:
1212 CreateRelayPorts();
1213 break;
1214
1215 case PHASE_TCP:
1216 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 break;
1219
1220 default:
nissec80e7412017-01-11 05:56:46 -08001221 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 }
1223
1224 if (state() == kRunning) {
1225 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001226 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1227 session_->allocator()->step_delay(),
1228 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001229 } else {
1230 // If all phases in AllocationSequence are completed, no allocation
1231 // steps needed further. Canceling pending signal.
1232 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1233 SignalPortAllocationComplete(this);
1234 }
1235}
1236
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237void AllocationSequence::CreateUDPPorts() {
1238 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001239 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240 return;
1241 }
1242
1243 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1244 // is enabled completely.
1245 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001246 bool emit_local_candidate_for_anyaddress =
1247 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001248 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001249 port = UDPPort::Create(
1250 session_->network_thread(), session_->socket_factory(), network_,
1251 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001252 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001254 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001255 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001256 session_->allocator()->min_port(), session_->allocator()->max_port(),
1257 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001258 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001259 }
1260
1261 if (port) {
1262 // If shared socket is enabled, STUN candidate will be allocated by the
1263 // UDPPort.
1264 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1265 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001266 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001267
1268 // If STUN is not disabled, setting stun server address to port.
1269 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001271 RTC_LOG(LS_INFO)
1272 << "AllocationSequence: UDPPort will be handling the "
1273 << "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001274 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001275 }
1276 }
1277 }
1278
1279 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001280 }
1281}
1282
1283void AllocationSequence::CreateTCPPorts() {
1284 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001285 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001286 return;
1287 }
1288
deadbeef5c3c1042017-08-04 15:01:57 -07001289 Port* port = TCPPort::Create(
1290 session_->network_thread(), session_->socket_factory(), network_,
1291 session_->allocator()->min_port(), session_->allocator()->max_port(),
1292 session_->username(), session_->password(),
1293 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001294 if (port) {
1295 session_->AddAllocatedPort(port, this, true);
1296 // Since TCPPort is not created using shared socket, |port| will not be
1297 // added to the dequeue.
1298 }
1299}
1300
1301void AllocationSequence::CreateStunPorts() {
1302 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001303 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001304 return;
1305 }
1306
1307 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1308 return;
1309 }
1310
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001311 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001312 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313 << "AllocationSequence: No STUN server configured, skipping.";
1314 return;
1315 }
1316
deadbeef5c3c1042017-08-04 15:01:57 -07001317 StunPort* port = StunPort::Create(
1318 session_->network_thread(), session_->socket_factory(), network_,
1319 session_->allocator()->min_port(), session_->allocator()->max_port(),
1320 session_->username(), session_->password(), config_->StunServers(),
1321 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 if (port) {
1323 session_->AddAllocatedPort(port, this, true);
1324 // Since StunPort is not created using shared socket, |port| will not be
1325 // added to the dequeue.
1326 }
1327}
1328
1329void AllocationSequence::CreateRelayPorts() {
1330 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001331 RTC_LOG(LS_VERBOSE)
1332 << "AllocationSequence: Relay ports disabled, skipping.";
1333 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001334 }
1335
1336 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1337 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001338 RTC_DCHECK(config_);
1339 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001340 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001341 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 << "AllocationSequence: No relay server configured, skipping.";
1343 return;
1344 }
1345
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001346 for (RelayServerConfig& relay : config_->relays) {
1347 if (relay.type == RELAY_GTURN) {
1348 CreateGturnPort(relay);
1349 } else if (relay.type == RELAY_TURN) {
1350 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001351 } else {
nissec80e7412017-01-11 05:56:46 -08001352 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001353 }
1354 }
1355}
1356
1357void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1358 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001359 RelayPort* port = RelayPort::Create(
1360 session_->network_thread(), session_->socket_factory(), network_,
1361 session_->allocator()->min_port(), session_->allocator()->max_port(),
1362 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001363 if (port) {
1364 // Since RelayPort is not created using shared socket, |port| will not be
1365 // added to the dequeue.
1366 // Note: We must add the allocated port before we add addresses because
1367 // the latter will create candidates that need name and preference
1368 // settings. However, we also can't prepare the address (normally
1369 // done by AddAllocatedPort) until we have these addresses. So we
1370 // wait to do that until below.
1371 session_->AddAllocatedPort(port, this, false);
1372
1373 // Add the addresses of this protocol.
1374 PortList::const_iterator relay_port;
1375 for (relay_port = config.ports.begin();
1376 relay_port != config.ports.end();
1377 ++relay_port) {
1378 port->AddServerAddress(*relay_port);
1379 port->AddExternalAddress(*relay_port);
1380 }
1381 // Start fetching an address for this port.
1382 port->PrepareAddress();
1383 }
1384}
1385
1386void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1387 PortList::const_iterator relay_port;
1388 for (relay_port = config.ports.begin();
1389 relay_port != config.ports.end(); ++relay_port) {
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001390 TurnPort* port = NULL;
1391
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001392 // Skip UDP connections to relay servers if it's disallowed.
1393 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1394 relay_port->proto == PROTO_UDP) {
1395 continue;
1396 }
1397
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001398 // Do not create a port if the server address family is known and does
1399 // not match the local IP address family.
1400 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001401 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001402 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001403 RTC_LOG(LS_INFO)
1404 << "Server and local address families are not compatible. "
1405 << "Server address: " << relay_port->address.ipaddr().ToString()
1406 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001407 continue;
1408 }
1409
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001410 // Shared socket mode must be enabled only for UDP based ports. Hence
1411 // don't pass shared socket for ports which will create TCP sockets.
1412 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1413 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1414 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001415 relay_port->proto == PROTO_UDP && udp_socket_) {
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001416 port = TurnPort::Create(session_->network_thread(),
1417 session_->socket_factory(),
1418 network_, udp_socket_.get(),
1419 session_->username(), session_->password(),
1420 *relay_port, config.credentials, config.priority,
1421 session_->allocator()->origin(),
1422 session_->allocator()->turn_customizer());
1423 turn_ports_.push_back(port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001424 // Listen to the port destroyed signal, to allow AllocationSequence to
1425 // remove entrt from it's map.
1426 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1427 } else {
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001428 port = TurnPort::Create(
1429 session_->network_thread(), session_->socket_factory(), network_,
1430 session_->allocator()->min_port(), session_->allocator()->max_port(),
1431 session_->username(), session_->password(), *relay_port,
1432 config.credentials, config.priority, session_->allocator()->origin(),
1433 config.tls_alpn_protocols, config.tls_elliptic_curves,
1434 session_->allocator()->turn_customizer());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001435 }
nisseede5da42017-01-12 05:15:36 -08001436 RTC_DCHECK(port != NULL);
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001437 port->SetTlsCertPolicy(config.tls_cert_policy);
1438 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001439 }
1440}
1441
1442void AllocationSequence::OnReadPacket(
1443 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1444 const rtc::SocketAddress& remote_addr,
1445 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001446 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001447
1448 bool turn_port_found = false;
1449
1450 // Try to find the TurnPort that matches the remote address. Note that the
1451 // message could be a STUN binding response if the TURN server is also used as
1452 // a STUN server. We don't want to parse every message here to check if it is
1453 // a STUN binding response, so we pass the message to TurnPort regardless of
1454 // the message type. The TurnPort will just ignore the message since it will
1455 // not find any request by transaction ID.
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001456 for (TurnPort* port : turn_ports_) {
1457 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001458 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1459 packet_time)) {
1460 return;
1461 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463 }
1464 }
1465
1466 if (udp_port_) {
1467 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1468
1469 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1470 // the TURN server is also a STUN server.
1471 if (!turn_port_found ||
1472 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001473 RTC_DCHECK(udp_port_->SharedSocket());
1474 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1475 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001476 }
1477 }
1478}
1479
1480void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1481 if (udp_port_ == port) {
1482 udp_port_ = NULL;
1483 return;
1484 }
1485
Guido Urdanetaf1a7a8c2017-12-15 17:47:37 +00001486 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1487 if (it != turn_ports_.end()) {
1488 turn_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001489 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001490 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001491 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001492 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001493}
1494
1495// PortConfiguration
1496PortConfiguration::PortConfiguration(
1497 const rtc::SocketAddress& stun_address,
1498 const std::string& username,
1499 const std::string& password)
1500 : stun_address(stun_address), username(username), password(password) {
1501 if (!stun_address.IsNil())
1502 stun_servers.insert(stun_address);
1503}
1504
1505PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1506 const std::string& username,
1507 const std::string& password)
1508 : stun_servers(stun_servers),
1509 username(username),
1510 password(password) {
1511 if (!stun_servers.empty())
1512 stun_address = *(stun_servers.begin());
1513}
1514
Steve Anton7995d8c2017-10-30 16:23:38 -07001515PortConfiguration::~PortConfiguration() = default;
1516
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001517ServerAddresses PortConfiguration::StunServers() {
1518 if (!stun_address.IsNil() &&
1519 stun_servers.find(stun_address) == stun_servers.end()) {
1520 stun_servers.insert(stun_address);
1521 }
deadbeefc5d0d952015-07-16 10:22:21 -07001522 // Every UDP TURN server should also be used as a STUN server.
1523 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1524 for (const rtc::SocketAddress& turn_server : turn_servers) {
1525 if (stun_servers.find(turn_server) == stun_servers.end()) {
1526 stun_servers.insert(turn_server);
1527 }
1528 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001529 return stun_servers;
1530}
1531
1532void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1533 relays.push_back(config);
1534}
1535
1536bool PortConfiguration::SupportsProtocol(
1537 const RelayServerConfig& relay, ProtocolType type) const {
1538 PortList::const_iterator relay_port;
1539 for (relay_port = relay.ports.begin();
1540 relay_port != relay.ports.end();
1541 ++relay_port) {
1542 if (relay_port->proto == type)
1543 return true;
1544 }
1545 return false;
1546}
1547
1548bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1549 ProtocolType type) const {
1550 for (size_t i = 0; i < relays.size(); ++i) {
1551 if (relays[i].type == turn_type &&
1552 SupportsProtocol(relays[i], type))
1553 return true;
1554 }
1555 return false;
1556}
1557
1558ServerAddresses PortConfiguration::GetRelayServerAddresses(
1559 RelayType turn_type, ProtocolType type) const {
1560 ServerAddresses servers;
1561 for (size_t i = 0; i < relays.size(); ++i) {
1562 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1563 servers.insert(relays[i].ports.front().address);
1564 }
1565 }
1566 return servers;
1567}
1568
1569} // namespace cricket