blob: 471748400d1dec9528b2cc85696123df2673c827 [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 Orelandb23ed7f2017-10-09 08:01:47 +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 Orelandb23ed7f2017-10-09 08:01:47 +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 Orelandb23ed7f2017-10-09 08:01:47 +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 Orelandb23ed7f2017-10-09 08:01:47 +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
deadbeefc5d0d952015-07-16 10:22:21 -0700182PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183 const std::string& content_name, int component,
184 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700185 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000186 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700187 session->SignalIceRegathering.connect(this,
188 &BasicPortAllocator::OnIceRegathering);
189 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190}
191
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700192void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
193 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
194 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700195 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandb23ed7f2017-10-09 08:01:47 +0200196 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700197}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198
199// BasicPortAllocatorSession
200BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700201 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000202 const std::string& content_name,
203 int component,
204 const std::string& ice_ufrag,
205 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700206 : PortAllocatorSession(content_name,
207 component,
208 ice_ufrag,
209 ice_pwd,
210 allocator->flags()),
211 allocator_(allocator),
212 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 socket_factory_(allocator->socket_factory()),
214 allocation_started_(false),
215 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700216 allocation_sequences_created_(false),
217 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218 allocator_->network_manager()->SignalNetworksChanged.connect(
219 this, &BasicPortAllocatorSession::OnNetworksChanged);
220 allocator_->network_manager()->StartUpdating();
221}
222
223BasicPortAllocatorSession::~BasicPortAllocatorSession() {
224 allocator_->network_manager()->StopUpdating();
225 if (network_thread_ != NULL)
226 network_thread_->Clear(this);
227
Peter Boström0c4e06b2015-10-07 12:23:21 +0200228 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229 // AllocationSequence should clear it's map entry for turn ports before
230 // ports are destroyed.
231 sequences_[i]->Clear();
232 }
233
234 std::vector<PortData>::iterator it;
235 for (it = ports_.begin(); it != ports_.end(); it++)
236 delete it->port();
237
Peter Boström0c4e06b2015-10-07 12:23:21 +0200238 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239 delete configs_[i];
240
Peter Boström0c4e06b2015-10-07 12:23:21 +0200241 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242 delete sequences_[i];
243}
244
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700245void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
246 if (filter == candidate_filter_) {
247 return;
248 }
249 // We assume the filter will only change from "ALL" to something else.
250 RTC_DCHECK(candidate_filter_ == CF_ALL);
251 candidate_filter_ = filter;
252 for (PortData& port : ports_) {
253 if (!port.has_pairable_candidate()) {
254 continue;
255 }
256 const auto& candidates = port.port()->Candidates();
257 // Setting a filter may cause a ready port to become non-ready
258 // if it no longer has any pairable candidates.
259 if (!std::any_of(candidates.begin(), candidates.end(),
260 [this, &port](const Candidate& candidate) {
261 return CandidatePairable(candidate, port.port());
262 })) {
263 port.set_has_pairable_candidate(false);
264 }
265 }
266}
267
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268void BasicPortAllocatorSession::StartGettingPorts() {
269 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700270 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000271 if (!socket_factory_) {
272 owned_socket_factory_.reset(
273 new rtc::BasicPacketSocketFactory(network_thread_));
274 socket_factory_ = owned_socket_factory_.get();
275 }
276
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700277 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700278
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700279 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700280 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000281}
282
283void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800284 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700285 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700286 // Note: this must be called after ClearGettingPorts because both may set the
287 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700288 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700289}
290
291void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800292 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700294 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700296 }
deadbeefb60a8192016-08-24 15:15:00 -0700297 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700298 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700299}
300
301std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
302 std::vector<rtc::Network*> networks = GetNetworks();
303
304 // A network interface may have both IPv4 and IPv6 networks. Only if
305 // neither of the networks has any connections, the network interface
306 // is considered failed and need to be regathered on.
307 std::set<std::string> networks_with_connection;
308 for (const PortData& data : ports_) {
309 Port* port = data.port();
310 if (!port->connections().empty()) {
311 networks_with_connection.insert(port->Network()->name());
312 }
313 }
314
315 networks.erase(
316 std::remove_if(networks.begin(), networks.end(),
317 [networks_with_connection](rtc::Network* network) {
318 // If a network does not have any connection, it is
319 // considered failed.
320 return networks_with_connection.find(network->name()) !=
321 networks_with_connection.end();
322 }),
323 networks.end());
324 return networks;
325}
326
327void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
328 // Find the list of networks that have no connection.
329 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
330 if (failed_networks.empty()) {
331 return;
332 }
333
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700334 LOG(LS_INFO) << "Regather candidates on failed networks";
335
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700336 // Mark a sequence as "network failed" if its network is in the list of failed
337 // networks, so that it won't be considered as equivalent when the session
338 // regathers ports and candidates.
339 for (AllocationSequence* sequence : sequences_) {
340 if (!sequence->network_failed() &&
341 std::find(failed_networks.begin(), failed_networks.end(),
342 sequence->network()) != failed_networks.end()) {
343 sequence->set_network_failed();
344 }
345 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700346
347 bool disable_equivalent_phases = true;
348 Regather(failed_networks, disable_equivalent_phases,
349 IceRegatheringReason::NETWORK_FAILURE);
350}
351
352void BasicPortAllocatorSession::RegatherOnAllNetworks() {
353 std::vector<rtc::Network*> networks = GetNetworks();
354 if (networks.empty()) {
355 return;
356 }
357
358 LOG(LS_INFO) << "Regather candidates on all networks";
359
360 // We expect to generate candidates that are equivalent to what we have now.
361 // Force DoAllocate to generate them instead of skipping.
362 bool disable_equivalent_phases = false;
363 Regather(networks, disable_equivalent_phases,
364 IceRegatheringReason::OCCASIONAL_REFRESH);
365}
366
367void BasicPortAllocatorSession::Regather(
368 const std::vector<rtc::Network*>& networks,
369 bool disable_equivalent_phases,
370 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700371 // Remove ports from being used locally and send signaling to remove
372 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700373 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700374 if (!ports_to_prune.empty()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700375 LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700376 PrunePortsAndRemoveCandidates(ports_to_prune);
377 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700378
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700379 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700380 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700381
Steve Anton300bf8e2017-07-14 10:13:10 -0700382 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700383 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000384}
385
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700386std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
387 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700388 for (const PortData& data : ports_) {
389 if (data.ready()) {
390 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700391 }
392 }
393 return ret;
394}
395
396std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
397 std::vector<Candidate> candidates;
398 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700399 if (!data.ready()) {
400 continue;
401 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700402 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700403 }
404 return candidates;
405}
406
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700407void BasicPortAllocatorSession::GetCandidatesFromPort(
408 const PortData& data,
409 std::vector<Candidate>* candidates) const {
410 RTC_CHECK(candidates != nullptr);
411 for (const Candidate& candidate : data.port()->Candidates()) {
412 if (!CheckCandidateFilter(candidate)) {
413 continue;
414 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700415 candidates->push_back(SanitizeRelatedAddress(candidate));
416 }
417}
418
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700419Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
420 const Candidate& c) const {
421 Candidate copy = c;
422 // If adapter enumeration is disabled or host candidates are disabled,
423 // clear the raddr of STUN candidates to avoid local address leakage.
424 bool filter_stun_related_address =
425 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
426 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
427 !(candidate_filter_ & CF_HOST);
428 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
429 // to avoid reflexive address leakage.
430 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
431 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
432 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
433 copy.set_related_address(
434 rtc::EmptySocketAddressWithFamily(copy.address().family()));
435 }
436 return copy;
437}
438
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700439bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
440 // Done only if all required AllocationSequence objects
441 // are created.
442 if (!allocation_sequences_created_) {
443 return false;
444 }
445
446 // Check that all port allocation sequences are complete (not running).
447 if (std::any_of(sequences_.begin(), sequences_.end(),
448 [](const AllocationSequence* sequence) {
449 return sequence->state() == AllocationSequence::kRunning;
450 })) {
451 return false;
452 }
453
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700454 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700455 // expected candidates. Session will trigger candidates allocation complete
456 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700457 return std::none_of(ports_.begin(), ports_.end(),
458 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700459}
460
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
462 switch (message->message_id) {
463 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800464 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465 GetPortConfigurations();
466 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000467 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800468 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
470 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800472 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000473 OnAllocate();
474 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800476 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 OnAllocationSequenceObjectsCreated();
478 break;
479 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800480 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000481 OnConfigStop();
482 break;
483 default:
nissec80e7412017-01-11 05:56:46 -0800484 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000485 }
486}
487
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700488void BasicPortAllocatorSession::UpdateIceParametersInternal() {
489 for (PortData& port : ports_) {
490 port.port()->set_content_name(content_name());
491 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
492 }
493}
494
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000495void BasicPortAllocatorSession::GetPortConfigurations() {
496 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
497 username(),
498 password());
499
deadbeef653b8e02015-11-11 12:55:10 -0800500 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
501 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000502 }
503 ConfigReady(config);
504}
505
506void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700507 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508}
509
510// Adds a configuration to the list.
511void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800512 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000513 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800514 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000515
516 AllocatePorts();
517}
518
519void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800520 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000521
522 // If any of the allocated ports have not completed the candidates allocation,
523 // mark those as error. Since session doesn't need any new candidates
524 // at this stage of the allocation, it's safe to discard any new candidates.
525 bool send_signal = false;
526 for (std::vector<PortData>::iterator it = ports_.begin();
527 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700528 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000529 // Updating port state to error, which didn't finish allocating candidates
530 // yet.
531 it->set_error();
532 send_signal = true;
533 }
534 }
535
536 // Did we stop any running sequences?
537 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
538 it != sequences_.end() && !send_signal; ++it) {
539 if ((*it)->state() == AllocationSequence::kStopped) {
540 send_signal = true;
541 }
542 }
543
544 // If we stopped anything that was running, send a done signal now.
545 if (send_signal) {
546 MaybeSignalCandidatesAllocationDone();
547 }
548}
549
550void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800551 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700552 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000553}
554
555void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700556 if (network_manager_started_ && !IsStopped()) {
557 bool disable_equivalent_phases = true;
558 DoAllocate(disable_equivalent_phases);
559 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560
561 allocation_started_ = true;
562}
563
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700564std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
565 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700566 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800567 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700568 // If the network permission state is BLOCKED, we just act as if the flag has
569 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700570 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700571 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700572 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
573 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000574 // If the adapter enumeration is disabled, we'll just bind to any address
575 // instead of specific NIC. This is to ensure the same routing for http
576 // traffic by OS is also used here to avoid any local or public IP leakage
577 // during stun process.
578 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700579 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000580 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700581 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800582 // If network enumeration fails, use the ANY address as a fallback, so we
583 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700584 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
585 // set, we'll use ANY address candidates either way.
586 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800587 network_manager->GetAnyAddressNetworks(&networks);
588 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000589 }
deadbeef3427f532017-07-26 16:09:33 -0700590 // Do some more filtering, depending on the network ignore mask and "disable
591 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700592 networks.erase(std::remove_if(networks.begin(), networks.end(),
593 [this](rtc::Network* network) {
594 return allocator_->network_ignore_mask() &
595 network->type();
596 }),
597 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700598 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
599 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700600 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700601 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
602 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700603 networks.erase(std::remove_if(networks.begin(), networks.end(),
604 [lowest_cost](rtc::Network* network) {
605 return network->GetCost() >
606 lowest_cost + rtc::kNetworkCostLow;
607 }),
608 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700609 }
deadbeef3427f532017-07-26 16:09:33 -0700610 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
611 // default, it's 5), remove networks to ensure that limit is satisfied.
612 //
613 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
614 // networks, we could try to choose a set that's "most likely to work". It's
615 // hard to define what that means though; it's not just "lowest cost".
616 // Alternatively, we could just focus on making our ICE pinging logic smarter
617 // such that this filtering isn't necessary in the first place.
618 int ipv6_networks = 0;
619 for (auto it = networks.begin(); it != networks.end();) {
620 if ((*it)->prefix().family() == AF_INET6) {
621 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
622 it = networks.erase(it);
623 continue;
624 } else {
625 ++ipv6_networks;
626 }
627 }
628 ++it;
629 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700630 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700631}
632
633// For each network, see if we have a sequence that covers it already. If not,
634// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700635void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700636 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700637 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000638 if (networks.empty()) {
639 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
640 done_signal_needed = true;
641 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700642 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700643 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200644 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200645 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
647 // If all the ports are disabled we should just fire the allocation
648 // done event and return.
649 done_signal_needed = true;
650 break;
651 }
652
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653 if (!config || config->relays.empty()) {
654 // No relay ports specified in this config.
655 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
656 }
657
658 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000659 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 // Skip IPv6 networks unless the flag's been set.
661 continue;
662 }
663
zhihuangb09b3f92017-03-07 14:40:51 -0800664 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
665 networks[i]->GetBestIP().family() == AF_INET6 &&
666 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
667 // Skip IPv6 Wi-Fi networks unless the flag's been set.
668 continue;
669 }
670
Steve Anton300bf8e2017-07-14 10:13:10 -0700671 if (disable_equivalent) {
672 // Disable phases that would only create ports equivalent to
673 // ones that we have already made.
674 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000675
Steve Anton300bf8e2017-07-14 10:13:10 -0700676 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
677 // New AllocationSequence would have nothing to do, so don't make it.
678 continue;
679 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680 }
681
682 AllocationSequence* sequence =
683 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684 sequence->SignalPortAllocationComplete.connect(
685 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700686 sequence->Init();
687 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000688 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700689 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690 }
691 }
692 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700693 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000694 }
695}
696
697void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700698 std::vector<rtc::Network*> networks = GetNetworks();
699 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700700 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700701 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700702 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700703 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700704 std::find(networks.begin(), networks.end(), sequence->network()) ==
705 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700706 sequence->OnNetworkFailed();
707 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700708 }
709 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700710 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
711 if (!ports_to_prune.empty()) {
712 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
713 << " ports because their networks were gone";
714 PrunePortsAndRemoveCandidates(ports_to_prune);
715 }
honghaiz8c404fa2015-09-28 07:59:43 -0700716
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700717 if (allocation_started_ && !IsStopped()) {
718 if (network_manager_started_) {
719 // If the network manager has started, it must be regathering.
720 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
721 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700722 bool disable_equivalent_phases = true;
723 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700724 }
725
Honghai Zhang5048f572016-08-23 15:47:33 -0700726 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700727 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700728 network_manager_started_ = true;
729 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000730}
731
732void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200733 rtc::Network* network,
734 PortConfiguration* config,
735 uint32_t* flags) {
736 for (uint32_t i = 0; i < sequences_.size() &&
737 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
738 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000739 sequences_[i]->DisableEquivalentPhases(network, config, flags);
740 }
741}
742
743void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
744 AllocationSequence * seq,
745 bool prepare_address) {
746 if (!port)
747 return;
748
749 LOG(LS_INFO) << "Adding allocated port for " << content_name();
750 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700751 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700753 if (allocator_->proxy().type != rtc::PROXY_NONE)
754 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700755 port->set_send_retransmit_count_attribute(
756 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758 PortData data(port, seq);
759 ports_.push_back(data);
760
761 port->SignalCandidateReady.connect(
762 this, &BasicPortAllocatorSession::OnCandidateReady);
763 port->SignalPortComplete.connect(this,
764 &BasicPortAllocatorSession::OnPortComplete);
765 port->SignalDestroyed.connect(this,
766 &BasicPortAllocatorSession::OnPortDestroyed);
767 port->SignalPortError.connect(
768 this, &BasicPortAllocatorSession::OnPortError);
769 LOG_J(LS_INFO, port) << "Added port to allocator";
770
771 if (prepare_address)
772 port->PrepareAddress();
773}
774
775void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
776 allocation_sequences_created_ = true;
777 // Send candidate allocation complete signal if we have no sequences.
778 MaybeSignalCandidatesAllocationDone();
779}
780
781void BasicPortAllocatorSession::OnCandidateReady(
782 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800783 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000784 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800785 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700786 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000787 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700788 // already done with gathering.
789 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700790 LOG(LS_WARNING)
791 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700792 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700793 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700794
danilchapf4e8cf02016-06-30 01:55:03 -0700795 // Mark that the port has a pairable candidate, either because we have a
796 // usable candidate from the port, or simply because the port is bound to the
797 // any address and therefore has no host candidate. This will trigger the port
798 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700799 // checks. If port has already been marked as having a pairable candidate,
800 // do nothing here.
801 // Note: We should check whether any candidates may become ready after this
802 // because there we will check whether the candidate is generated by the ready
803 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700804 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700805 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700806 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700807
808 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700809 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700810 }
811 // If the current port is not pruned yet, SignalPortReady.
812 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700813 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700814 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700815 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700816 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700817 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700818
deadbeef1c5e6d02017-09-15 17:46:56 -0700819 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700820 std::vector<Candidate> candidates;
821 candidates.push_back(SanitizeRelatedAddress(c));
822 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700823 } else {
824 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700825 }
826
827 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700828 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700829 MaybeSignalCandidatesAllocationDone();
830 }
831}
832
833Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
834 const std::string& network_name) const {
835 Port* best_turn_port = nullptr;
836 for (const PortData& data : ports_) {
837 if (data.port()->Network()->name() == network_name &&
838 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
839 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
840 best_turn_port = data.port();
841 }
842 }
843 return best_turn_port;
844}
845
846bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700847 // Note: We determine the same network based only on their network names. So
848 // if an IPv4 address and an IPv6 address have the same network name, they
849 // are considered the same network here.
850 const std::string& network_name = newly_pairable_turn_port->Network()->name();
851 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
852 // |port| is already in the list of ports, so the best port cannot be nullptr.
853 RTC_CHECK(best_turn_port != nullptr);
854
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700855 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700856 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700857 for (PortData& data : ports_) {
858 if (data.port()->Network()->name() == network_name &&
859 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
860 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700861 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700862 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700863 // These ports will be pruned in PrunePortsAndRemoveCandidates.
864 ports_to_prune.push_back(&data);
865 } else {
866 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700867 }
868 }
869 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700870
871 if (!ports_to_prune.empty()) {
872 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
873 << " low-priority TURN ports";
874 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700875 }
876 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000877}
878
Honghai Zhanga74363c2016-07-28 18:06:15 -0700879void BasicPortAllocatorSession::PruneAllPorts() {
880 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700881 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700882 }
883}
884
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800886 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700887 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800889 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000890
891 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700892 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700894 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895
896 // Moving to COMPLETE state.
897 data->set_complete();
898 // Send candidate allocation complete signal if this was the last port.
899 MaybeSignalCandidatesAllocationDone();
900}
901
902void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800903 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700904 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800906 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000907 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700908 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700910 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000911
912 // SignalAddressError is currently sent from StunPort/TurnPort.
913 // But this signal itself is generic.
914 data->set_error();
915 // Send candidate allocation complete signal if this was the last port.
916 MaybeSignalCandidatesAllocationDone();
917}
918
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700919bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700920 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000921
922 // When binding to any address, before sending packets out, the getsockname
923 // returns all 0s, but after sending packets, it'll be the NIC used to
924 // send. All 0s is not a valid ICE candidate address and should be filtered
925 // out.
926 if (c.address().IsAnyIP()) {
927 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000928 }
929
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000930 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000931 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000932 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000933 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000934 } else if (c.type() == LOCAL_PORT_TYPE) {
935 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
936 // We allow host candidates if the filter allows server-reflexive
937 // candidates and the candidate is a public IP. Because we don't generate
938 // server-reflexive candidates if they have the same IP as the host
939 // candidate (i.e. when the host candidate is a public IP), filtering to
940 // only server-reflexive candidates won't work right when the host
941 // candidates have public IPs.
942 return true;
943 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000944
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000945 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000946 }
947 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000948}
949
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700950bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
951 const Port* port) const {
952 bool candidate_signalable = CheckCandidateFilter(c);
953
954 // When device enumeration is disabled (to prevent non-default IP addresses
955 // from leaking), we ping from some local candidates even though we don't
956 // signal them. However, if host candidates are also disabled (for example, to
957 // prevent even default IP addresses from leaking), we still don't want to
958 // ping from them, even if device enumeration is disabled. Thus, we check for
959 // both device enumeration and host candidates being disabled.
960 bool network_enumeration_disabled = c.address().IsAnyIP();
961 bool can_ping_from_candidate =
962 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
963 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
964
965 return candidate_signalable ||
966 (network_enumeration_disabled && can_ping_from_candidate &&
967 !host_candidates_disabled);
968}
969
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970void BasicPortAllocatorSession::OnPortAllocationComplete(
971 AllocationSequence* seq) {
972 // Send candidate allocation complete signal if all ports are done.
973 MaybeSignalCandidatesAllocationDone();
974}
975
976void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700977 if (CandidatesAllocationDone()) {
978 if (pooled()) {
979 LOG(LS_INFO) << "All candidates gathered for pooled session.";
980 } else {
981 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
982 << component() << ":" << generation();
983 }
984 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000985 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986}
987
988void BasicPortAllocatorSession::OnPortDestroyed(
989 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800990 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000991 for (std::vector<PortData>::iterator iter = ports_.begin();
992 iter != ports_.end(); ++iter) {
993 if (port == iter->port()) {
994 ports_.erase(iter);
995 LOG_J(LS_INFO, port) << "Removed port from allocator ("
996 << static_cast<int>(ports_.size()) << " remaining)";
997 return;
998 }
999 }
nissec80e7412017-01-11 05:56:46 -08001000 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001001}
1002
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001003BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1004 Port* port) {
1005 for (std::vector<PortData>::iterator it = ports_.begin();
1006 it != ports_.end(); ++it) {
1007 if (it->port() == port) {
1008 return &*it;
1009 }
1010 }
1011 return NULL;
1012}
1013
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001014std::vector<BasicPortAllocatorSession::PortData*>
1015BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001016 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001017 std::vector<PortData*> unpruned_ports;
1018 for (PortData& port : ports_) {
1019 if (!port.pruned() &&
1020 std::find(networks.begin(), networks.end(),
1021 port.sequence()->network()) != networks.end()) {
1022 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001023 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001024 }
1025 return unpruned_ports;
1026}
1027
1028void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1029 const std::vector<PortData*>& port_data_list) {
1030 std::vector<PortInterface*> pruned_ports;
1031 std::vector<Candidate> removed_candidates;
1032 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001033 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001034 data->Prune();
1035 pruned_ports.push_back(data->port());
1036 if (data->has_pairable_candidate()) {
1037 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001038 // Mark the port as having no pairable candidates so that its candidates
1039 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001040 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001041 }
1042 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001043 if (!pruned_ports.empty()) {
1044 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001045 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001046 if (!removed_candidates.empty()) {
1047 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1048 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001049 }
1050}
1051
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001052// AllocationSequence
1053
1054AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1055 rtc::Network* network,
1056 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001057 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001058 : session_(session),
1059 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001060 config_(config),
1061 state_(kInit),
1062 flags_(flags),
1063 udp_socket_(),
1064 udp_port_(NULL),
1065 phase_(0) {
1066}
1067
Honghai Zhang5048f572016-08-23 15:47:33 -07001068void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001069 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1070 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001071 rtc::SocketAddress(network_->GetBestIP(), 0),
1072 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001073 if (udp_socket_) {
1074 udp_socket_->SignalReadPacket.connect(
1075 this, &AllocationSequence::OnReadPacket);
1076 }
1077 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1078 // are next available options to setup a communication channel.
1079 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080}
1081
1082void AllocationSequence::Clear() {
1083 udp_port_ = NULL;
1084 turn_ports_.clear();
1085}
1086
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001087void AllocationSequence::OnNetworkFailed() {
1088 RTC_DCHECK(!network_failed_);
1089 network_failed_ = true;
1090 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001091 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001092}
1093
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001094AllocationSequence::~AllocationSequence() {
1095 session_->network_thread()->Clear(this);
1096}
1097
1098void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001099 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001100 if (network_failed_) {
1101 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001102 // it won't be equivalent to the new network.
1103 return;
1104 }
1105
deadbeef5c3c1042017-08-04 15:01:57 -07001106 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001107 // Different network setup; nothing is equivalent.
1108 return;
1109 }
1110
1111 // Else turn off the stuff that we've already got covered.
1112
deadbeef1c46a352017-09-27 11:24:05 -07001113 // Every config implicitly specifies local, so turn that off right away if we
1114 // already have a port of the corresponding type. Look for a port that
1115 // matches this AllocationSequence's network, is the right protocol, and
1116 // hasn't encountered an error.
1117 // TODO(deadbeef): This doesn't take into account that there may be another
1118 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1119 // This can happen if, say, there's a network change event right before an
1120 // application-triggered ICE restart. Hopefully this problem will just go
1121 // away if we get rid of the gathering "phases" though, which is planned.
1122 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1123 [this](const BasicPortAllocatorSession::PortData& p) {
1124 return p.port()->Network() == network_ &&
1125 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1126 })) {
1127 *flags |= PORTALLOCATOR_DISABLE_UDP;
1128 }
1129 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1130 [this](const BasicPortAllocatorSession::PortData& p) {
1131 return p.port()->Network() == network_ &&
1132 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1133 })) {
1134 *flags |= PORTALLOCATOR_DISABLE_TCP;
1135 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001136
1137 if (config_ && config) {
1138 if (config_->StunServers() == config->StunServers()) {
1139 // Already got this STUN servers covered.
1140 *flags |= PORTALLOCATOR_DISABLE_STUN;
1141 }
1142 if (!config_->relays.empty()) {
1143 // Already got relays covered.
1144 // NOTE: This will even skip a _different_ set of relay servers if we
1145 // were to be given one, but that never happens in our codebase. Should
1146 // probably get rid of the list in PortConfiguration and just keep a
1147 // single relay server in each one.
1148 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1149 }
1150 }
1151}
1152
1153void AllocationSequence::Start() {
1154 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001155 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001156 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1157 // called next time, we enable all phases if the best IP has since changed.
1158 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001159}
1160
1161void AllocationSequence::Stop() {
1162 // If the port is completed, don't set it to stopped.
1163 if (state_ == kRunning) {
1164 state_ = kStopped;
1165 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1166 }
1167}
1168
1169void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001170 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1171 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001172
deadbeef1c5e6d02017-09-15 17:46:56 -07001173 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001174
1175 // Perform all of the phases in the current step.
1176 LOG_J(LS_INFO, network_) << "Allocation Phase="
1177 << PHASE_NAMES[phase_];
1178
1179 switch (phase_) {
1180 case PHASE_UDP:
1181 CreateUDPPorts();
1182 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001183 break;
1184
1185 case PHASE_RELAY:
1186 CreateRelayPorts();
1187 break;
1188
1189 case PHASE_TCP:
1190 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001192 break;
1193
1194 default:
nissec80e7412017-01-11 05:56:46 -08001195 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001196 }
1197
1198 if (state() == kRunning) {
1199 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001200 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1201 session_->allocator()->step_delay(),
1202 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001203 } else {
1204 // If all phases in AllocationSequence are completed, no allocation
1205 // steps needed further. Canceling pending signal.
1206 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1207 SignalPortAllocationComplete(this);
1208 }
1209}
1210
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001211void AllocationSequence::CreateUDPPorts() {
1212 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1213 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1214 return;
1215 }
1216
1217 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1218 // is enabled completely.
1219 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001220 bool emit_local_candidate_for_anyaddress =
1221 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001223 port = UDPPort::Create(
1224 session_->network_thread(), session_->socket_factory(), network_,
1225 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001226 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001227 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001228 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001229 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001230 session_->allocator()->min_port(), session_->allocator()->max_port(),
1231 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001232 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233 }
1234
1235 if (port) {
1236 // If shared socket is enabled, STUN candidate will be allocated by the
1237 // UDPPort.
1238 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1239 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001240 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001241
1242 // If STUN is not disabled, setting stun server address to port.
1243 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 if (config_ && !config_->StunServers().empty()) {
1245 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1246 << "STUN candidate generation.";
1247 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001248 }
1249 }
1250 }
1251
1252 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253 }
1254}
1255
1256void AllocationSequence::CreateTCPPorts() {
1257 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1258 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1259 return;
1260 }
1261
deadbeef5c3c1042017-08-04 15:01:57 -07001262 Port* port = TCPPort::Create(
1263 session_->network_thread(), session_->socket_factory(), network_,
1264 session_->allocator()->min_port(), session_->allocator()->max_port(),
1265 session_->username(), session_->password(),
1266 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001267 if (port) {
1268 session_->AddAllocatedPort(port, this, true);
1269 // Since TCPPort is not created using shared socket, |port| will not be
1270 // added to the dequeue.
1271 }
1272}
1273
1274void AllocationSequence::CreateStunPorts() {
1275 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1276 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1277 return;
1278 }
1279
1280 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1281 return;
1282 }
1283
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001284 if (!(config_ && !config_->StunServers().empty())) {
1285 LOG(LS_WARNING)
1286 << "AllocationSequence: No STUN server configured, skipping.";
1287 return;
1288 }
1289
deadbeef5c3c1042017-08-04 15:01:57 -07001290 StunPort* port = StunPort::Create(
1291 session_->network_thread(), session_->socket_factory(), network_,
1292 session_->allocator()->min_port(), session_->allocator()->max_port(),
1293 session_->username(), session_->password(), config_->StunServers(),
1294 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001295 if (port) {
1296 session_->AddAllocatedPort(port, this, true);
1297 // Since StunPort is not created using shared socket, |port| will not be
1298 // added to the dequeue.
1299 }
1300}
1301
1302void AllocationSequence::CreateRelayPorts() {
1303 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1304 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1305 return;
1306 }
1307
1308 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1309 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001310 RTC_DCHECK(config_);
1311 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001312 if (!(config_ && !config_->relays.empty())) {
1313 LOG(LS_WARNING)
1314 << "AllocationSequence: No relay server configured, skipping.";
1315 return;
1316 }
1317
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001318 for (RelayServerConfig& relay : config_->relays) {
1319 if (relay.type == RELAY_GTURN) {
1320 CreateGturnPort(relay);
1321 } else if (relay.type == RELAY_TURN) {
1322 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001323 } else {
nissec80e7412017-01-11 05:56:46 -08001324 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325 }
1326 }
1327}
1328
1329void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1330 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001331 RelayPort* port = RelayPort::Create(
1332 session_->network_thread(), session_->socket_factory(), network_,
1333 session_->allocator()->min_port(), session_->allocator()->max_port(),
1334 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001335 if (port) {
1336 // Since RelayPort is not created using shared socket, |port| will not be
1337 // added to the dequeue.
1338 // Note: We must add the allocated port before we add addresses because
1339 // the latter will create candidates that need name and preference
1340 // settings. However, we also can't prepare the address (normally
1341 // done by AddAllocatedPort) until we have these addresses. So we
1342 // wait to do that until below.
1343 session_->AddAllocatedPort(port, this, false);
1344
1345 // Add the addresses of this protocol.
1346 PortList::const_iterator relay_port;
1347 for (relay_port = config.ports.begin();
1348 relay_port != config.ports.end();
1349 ++relay_port) {
1350 port->AddServerAddress(*relay_port);
1351 port->AddExternalAddress(*relay_port);
1352 }
1353 // Start fetching an address for this port.
1354 port->PrepareAddress();
1355 }
1356}
1357
1358void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1359 PortList::const_iterator relay_port;
1360 for (relay_port = config.ports.begin();
1361 relay_port != config.ports.end(); ++relay_port) {
1362 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001363
1364 // Skip UDP connections to relay servers if it's disallowed.
1365 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1366 relay_port->proto == PROTO_UDP) {
1367 continue;
1368 }
1369
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001370 // Do not create a port if the server address family is known and does
1371 // not match the local IP address family.
1372 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001373 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001374 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1375 LOG(LS_INFO) << "Server and local address families are not compatible. "
1376 << "Server address: "
1377 << relay_port->address.ipaddr().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -07001378 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001379 continue;
1380 }
1381
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001382 // Shared socket mode must be enabled only for UDP based ports. Hence
1383 // don't pass shared socket for ports which will create TCP sockets.
1384 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1385 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1386 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001387 relay_port->proto == PROTO_UDP && udp_socket_) {
maxmorine9ef9072017-08-29 04:49:00 -07001388 port = TurnPort::Create(session_->network_thread(),
1389 session_->socket_factory(),
1390 network_, udp_socket_.get(),
1391 session_->username(), session_->password(),
1392 *relay_port, config.credentials, config.priority,
Jonas Orelandb23ed7f2017-10-09 08:01:47 +02001393 session_->allocator()->origin(),
1394 session_->allocator()->turn_customizer());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001395 turn_ports_.push_back(port);
1396 // Listen to the port destroyed signal, to allow AllocationSequence to
1397 // remove entrt from it's map.
1398 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1399 } else {
deadbeef5c3c1042017-08-04 15:01:57 -07001400 port = TurnPort::Create(
1401 session_->network_thread(), session_->socket_factory(), network_,
1402 session_->allocator()->min_port(), session_->allocator()->max_port(),
1403 session_->username(), session_->password(), *relay_port,
Diogo Real1dca9d52017-08-29 12:18:32 -07001404 config.credentials, config.priority, session_->allocator()->origin(),
Jonas Orelandb23ed7f2017-10-09 08:01:47 +02001405 config.tls_alpn_protocols, config.tls_elliptic_curves,
1406 session_->allocator()->turn_customizer());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001407 }
nisseede5da42017-01-12 05:15:36 -08001408 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001409 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001410 session_->AddAllocatedPort(port, this, true);
1411 }
1412}
1413
1414void AllocationSequence::OnReadPacket(
1415 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1416 const rtc::SocketAddress& remote_addr,
1417 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001418 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001419
1420 bool turn_port_found = false;
1421
1422 // Try to find the TurnPort that matches the remote address. Note that the
1423 // message could be a STUN binding response if the TURN server is also used as
1424 // a STUN server. We don't want to parse every message here to check if it is
1425 // a STUN binding response, so we pass the message to TurnPort regardless of
1426 // the message type. The TurnPort will just ignore the message since it will
1427 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001428 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001430 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1431 packet_time)) {
1432 return;
1433 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001434 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001435 }
1436 }
1437
1438 if (udp_port_) {
1439 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1440
1441 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1442 // the TURN server is also a STUN server.
1443 if (!turn_port_found ||
1444 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001445 RTC_DCHECK(udp_port_->SharedSocket());
1446 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1447 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001448 }
1449 }
1450}
1451
1452void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1453 if (udp_port_ == port) {
1454 udp_port_ = NULL;
1455 return;
1456 }
1457
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001458 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1459 if (it != turn_ports_.end()) {
1460 turn_ports_.erase(it);
1461 } else {
1462 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001463 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001464 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001465}
1466
1467// PortConfiguration
1468PortConfiguration::PortConfiguration(
1469 const rtc::SocketAddress& stun_address,
1470 const std::string& username,
1471 const std::string& password)
1472 : stun_address(stun_address), username(username), password(password) {
1473 if (!stun_address.IsNil())
1474 stun_servers.insert(stun_address);
1475}
1476
1477PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1478 const std::string& username,
1479 const std::string& password)
1480 : stun_servers(stun_servers),
1481 username(username),
1482 password(password) {
1483 if (!stun_servers.empty())
1484 stun_address = *(stun_servers.begin());
1485}
1486
1487ServerAddresses PortConfiguration::StunServers() {
1488 if (!stun_address.IsNil() &&
1489 stun_servers.find(stun_address) == stun_servers.end()) {
1490 stun_servers.insert(stun_address);
1491 }
deadbeefc5d0d952015-07-16 10:22:21 -07001492 // Every UDP TURN server should also be used as a STUN server.
1493 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1494 for (const rtc::SocketAddress& turn_server : turn_servers) {
1495 if (stun_servers.find(turn_server) == stun_servers.end()) {
1496 stun_servers.insert(turn_server);
1497 }
1498 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001499 return stun_servers;
1500}
1501
1502void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1503 relays.push_back(config);
1504}
1505
1506bool PortConfiguration::SupportsProtocol(
1507 const RelayServerConfig& relay, ProtocolType type) const {
1508 PortList::const_iterator relay_port;
1509 for (relay_port = relay.ports.begin();
1510 relay_port != relay.ports.end();
1511 ++relay_port) {
1512 if (relay_port->proto == type)
1513 return true;
1514 }
1515 return false;
1516}
1517
1518bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1519 ProtocolType type) const {
1520 for (size_t i = 0; i < relays.size(); ++i) {
1521 if (relays[i].type == turn_type &&
1522 SupportsProtocol(relays[i], type))
1523 return true;
1524 }
1525 return false;
1526}
1527
1528ServerAddresses PortConfiguration::GetRelayServerAddresses(
1529 RelayType turn_type, ProtocolType type) const {
1530 ServerAddresses servers;
1531 for (size_t i = 0; i < relays.size(); ++i) {
1532 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1533 servers.insert(relays[i].ports.front().address);
1534 }
1535 }
1536 return servers;
1537}
1538
1539} // namespace cricket