blob: e161a864b02b9168d34a88366d7fd4518c6b654c [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>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000014#include <string>
15#include <vector>
16
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/umametrics.h"
18#include "p2p/base/basicpacketsocketfactory.h"
19#include "p2p/base/common.h"
20#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"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000029
30using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32namespace {
33
34enum {
35 MSG_CONFIG_START,
36 MSG_CONFIG_READY,
37 MSG_ALLOCATE,
38 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000039 MSG_SEQUENCEOBJECTS_CREATED,
40 MSG_CONFIG_STOP,
41};
42
43const int PHASE_UDP = 0;
44const int PHASE_RELAY = 1;
45const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046
deadbeef1c5e6d02017-09-15 17:46:56 -070047const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000048
zhihuang696f8ca2017-06-27 15:11:24 -070049// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070050int GetProtocolPriority(cricket::ProtocolType protocol) {
51 switch (protocol) {
52 case cricket::PROTO_UDP:
53 return 2;
54 case cricket::PROTO_TCP:
55 return 1;
56 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070057 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070058 return 0;
59 default:
nisseeb4ca4e2017-01-12 02:24:27 -080060 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070061 return 0;
62 }
63}
64// Gets address family priority: IPv6 > IPv4 > Unspecified.
65int GetAddressFamilyPriority(int ip_family) {
66 switch (ip_family) {
67 case AF_INET6:
68 return 2;
69 case AF_INET:
70 return 1;
71 default:
nisseeb4ca4e2017-01-12 02:24:27 -080072 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070073 return 0;
74 }
75}
76
77// Returns positive if a is better, negative if b is better, and 0 otherwise.
78int ComparePort(const cricket::Port* a, const cricket::Port* b) {
79 int a_protocol = GetProtocolPriority(a->GetProtocol());
80 int b_protocol = GetProtocolPriority(b->GetProtocol());
81 int cmp_protocol = a_protocol - b_protocol;
82 if (cmp_protocol != 0) {
83 return cmp_protocol;
84 }
85
86 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
87 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
88 return a_family - b_family;
89}
90
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091} // namespace
92
93namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020094const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070095 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
96 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097
98// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +020099BasicPortAllocator::BasicPortAllocator(
100 rtc::NetworkManager* network_manager,
101 rtc::PacketSocketFactory* socket_factory,
102 webrtc::TurnCustomizer* customizer)
maxmorine9ef9072017-08-29 04:49:00 -0700103 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800104 RTC_DCHECK(network_manager_ != nullptr);
105 RTC_DCHECK(socket_factory_ != nullptr);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200106 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(),
107 0, false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000108 Construct();
109}
110
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800111BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700112 : network_manager_(network_manager), socket_factory_(nullptr) {
nisseede5da42017-01-12 05:15:36 -0800113 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114 Construct();
115}
116
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700117BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
118 rtc::PacketSocketFactory* socket_factory,
119 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700120 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800121 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200122 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
123 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000124 Construct();
125}
126
127BasicPortAllocator::BasicPortAllocator(
128 rtc::NetworkManager* network_manager,
129 const ServerAddresses& stun_servers,
130 const rtc::SocketAddress& relay_address_udp,
131 const rtc::SocketAddress& relay_address_tcp,
132 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700133 : network_manager_(network_manager), socket_factory_(NULL) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700134 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800136 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000137 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800138 }
139 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800141 }
142 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000143 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800144 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145
deadbeef653b8e02015-11-11 12:55:10 -0800146 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700147 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800148 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000149
Jonas Orelandbdcee282017-10-10 14:01:40 +0200150 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 Construct();
152}
153
154void BasicPortAllocator::Construct() {
155 allow_tcp_listen_ = true;
156}
157
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700158void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
159 IceRegatheringReason reason) {
160 if (!metrics_observer()) {
161 return;
162 }
163 // If the session has not been taken by an active channel, do not report the
164 // metric.
165 for (auto& allocator_session : pooled_sessions()) {
166 if (allocator_session.get() == session) {
167 return;
168 }
169 }
170
171 metrics_observer()->IncrementEnumCounter(
172 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
173 static_cast<int>(IceRegatheringReason::MAX_VALUE));
174}
175
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800177 // Our created port allocator sessions depend on us, so destroy our remaining
178 // pooled sessions before anything else.
179 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000180}
181
Steve Anton7995d8c2017-10-30 16:23:38 -0700182void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
183 // TODO(phoglund): implement support for other types than loopback.
184 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
185 // Then remove set_network_ignore_list from NetworkManager.
186 network_ignore_mask_ = network_ignore_mask;
187}
188
deadbeefc5d0d952015-07-16 10:22:21 -0700189PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190 const std::string& content_name, int component,
191 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700192 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700194 session->SignalIceRegathering.connect(this,
195 &BasicPortAllocator::OnIceRegathering);
196 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197}
198
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700199void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
200 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
201 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700202 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200203 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700204}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205
206// BasicPortAllocatorSession
207BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700208 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 const std::string& content_name,
210 int component,
211 const std::string& ice_ufrag,
212 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700213 : PortAllocatorSession(content_name,
214 component,
215 ice_ufrag,
216 ice_pwd,
217 allocator->flags()),
218 allocator_(allocator),
219 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 socket_factory_(allocator->socket_factory()),
221 allocation_started_(false),
222 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700223 allocation_sequences_created_(false),
224 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000225 allocator_->network_manager()->SignalNetworksChanged.connect(
226 this, &BasicPortAllocatorSession::OnNetworksChanged);
227 allocator_->network_manager()->StartUpdating();
228}
229
230BasicPortAllocatorSession::~BasicPortAllocatorSession() {
231 allocator_->network_manager()->StopUpdating();
232 if (network_thread_ != NULL)
233 network_thread_->Clear(this);
234
Peter Boström0c4e06b2015-10-07 12:23:21 +0200235 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000236 // AllocationSequence should clear it's map entry for turn ports before
237 // ports are destroyed.
238 sequences_[i]->Clear();
239 }
240
241 std::vector<PortData>::iterator it;
242 for (it = ports_.begin(); it != ports_.end(); it++)
243 delete it->port();
244
Peter Boström0c4e06b2015-10-07 12:23:21 +0200245 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000246 delete configs_[i];
247
Peter Boström0c4e06b2015-10-07 12:23:21 +0200248 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249 delete sequences_[i];
250}
251
Steve Anton7995d8c2017-10-30 16:23:38 -0700252BasicPortAllocator* BasicPortAllocatorSession::allocator() {
253 return allocator_;
254}
255
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700256void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
257 if (filter == candidate_filter_) {
258 return;
259 }
260 // We assume the filter will only change from "ALL" to something else.
261 RTC_DCHECK(candidate_filter_ == CF_ALL);
262 candidate_filter_ = filter;
263 for (PortData& port : ports_) {
264 if (!port.has_pairable_candidate()) {
265 continue;
266 }
267 const auto& candidates = port.port()->Candidates();
268 // Setting a filter may cause a ready port to become non-ready
269 // if it no longer has any pairable candidates.
270 if (!std::any_of(candidates.begin(), candidates.end(),
271 [this, &port](const Candidate& candidate) {
272 return CandidatePairable(candidate, port.port());
273 })) {
274 port.set_has_pairable_candidate(false);
275 }
276 }
277}
278
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279void BasicPortAllocatorSession::StartGettingPorts() {
280 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700281 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000282 if (!socket_factory_) {
283 owned_socket_factory_.reset(
284 new rtc::BasicPacketSocketFactory(network_thread_));
285 socket_factory_ = owned_socket_factory_.get();
286 }
287
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700288 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700289
Mirko Bonadei675513b2017-11-09 11:09:25 +0100290 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
291 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292}
293
294void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800295 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700296 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700297 // Note: this must be called after ClearGettingPorts because both may set the
298 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700299 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700300}
301
302void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800303 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000304 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700305 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000306 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700307 }
deadbeefb60a8192016-08-24 15:15:00 -0700308 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700309 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700310}
311
Steve Anton7995d8c2017-10-30 16:23:38 -0700312bool BasicPortAllocatorSession::IsGettingPorts() {
313 return state_ == SessionState::GATHERING;
314}
315
316bool BasicPortAllocatorSession::IsCleared() const {
317 return state_ == SessionState::CLEARED;
318}
319
320bool BasicPortAllocatorSession::IsStopped() const {
321 return state_ == SessionState::STOPPED;
322}
323
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700324std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
325 std::vector<rtc::Network*> networks = GetNetworks();
326
327 // A network interface may have both IPv4 and IPv6 networks. Only if
328 // neither of the networks has any connections, the network interface
329 // is considered failed and need to be regathered on.
330 std::set<std::string> networks_with_connection;
331 for (const PortData& data : ports_) {
332 Port* port = data.port();
333 if (!port->connections().empty()) {
334 networks_with_connection.insert(port->Network()->name());
335 }
336 }
337
338 networks.erase(
339 std::remove_if(networks.begin(), networks.end(),
340 [networks_with_connection](rtc::Network* network) {
341 // If a network does not have any connection, it is
342 // considered failed.
343 return networks_with_connection.find(network->name()) !=
344 networks_with_connection.end();
345 }),
346 networks.end());
347 return networks;
348}
349
350void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
351 // Find the list of networks that have no connection.
352 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
353 if (failed_networks.empty()) {
354 return;
355 }
356
Mirko Bonadei675513b2017-11-09 11:09:25 +0100357 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700358
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700359 // Mark a sequence as "network failed" if its network is in the list of failed
360 // networks, so that it won't be considered as equivalent when the session
361 // regathers ports and candidates.
362 for (AllocationSequence* sequence : sequences_) {
363 if (!sequence->network_failed() &&
364 std::find(failed_networks.begin(), failed_networks.end(),
365 sequence->network()) != failed_networks.end()) {
366 sequence->set_network_failed();
367 }
368 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700369
370 bool disable_equivalent_phases = true;
371 Regather(failed_networks, disable_equivalent_phases,
372 IceRegatheringReason::NETWORK_FAILURE);
373}
374
375void BasicPortAllocatorSession::RegatherOnAllNetworks() {
376 std::vector<rtc::Network*> networks = GetNetworks();
377 if (networks.empty()) {
378 return;
379 }
380
Mirko Bonadei675513b2017-11-09 11:09:25 +0100381 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700382
383 // We expect to generate candidates that are equivalent to what we have now.
384 // Force DoAllocate to generate them instead of skipping.
385 bool disable_equivalent_phases = false;
386 Regather(networks, disable_equivalent_phases,
387 IceRegatheringReason::OCCASIONAL_REFRESH);
388}
389
390void BasicPortAllocatorSession::Regather(
391 const std::vector<rtc::Network*>& networks,
392 bool disable_equivalent_phases,
393 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700394 // Remove ports from being used locally and send signaling to remove
395 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700396 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700397 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100398 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700399 PrunePortsAndRemoveCandidates(ports_to_prune);
400 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700401
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700402 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700403 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700404
Steve Anton300bf8e2017-07-14 10:13:10 -0700405 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700406 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407}
408
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700409std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
410 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700411 for (const PortData& data : ports_) {
412 if (data.ready()) {
413 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700414 }
415 }
416 return ret;
417}
418
419std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
420 std::vector<Candidate> candidates;
421 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700422 if (!data.ready()) {
423 continue;
424 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700425 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700426 }
427 return candidates;
428}
429
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700430void BasicPortAllocatorSession::GetCandidatesFromPort(
431 const PortData& data,
432 std::vector<Candidate>* candidates) const {
433 RTC_CHECK(candidates != nullptr);
434 for (const Candidate& candidate : data.port()->Candidates()) {
435 if (!CheckCandidateFilter(candidate)) {
436 continue;
437 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700438 candidates->push_back(SanitizeRelatedAddress(candidate));
439 }
440}
441
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700442Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
443 const Candidate& c) const {
444 Candidate copy = c;
445 // If adapter enumeration is disabled or host candidates are disabled,
446 // clear the raddr of STUN candidates to avoid local address leakage.
447 bool filter_stun_related_address =
448 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
449 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
450 !(candidate_filter_ & CF_HOST);
451 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
452 // to avoid reflexive address leakage.
453 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
454 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
455 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
456 copy.set_related_address(
457 rtc::EmptySocketAddressWithFamily(copy.address().family()));
458 }
459 return copy;
460}
461
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700462bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
463 // Done only if all required AllocationSequence objects
464 // are created.
465 if (!allocation_sequences_created_) {
466 return false;
467 }
468
469 // Check that all port allocation sequences are complete (not running).
470 if (std::any_of(sequences_.begin(), sequences_.end(),
471 [](const AllocationSequence* sequence) {
472 return sequence->state() == AllocationSequence::kRunning;
473 })) {
474 return false;
475 }
476
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700477 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700478 // expected candidates. Session will trigger candidates allocation complete
479 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700480 return std::none_of(ports_.begin(), ports_.end(),
481 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700482}
483
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
485 switch (message->message_id) {
486 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800487 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488 GetPortConfigurations();
489 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000490 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800491 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
493 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800495 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496 OnAllocate();
497 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000498 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800499 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000500 OnAllocationSequenceObjectsCreated();
501 break;
502 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800503 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504 OnConfigStop();
505 break;
506 default:
nissec80e7412017-01-11 05:56:46 -0800507 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508 }
509}
510
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700511void BasicPortAllocatorSession::UpdateIceParametersInternal() {
512 for (PortData& port : ports_) {
513 port.port()->set_content_name(content_name());
514 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
515 }
516}
517
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000518void BasicPortAllocatorSession::GetPortConfigurations() {
519 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
520 username(),
521 password());
522
deadbeef653b8e02015-11-11 12:55:10 -0800523 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
524 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000525 }
526 ConfigReady(config);
527}
528
529void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700530 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000531}
532
533// Adds a configuration to the list.
534void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800535 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800537 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000538
539 AllocatePorts();
540}
541
542void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800543 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000544
545 // If any of the allocated ports have not completed the candidates allocation,
546 // mark those as error. Since session doesn't need any new candidates
547 // at this stage of the allocation, it's safe to discard any new candidates.
548 bool send_signal = false;
549 for (std::vector<PortData>::iterator it = ports_.begin();
550 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700551 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 // Updating port state to error, which didn't finish allocating candidates
553 // yet.
554 it->set_error();
555 send_signal = true;
556 }
557 }
558
559 // Did we stop any running sequences?
560 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
561 it != sequences_.end() && !send_signal; ++it) {
562 if ((*it)->state() == AllocationSequence::kStopped) {
563 send_signal = true;
564 }
565 }
566
567 // If we stopped anything that was running, send a done signal now.
568 if (send_signal) {
569 MaybeSignalCandidatesAllocationDone();
570 }
571}
572
573void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800574 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700575 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000576}
577
578void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700579 if (network_manager_started_ && !IsStopped()) {
580 bool disable_equivalent_phases = true;
581 DoAllocate(disable_equivalent_phases);
582 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583
584 allocation_started_ = true;
585}
586
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700587std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
588 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700589 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800590 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700591 // If the network permission state is BLOCKED, we just act as if the flag has
592 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700593 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700594 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700595 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
596 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000597 // If the adapter enumeration is disabled, we'll just bind to any address
598 // instead of specific NIC. This is to ensure the same routing for http
599 // traffic by OS is also used here to avoid any local or public IP leakage
600 // during stun process.
601 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700602 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000603 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700604 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800605 // If network enumeration fails, use the ANY address as a fallback, so we
606 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700607 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
608 // set, we'll use ANY address candidates either way.
609 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800610 network_manager->GetAnyAddressNetworks(&networks);
611 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000612 }
deadbeef3427f532017-07-26 16:09:33 -0700613 // Do some more filtering, depending on the network ignore mask and "disable
614 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700615 networks.erase(std::remove_if(networks.begin(), networks.end(),
616 [this](rtc::Network* network) {
617 return allocator_->network_ignore_mask() &
618 network->type();
619 }),
620 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700621 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
622 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700623 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700624 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
625 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700626 networks.erase(std::remove_if(networks.begin(), networks.end(),
627 [lowest_cost](rtc::Network* network) {
628 return network->GetCost() >
629 lowest_cost + rtc::kNetworkCostLow;
630 }),
631 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700632 }
deadbeef3427f532017-07-26 16:09:33 -0700633 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
634 // default, it's 5), remove networks to ensure that limit is satisfied.
635 //
636 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
637 // networks, we could try to choose a set that's "most likely to work". It's
638 // hard to define what that means though; it's not just "lowest cost".
639 // Alternatively, we could just focus on making our ICE pinging logic smarter
640 // such that this filtering isn't necessary in the first place.
641 int ipv6_networks = 0;
642 for (auto it = networks.begin(); it != networks.end();) {
643 if ((*it)->prefix().family() == AF_INET6) {
644 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
645 it = networks.erase(it);
646 continue;
647 } else {
648 ++ipv6_networks;
649 }
650 }
651 ++it;
652 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700653 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700654}
655
656// For each network, see if we have a sequence that covers it already. If not,
657// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700658void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700659 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700660 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100662 RTC_LOG(LS_WARNING)
663 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664 done_signal_needed = true;
665 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100666 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700667 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200668 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200669 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
671 // If all the ports are disabled we should just fire the allocation
672 // done event and return.
673 done_signal_needed = true;
674 break;
675 }
676
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000677 if (!config || config->relays.empty()) {
678 // No relay ports specified in this config.
679 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
680 }
681
682 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000683 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684 // Skip IPv6 networks unless the flag's been set.
685 continue;
686 }
687
zhihuangb09b3f92017-03-07 14:40:51 -0800688 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
689 networks[i]->GetBestIP().family() == AF_INET6 &&
690 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
691 // Skip IPv6 Wi-Fi networks unless the flag's been set.
692 continue;
693 }
694
Steve Anton300bf8e2017-07-14 10:13:10 -0700695 if (disable_equivalent) {
696 // Disable phases that would only create ports equivalent to
697 // ones that we have already made.
698 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000699
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
701 // New AllocationSequence would have nothing to do, so don't make it.
702 continue;
703 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704 }
705
706 AllocationSequence* sequence =
707 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708 sequence->SignalPortAllocationComplete.connect(
709 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700710 sequence->Init();
711 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000712 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700713 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000714 }
715 }
716 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700717 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000718 }
719}
720
721void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700722 std::vector<rtc::Network*> networks = GetNetworks();
723 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700724 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700725 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700726 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700727 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700728 std::find(networks.begin(), networks.end(), sequence->network()) ==
729 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700730 sequence->OnNetworkFailed();
731 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700732 }
733 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700734 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
735 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100736 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
737 << " ports because their networks were gone";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700738 PrunePortsAndRemoveCandidates(ports_to_prune);
739 }
honghaiz8c404fa2015-09-28 07:59:43 -0700740
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700741 if (allocation_started_ && !IsStopped()) {
742 if (network_manager_started_) {
743 // If the network manager has started, it must be regathering.
744 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
745 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700746 bool disable_equivalent_phases = true;
747 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700748 }
749
Honghai Zhang5048f572016-08-23 15:47:33 -0700750 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100751 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700752 network_manager_started_ = true;
753 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000754}
755
756void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200757 rtc::Network* network,
758 PortConfiguration* config,
759 uint32_t* flags) {
760 for (uint32_t i = 0; i < sequences_.size() &&
761 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
762 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000763 sequences_[i]->DisableEquivalentPhases(network, config, flags);
764 }
765}
766
767void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
768 AllocationSequence * seq,
769 bool prepare_address) {
770 if (!port)
771 return;
772
Mirko Bonadei675513b2017-11-09 11:09:25 +0100773 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700775 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000776 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700777 if (allocator_->proxy().type != rtc::PROXY_NONE)
778 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700779 port->set_send_retransmit_count_attribute(
780 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000781
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782 PortData data(port, seq);
783 ports_.push_back(data);
784
785 port->SignalCandidateReady.connect(
786 this, &BasicPortAllocatorSession::OnCandidateReady);
787 port->SignalPortComplete.connect(this,
788 &BasicPortAllocatorSession::OnPortComplete);
789 port->SignalDestroyed.connect(this,
790 &BasicPortAllocatorSession::OnPortDestroyed);
791 port->SignalPortError.connect(
792 this, &BasicPortAllocatorSession::OnPortError);
793 LOG_J(LS_INFO, port) << "Added port to allocator";
794
795 if (prepare_address)
796 port->PrepareAddress();
797}
798
799void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
800 allocation_sequences_created_ = true;
801 // Send candidate allocation complete signal if we have no sequences.
802 MaybeSignalCandidatesAllocationDone();
803}
804
805void BasicPortAllocatorSession::OnCandidateReady(
806 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800807 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000808 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800809 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700810 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000811 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700812 // already done with gathering.
813 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100814 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700815 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700816 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700817 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700818
danilchapf4e8cf02016-06-30 01:55:03 -0700819 // Mark that the port has a pairable candidate, either because we have a
820 // usable candidate from the port, or simply because the port is bound to the
821 // any address and therefore has no host candidate. This will trigger the port
822 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700823 // checks. If port has already been marked as having a pairable candidate,
824 // do nothing here.
825 // Note: We should check whether any candidates may become ready after this
826 // because there we will check whether the candidate is generated by the ready
827 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700828 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700829 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700830 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700831
832 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700833 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700834 }
835 // If the current port is not pruned yet, SignalPortReady.
836 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700837 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700838 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700839 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700840 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700841 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700842
deadbeef1c5e6d02017-09-15 17:46:56 -0700843 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700844 std::vector<Candidate> candidates;
845 candidates.push_back(SanitizeRelatedAddress(c));
846 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700847 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700849 }
850
851 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700852 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700853 MaybeSignalCandidatesAllocationDone();
854 }
855}
856
857Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
858 const std::string& network_name) const {
859 Port* best_turn_port = nullptr;
860 for (const PortData& data : ports_) {
861 if (data.port()->Network()->name() == network_name &&
862 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
863 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
864 best_turn_port = data.port();
865 }
866 }
867 return best_turn_port;
868}
869
870bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700871 // Note: We determine the same network based only on their network names. So
872 // if an IPv4 address and an IPv6 address have the same network name, they
873 // are considered the same network here.
874 const std::string& network_name = newly_pairable_turn_port->Network()->name();
875 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
876 // |port| is already in the list of ports, so the best port cannot be nullptr.
877 RTC_CHECK(best_turn_port != nullptr);
878
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700879 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700880 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700881 for (PortData& data : ports_) {
882 if (data.port()->Network()->name() == network_name &&
883 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
884 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700885 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700886 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700887 // These ports will be pruned in PrunePortsAndRemoveCandidates.
888 ports_to_prune.push_back(&data);
889 } else {
890 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700891 }
892 }
893 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700894
895 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
897 << " low-priority TURN ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700898 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700899 }
900 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901}
902
Honghai Zhanga74363c2016-07-28 18:06:15 -0700903void BasicPortAllocatorSession::PruneAllPorts() {
904 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700905 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700906 }
907}
908
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800910 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700911 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000912 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800913 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914
915 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700916 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700918 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000919
920 // Moving to COMPLETE state.
921 data->set_complete();
922 // Send candidate allocation complete signal if this was the last port.
923 MaybeSignalCandidatesAllocationDone();
924}
925
926void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800927 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700928 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800930 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000931 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700932 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700934 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000935
936 // SignalAddressError is currently sent from StunPort/TurnPort.
937 // But this signal itself is generic.
938 data->set_error();
939 // Send candidate allocation complete signal if this was the last port.
940 MaybeSignalCandidatesAllocationDone();
941}
942
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700943bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700944 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000945
946 // When binding to any address, before sending packets out, the getsockname
947 // returns all 0s, but after sending packets, it'll be the NIC used to
948 // send. All 0s is not a valid ICE candidate address and should be filtered
949 // out.
950 if (c.address().IsAnyIP()) {
951 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952 }
953
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000954 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000955 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000956 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000957 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000958 } else if (c.type() == LOCAL_PORT_TYPE) {
959 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
960 // We allow host candidates if the filter allows server-reflexive
961 // candidates and the candidate is a public IP. Because we don't generate
962 // server-reflexive candidates if they have the same IP as the host
963 // candidate (i.e. when the host candidate is a public IP), filtering to
964 // only server-reflexive candidates won't work right when the host
965 // candidates have public IPs.
966 return true;
967 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000968
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000969 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000970 }
971 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000972}
973
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700974bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
975 const Port* port) const {
976 bool candidate_signalable = CheckCandidateFilter(c);
977
978 // When device enumeration is disabled (to prevent non-default IP addresses
979 // from leaking), we ping from some local candidates even though we don't
980 // signal them. However, if host candidates are also disabled (for example, to
981 // prevent even default IP addresses from leaking), we still don't want to
982 // ping from them, even if device enumeration is disabled. Thus, we check for
983 // both device enumeration and host candidates being disabled.
984 bool network_enumeration_disabled = c.address().IsAnyIP();
985 bool can_ping_from_candidate =
986 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
987 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
988
989 return candidate_signalable ||
990 (network_enumeration_disabled && can_ping_from_candidate &&
991 !host_candidates_disabled);
992}
993
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000994void BasicPortAllocatorSession::OnPortAllocationComplete(
995 AllocationSequence* seq) {
996 // Send candidate allocation complete signal if all ports are done.
997 MaybeSignalCandidatesAllocationDone();
998}
999
1000void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001001 if (CandidatesAllocationDone()) {
1002 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001003 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001004 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001005 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1006 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001007 }
1008 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001010}
1011
1012void BasicPortAllocatorSession::OnPortDestroyed(
1013 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001014 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001015 for (std::vector<PortData>::iterator iter = ports_.begin();
1016 iter != ports_.end(); ++iter) {
1017 if (port == iter->port()) {
1018 ports_.erase(iter);
1019 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1020 << static_cast<int>(ports_.size()) << " remaining)";
1021 return;
1022 }
1023 }
nissec80e7412017-01-11 05:56:46 -08001024 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001025}
1026
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001027BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1028 Port* port) {
1029 for (std::vector<PortData>::iterator it = ports_.begin();
1030 it != ports_.end(); ++it) {
1031 if (it->port() == port) {
1032 return &*it;
1033 }
1034 }
1035 return NULL;
1036}
1037
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001038std::vector<BasicPortAllocatorSession::PortData*>
1039BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001040 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001041 std::vector<PortData*> unpruned_ports;
1042 for (PortData& port : ports_) {
1043 if (!port.pruned() &&
1044 std::find(networks.begin(), networks.end(),
1045 port.sequence()->network()) != networks.end()) {
1046 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001047 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001048 }
1049 return unpruned_ports;
1050}
1051
1052void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1053 const std::vector<PortData*>& port_data_list) {
1054 std::vector<PortInterface*> pruned_ports;
1055 std::vector<Candidate> removed_candidates;
1056 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001057 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001058 data->Prune();
1059 pruned_ports.push_back(data->port());
1060 if (data->has_pairable_candidate()) {
1061 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001062 // Mark the port as having no pairable candidates so that its candidates
1063 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001064 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001065 }
1066 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001067 if (!pruned_ports.empty()) {
1068 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001069 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001070 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001071 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1072 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001073 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001074 }
1075}
1076
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001077// AllocationSequence
1078
1079AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1080 rtc::Network* network,
1081 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001082 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001083 : session_(session),
1084 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001085 config_(config),
1086 state_(kInit),
1087 flags_(flags),
1088 udp_socket_(),
1089 udp_port_(NULL),
1090 phase_(0) {
1091}
1092
Honghai Zhang5048f572016-08-23 15:47:33 -07001093void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001094 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1095 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001096 rtc::SocketAddress(network_->GetBestIP(), 0),
1097 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001098 if (udp_socket_) {
1099 udp_socket_->SignalReadPacket.connect(
1100 this, &AllocationSequence::OnReadPacket);
1101 }
1102 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1103 // are next available options to setup a communication channel.
1104 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001105}
1106
1107void AllocationSequence::Clear() {
1108 udp_port_ = NULL;
1109 turn_ports_.clear();
1110}
1111
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001112void AllocationSequence::OnNetworkFailed() {
1113 RTC_DCHECK(!network_failed_);
1114 network_failed_ = true;
1115 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001116 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001117}
1118
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001119AllocationSequence::~AllocationSequence() {
1120 session_->network_thread()->Clear(this);
1121}
1122
1123void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001124 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001125 if (network_failed_) {
1126 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001127 // it won't be equivalent to the new network.
1128 return;
1129 }
1130
deadbeef5c3c1042017-08-04 15:01:57 -07001131 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132 // Different network setup; nothing is equivalent.
1133 return;
1134 }
1135
1136 // Else turn off the stuff that we've already got covered.
1137
deadbeef1c46a352017-09-27 11:24:05 -07001138 // Every config implicitly specifies local, so turn that off right away if we
1139 // already have a port of the corresponding type. Look for a port that
1140 // matches this AllocationSequence's network, is the right protocol, and
1141 // hasn't encountered an error.
1142 // TODO(deadbeef): This doesn't take into account that there may be another
1143 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1144 // This can happen if, say, there's a network change event right before an
1145 // application-triggered ICE restart. Hopefully this problem will just go
1146 // away if we get rid of the gathering "phases" though, which is planned.
1147 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1148 [this](const BasicPortAllocatorSession::PortData& p) {
1149 return p.port()->Network() == network_ &&
1150 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1151 })) {
1152 *flags |= PORTALLOCATOR_DISABLE_UDP;
1153 }
1154 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1155 [this](const BasicPortAllocatorSession::PortData& p) {
1156 return p.port()->Network() == network_ &&
1157 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1158 })) {
1159 *flags |= PORTALLOCATOR_DISABLE_TCP;
1160 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001161
1162 if (config_ && config) {
1163 if (config_->StunServers() == config->StunServers()) {
1164 // Already got this STUN servers covered.
1165 *flags |= PORTALLOCATOR_DISABLE_STUN;
1166 }
1167 if (!config_->relays.empty()) {
1168 // Already got relays covered.
1169 // NOTE: This will even skip a _different_ set of relay servers if we
1170 // were to be given one, but that never happens in our codebase. Should
1171 // probably get rid of the list in PortConfiguration and just keep a
1172 // single relay server in each one.
1173 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1174 }
1175 }
1176}
1177
1178void AllocationSequence::Start() {
1179 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001180 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001181 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1182 // called next time, we enable all phases if the best IP has since changed.
1183 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001184}
1185
1186void AllocationSequence::Stop() {
1187 // If the port is completed, don't set it to stopped.
1188 if (state_ == kRunning) {
1189 state_ = kStopped;
1190 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1191 }
1192}
1193
1194void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001195 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1196 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001197
deadbeef1c5e6d02017-09-15 17:46:56 -07001198 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001199
1200 // Perform all of the phases in the current step.
1201 LOG_J(LS_INFO, network_) << "Allocation Phase="
1202 << PHASE_NAMES[phase_];
1203
1204 switch (phase_) {
1205 case PHASE_UDP:
1206 CreateUDPPorts();
1207 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001208 break;
1209
1210 case PHASE_RELAY:
1211 CreateRelayPorts();
1212 break;
1213
1214 case PHASE_TCP:
1215 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001216 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217 break;
1218
1219 default:
nissec80e7412017-01-11 05:56:46 -08001220 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221 }
1222
1223 if (state() == kRunning) {
1224 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001225 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1226 session_->allocator()->step_delay(),
1227 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228 } else {
1229 // If all phases in AllocationSequence are completed, no allocation
1230 // steps needed further. Canceling pending signal.
1231 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1232 SignalPortAllocationComplete(this);
1233 }
1234}
1235
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001236void AllocationSequence::CreateUDPPorts() {
1237 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001238 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001239 return;
1240 }
1241
1242 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1243 // is enabled completely.
1244 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001245 bool emit_local_candidate_for_anyaddress =
1246 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001247 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001248 port = UDPPort::Create(
1249 session_->network_thread(), session_->socket_factory(), network_,
1250 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001251 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001252 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001253 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001254 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001255 session_->allocator()->min_port(), session_->allocator()->max_port(),
1256 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001257 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001258 }
1259
1260 if (port) {
1261 // If shared socket is enabled, STUN candidate will be allocated by the
1262 // UDPPort.
1263 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1264 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001265 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266
1267 // If STUN is not disabled, setting stun server address to port.
1268 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001269 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001270 RTC_LOG(LS_INFO)
1271 << "AllocationSequence: UDPPort will be handling the "
1272 << "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001274 }
1275 }
1276 }
1277
1278 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001279 }
1280}
1281
1282void AllocationSequence::CreateTCPPorts() {
1283 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001284 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001285 return;
1286 }
1287
deadbeef5c3c1042017-08-04 15:01:57 -07001288 Port* port = TCPPort::Create(
1289 session_->network_thread(), session_->socket_factory(), network_,
1290 session_->allocator()->min_port(), session_->allocator()->max_port(),
1291 session_->username(), session_->password(),
1292 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001293 if (port) {
1294 session_->AddAllocatedPort(port, this, true);
1295 // Since TCPPort is not created using shared socket, |port| will not be
1296 // added to the dequeue.
1297 }
1298}
1299
1300void AllocationSequence::CreateStunPorts() {
1301 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001302 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001303 return;
1304 }
1305
1306 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1307 return;
1308 }
1309
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001311 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001312 << "AllocationSequence: No STUN server configured, skipping.";
1313 return;
1314 }
1315
deadbeef5c3c1042017-08-04 15:01:57 -07001316 StunPort* port = StunPort::Create(
1317 session_->network_thread(), session_->socket_factory(), network_,
1318 session_->allocator()->min_port(), session_->allocator()->max_port(),
1319 session_->username(), session_->password(), config_->StunServers(),
1320 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001321 if (port) {
1322 session_->AddAllocatedPort(port, this, true);
1323 // Since StunPort is not created using shared socket, |port| will not be
1324 // added to the dequeue.
1325 }
1326}
1327
1328void AllocationSequence::CreateRelayPorts() {
1329 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001330 RTC_LOG(LS_VERBOSE)
1331 << "AllocationSequence: Relay ports disabled, skipping.";
1332 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333 }
1334
1335 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1336 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001337 RTC_DCHECK(config_);
1338 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001339 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001340 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001341 << "AllocationSequence: No relay server configured, skipping.";
1342 return;
1343 }
1344
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001345 for (RelayServerConfig& relay : config_->relays) {
1346 if (relay.type == RELAY_GTURN) {
1347 CreateGturnPort(relay);
1348 } else if (relay.type == RELAY_TURN) {
1349 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350 } else {
nissec80e7412017-01-11 05:56:46 -08001351 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001352 }
1353 }
1354}
1355
1356void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1357 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001358 RelayPort* port = RelayPort::Create(
1359 session_->network_thread(), session_->socket_factory(), network_,
1360 session_->allocator()->min_port(), session_->allocator()->max_port(),
1361 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001362 if (port) {
1363 // Since RelayPort is not created using shared socket, |port| will not be
1364 // added to the dequeue.
1365 // Note: We must add the allocated port before we add addresses because
1366 // the latter will create candidates that need name and preference
1367 // settings. However, we also can't prepare the address (normally
1368 // done by AddAllocatedPort) until we have these addresses. So we
1369 // wait to do that until below.
1370 session_->AddAllocatedPort(port, this, false);
1371
1372 // Add the addresses of this protocol.
1373 PortList::const_iterator relay_port;
1374 for (relay_port = config.ports.begin();
1375 relay_port != config.ports.end();
1376 ++relay_port) {
1377 port->AddServerAddress(*relay_port);
1378 port->AddExternalAddress(*relay_port);
1379 }
1380 // Start fetching an address for this port.
1381 port->PrepareAddress();
1382 }
1383}
1384
1385void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1386 PortList::const_iterator relay_port;
1387 for (relay_port = config.ports.begin();
1388 relay_port != config.ports.end(); ++relay_port) {
1389 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001390
1391 // Skip UDP connections to relay servers if it's disallowed.
1392 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1393 relay_port->proto == PROTO_UDP) {
1394 continue;
1395 }
1396
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001397 // Do not create a port if the server address family is known and does
1398 // not match the local IP address family.
1399 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001400 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001401 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001402 RTC_LOG(LS_INFO)
1403 << "Server and local address families are not compatible. "
1404 << "Server address: " << relay_port->address.ipaddr().ToString()
1405 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001406 continue;
1407 }
1408
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001409 // Shared socket mode must be enabled only for UDP based ports. Hence
1410 // don't pass shared socket for ports which will create TCP sockets.
1411 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1412 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1413 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001414 relay_port->proto == PROTO_UDP && udp_socket_) {
maxmorine9ef9072017-08-29 04:49:00 -07001415 port = TurnPort::Create(session_->network_thread(),
1416 session_->socket_factory(),
1417 network_, udp_socket_.get(),
1418 session_->username(), session_->password(),
1419 *relay_port, config.credentials, config.priority,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001420 session_->allocator()->origin(),
1421 session_->allocator()->turn_customizer());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 turn_ports_.push_back(port);
1423 // Listen to the port destroyed signal, to allow AllocationSequence to
1424 // remove entrt from it's map.
1425 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1426 } else {
deadbeef5c3c1042017-08-04 15:01:57 -07001427 port = TurnPort::Create(
1428 session_->network_thread(), session_->socket_factory(), network_,
1429 session_->allocator()->min_port(), session_->allocator()->max_port(),
1430 session_->username(), session_->password(), *relay_port,
Diogo Real1dca9d52017-08-29 12:18:32 -07001431 config.credentials, config.priority, session_->allocator()->origin(),
Jonas Orelandbdcee282017-10-10 14:01:40 +02001432 config.tls_alpn_protocols, config.tls_elliptic_curves,
1433 session_->allocator()->turn_customizer());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001434 }
nisseede5da42017-01-12 05:15:36 -08001435 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001436 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001437 session_->AddAllocatedPort(port, this, true);
1438 }
1439}
1440
1441void AllocationSequence::OnReadPacket(
1442 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1443 const rtc::SocketAddress& remote_addr,
1444 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001445 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001446
1447 bool turn_port_found = false;
1448
1449 // Try to find the TurnPort that matches the remote address. Note that the
1450 // message could be a STUN binding response if the TURN server is also used as
1451 // a STUN server. We don't want to parse every message here to check if it is
1452 // a STUN binding response, so we pass the message to TurnPort regardless of
1453 // the message type. The TurnPort will just ignore the message since it will
1454 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001455 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001456 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001457 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1458 packet_time)) {
1459 return;
1460 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001461 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462 }
1463 }
1464
1465 if (udp_port_) {
1466 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1467
1468 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1469 // the TURN server is also a STUN server.
1470 if (!turn_port_found ||
1471 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001472 RTC_DCHECK(udp_port_->SharedSocket());
1473 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1474 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001475 }
1476 }
1477}
1478
1479void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1480 if (udp_port_ == port) {
1481 udp_port_ = NULL;
1482 return;
1483 }
1484
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001485 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1486 if (it != turn_ports_.end()) {
1487 turn_ports_.erase(it);
1488 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001489 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001490 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001491 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492}
1493
1494// PortConfiguration
1495PortConfiguration::PortConfiguration(
1496 const rtc::SocketAddress& stun_address,
1497 const std::string& username,
1498 const std::string& password)
1499 : stun_address(stun_address), username(username), password(password) {
1500 if (!stun_address.IsNil())
1501 stun_servers.insert(stun_address);
1502}
1503
1504PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1505 const std::string& username,
1506 const std::string& password)
1507 : stun_servers(stun_servers),
1508 username(username),
1509 password(password) {
1510 if (!stun_servers.empty())
1511 stun_address = *(stun_servers.begin());
1512}
1513
Steve Anton7995d8c2017-10-30 16:23:38 -07001514PortConfiguration::~PortConfiguration() = default;
1515
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001516ServerAddresses PortConfiguration::StunServers() {
1517 if (!stun_address.IsNil() &&
1518 stun_servers.find(stun_address) == stun_servers.end()) {
1519 stun_servers.insert(stun_address);
1520 }
deadbeefc5d0d952015-07-16 10:22:21 -07001521 // Every UDP TURN server should also be used as a STUN server.
1522 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1523 for (const rtc::SocketAddress& turn_server : turn_servers) {
1524 if (stun_servers.find(turn_server) == stun_servers.end()) {
1525 stun_servers.insert(turn_server);
1526 }
1527 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001528 return stun_servers;
1529}
1530
1531void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1532 relays.push_back(config);
1533}
1534
1535bool PortConfiguration::SupportsProtocol(
1536 const RelayServerConfig& relay, ProtocolType type) const {
1537 PortList::const_iterator relay_port;
1538 for (relay_port = relay.ports.begin();
1539 relay_port != relay.ports.end();
1540 ++relay_port) {
1541 if (relay_port->proto == type)
1542 return true;
1543 }
1544 return false;
1545}
1546
1547bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1548 ProtocolType type) const {
1549 for (size_t i = 0; i < relays.size(); ++i) {
1550 if (relays[i].type == turn_type &&
1551 SupportsProtocol(relays[i], type))
1552 return true;
1553 }
1554 return false;
1555}
1556
1557ServerAddresses PortConfiguration::GetRelayServerAddresses(
1558 RelayType turn_type, ProtocolType type) const {
1559 ServerAddresses servers;
1560 for (size_t i = 0; i < relays.size(); ++i) {
1561 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1562 servers.insert(relays[i].ports.front().address);
1563 }
1564 }
1565 return servers;
1566}
1567
1568} // namespace cricket