blob: 051ef846317597b4bb5d9fb635104f75d9e8a426 [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
11#include "webrtc/p2p/client/basicportallocator.h"
12
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
skvlad1d3c7e02017-01-11 17:50:30 -080017#include "webrtc/api/umametrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000018#include "webrtc/p2p/base/basicpacketsocketfactory.h"
19#include "webrtc/p2p/base/common.h"
20#include "webrtc/p2p/base/port.h"
21#include "webrtc/p2p/base/relayport.h"
22#include "webrtc/p2p/base/stunport.h"
23#include "webrtc/p2p/base/tcpport.h"
24#include "webrtc/p2p/base/turnport.h"
25#include "webrtc/p2p/base/udpport.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020026#include "webrtc/rtc_base/checks.h"
27#include "webrtc/rtc_base/helpers.h"
28#include "webrtc/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;
46const int PHASE_SSLTCP = 3;
47
48const int kNumPhases = 4;
49
zhihuang696f8ca2017-06-27 15:11:24 -070050// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070051int GetProtocolPriority(cricket::ProtocolType protocol) {
52 switch (protocol) {
53 case cricket::PROTO_UDP:
54 return 2;
55 case cricket::PROTO_TCP:
56 return 1;
57 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070058 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070059 return 0;
60 default:
nisseeb4ca4e2017-01-12 02:24:27 -080061 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070062 return 0;
63 }
64}
65// Gets address family priority: IPv6 > IPv4 > Unspecified.
66int GetAddressFamilyPriority(int ip_family) {
67 switch (ip_family) {
68 case AF_INET6:
69 return 2;
70 case AF_INET:
71 return 1;
72 default:
nisseeb4ca4e2017-01-12 02:24:27 -080073 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070074 return 0;
75 }
76}
77
78// Returns positive if a is better, negative if b is better, and 0 otherwise.
79int ComparePort(const cricket::Port* a, const cricket::Port* b) {
80 int a_protocol = GetProtocolPriority(a->GetProtocol());
81 int b_protocol = GetProtocolPriority(b->GetProtocol());
82 int cmp_protocol = a_protocol - b_protocol;
83 if (cmp_protocol != 0) {
84 return cmp_protocol;
85 }
86
87 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
88 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
89 return a_family - b_family;
90}
91
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092} // namespace
93
94namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020095const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070096 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
97 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098
99// BasicPortAllocator
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700100BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
jonasoc251cb12017-08-29 03:20:58 -0700101 rtc::PacketSocketFactory* socket_factory,
102 webrtc::RtcEventLog* event_log)
103 : network_manager_(network_manager),
104 socket_factory_(socket_factory),
105 event_log_(event_log) {
nisseede5da42017-01-12 05:15:36 -0800106 RTC_DCHECK(network_manager_ != nullptr);
107 RTC_DCHECK(socket_factory_ != nullptr);
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)
jonasoc251cb12017-08-29 03:20:58 -0700112 : network_manager_(network_manager), socket_factory_(nullptr),
113 event_log_(nullptr) {
nisseede5da42017-01-12 05:15:36 -0800114 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115 Construct();
116}
117
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700118BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
119 rtc::PacketSocketFactory* socket_factory,
120 const ServerAddresses& stun_servers)
jonasoc251cb12017-08-29 03:20:58 -0700121 : network_manager_(network_manager), socket_factory_(socket_factory),
122 event_log_(nullptr) {
nisseede5da42017-01-12 05:15:36 -0800123 RTC_DCHECK(socket_factory_ != NULL);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700124 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000125 Construct();
126}
127
128BasicPortAllocator::BasicPortAllocator(
129 rtc::NetworkManager* network_manager,
130 const ServerAddresses& stun_servers,
131 const rtc::SocketAddress& relay_address_udp,
132 const rtc::SocketAddress& relay_address_tcp,
133 const rtc::SocketAddress& relay_address_ssl)
jonasoc251cb12017-08-29 03:20:58 -0700134 : network_manager_(network_manager), socket_factory_(NULL),
135 event_log_(nullptr) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700136 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000137 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800138 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800140 }
141 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800143 }
144 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800146 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147
deadbeef653b8e02015-11-11 12:55:10 -0800148 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700149 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800150 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700152 SetConfiguration(stun_servers, turn_servers, 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153 Construct();
154}
155
156void BasicPortAllocator::Construct() {
157 allow_tcp_listen_ = true;
158}
159
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700160void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
161 IceRegatheringReason reason) {
162 if (!metrics_observer()) {
163 return;
164 }
165 // If the session has not been taken by an active channel, do not report the
166 // metric.
167 for (auto& allocator_session : pooled_sessions()) {
168 if (allocator_session.get() == session) {
169 return;
170 }
171 }
172
173 metrics_observer()->IncrementEnumCounter(
174 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
175 static_cast<int>(IceRegatheringReason::MAX_VALUE));
176}
177
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800179 // Our created port allocator sessions depend on us, so destroy our remaining
180 // pooled sessions before anything else.
181 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182}
183
deadbeefc5d0d952015-07-16 10:22:21 -0700184PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 const std::string& content_name, int component,
186 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700187 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000188 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700189 session->SignalIceRegathering.connect(this,
190 &BasicPortAllocator::OnIceRegathering);
191 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000192}
193
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700194void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
195 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
196 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700197 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
198 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700199}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200
201// BasicPortAllocatorSession
202BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700203 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204 const std::string& content_name,
205 int component,
206 const std::string& ice_ufrag,
207 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700208 : PortAllocatorSession(content_name,
209 component,
210 ice_ufrag,
211 ice_pwd,
212 allocator->flags()),
213 allocator_(allocator),
214 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215 socket_factory_(allocator->socket_factory()),
216 allocation_started_(false),
217 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700218 allocation_sequences_created_(false),
219 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000220 allocator_->network_manager()->SignalNetworksChanged.connect(
221 this, &BasicPortAllocatorSession::OnNetworksChanged);
222 allocator_->network_manager()->StartUpdating();
223}
224
225BasicPortAllocatorSession::~BasicPortAllocatorSession() {
226 allocator_->network_manager()->StopUpdating();
227 if (network_thread_ != NULL)
228 network_thread_->Clear(this);
229
Peter Boström0c4e06b2015-10-07 12:23:21 +0200230 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000231 // AllocationSequence should clear it's map entry for turn ports before
232 // ports are destroyed.
233 sequences_[i]->Clear();
234 }
235
236 std::vector<PortData>::iterator it;
237 for (it = ports_.begin(); it != ports_.end(); it++)
238 delete it->port();
239
Peter Boström0c4e06b2015-10-07 12:23:21 +0200240 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000241 delete configs_[i];
242
Peter Boström0c4e06b2015-10-07 12:23:21 +0200243 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000244 delete sequences_[i];
245}
246
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700247void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
248 if (filter == candidate_filter_) {
249 return;
250 }
251 // We assume the filter will only change from "ALL" to something else.
252 RTC_DCHECK(candidate_filter_ == CF_ALL);
253 candidate_filter_ = filter;
254 for (PortData& port : ports_) {
255 if (!port.has_pairable_candidate()) {
256 continue;
257 }
258 const auto& candidates = port.port()->Candidates();
259 // Setting a filter may cause a ready port to become non-ready
260 // if it no longer has any pairable candidates.
261 if (!std::any_of(candidates.begin(), candidates.end(),
262 [this, &port](const Candidate& candidate) {
263 return CandidatePairable(candidate, port.port());
264 })) {
265 port.set_has_pairable_candidate(false);
266 }
267 }
268}
269
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270void BasicPortAllocatorSession::StartGettingPorts() {
271 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700272 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273 if (!socket_factory_) {
274 owned_socket_factory_.reset(
275 new rtc::BasicPacketSocketFactory(network_thread_));
276 socket_factory_ = owned_socket_factory_.get();
277 }
278
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700279 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700280
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700281 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700282 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283}
284
285void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800286 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700287 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700288 // Note: this must be called after ClearGettingPorts because both may set the
289 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700290 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700291}
292
293void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800294 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000295 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700296 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700298 }
deadbeefb60a8192016-08-24 15:15:00 -0700299 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700300 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700301}
302
303std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
304 std::vector<rtc::Network*> networks = GetNetworks();
305
306 // A network interface may have both IPv4 and IPv6 networks. Only if
307 // neither of the networks has any connections, the network interface
308 // is considered failed and need to be regathered on.
309 std::set<std::string> networks_with_connection;
310 for (const PortData& data : ports_) {
311 Port* port = data.port();
312 if (!port->connections().empty()) {
313 networks_with_connection.insert(port->Network()->name());
314 }
315 }
316
317 networks.erase(
318 std::remove_if(networks.begin(), networks.end(),
319 [networks_with_connection](rtc::Network* network) {
320 // If a network does not have any connection, it is
321 // considered failed.
322 return networks_with_connection.find(network->name()) !=
323 networks_with_connection.end();
324 }),
325 networks.end());
326 return networks;
327}
328
329void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
330 // Find the list of networks that have no connection.
331 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
332 if (failed_networks.empty()) {
333 return;
334 }
335
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700336 LOG(LS_INFO) << "Regather candidates on failed networks";
337
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700338 // Mark a sequence as "network failed" if its network is in the list of failed
339 // networks, so that it won't be considered as equivalent when the session
340 // regathers ports and candidates.
341 for (AllocationSequence* sequence : sequences_) {
342 if (!sequence->network_failed() &&
343 std::find(failed_networks.begin(), failed_networks.end(),
344 sequence->network()) != failed_networks.end()) {
345 sequence->set_network_failed();
346 }
347 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700348
349 bool disable_equivalent_phases = true;
350 Regather(failed_networks, disable_equivalent_phases,
351 IceRegatheringReason::NETWORK_FAILURE);
352}
353
354void BasicPortAllocatorSession::RegatherOnAllNetworks() {
355 std::vector<rtc::Network*> networks = GetNetworks();
356 if (networks.empty()) {
357 return;
358 }
359
360 LOG(LS_INFO) << "Regather candidates on all networks";
361
362 // We expect to generate candidates that are equivalent to what we have now.
363 // Force DoAllocate to generate them instead of skipping.
364 bool disable_equivalent_phases = false;
365 Regather(networks, disable_equivalent_phases,
366 IceRegatheringReason::OCCASIONAL_REFRESH);
367}
368
369void BasicPortAllocatorSession::Regather(
370 const std::vector<rtc::Network*>& networks,
371 bool disable_equivalent_phases,
372 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700373 // Remove ports from being used locally and send signaling to remove
374 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700375 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700376 if (!ports_to_prune.empty()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700377 LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700378 PrunePortsAndRemoveCandidates(ports_to_prune);
379 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700380
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700381 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700382 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700383
Steve Anton300bf8e2017-07-14 10:13:10 -0700384 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700385 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000386}
387
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700388std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
389 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700390 for (const PortData& data : ports_) {
391 if (data.ready()) {
392 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700393 }
394 }
395 return ret;
396}
397
398std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
399 std::vector<Candidate> candidates;
400 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700401 if (!data.ready()) {
402 continue;
403 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700404 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700405 }
406 return candidates;
407}
408
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700409void BasicPortAllocatorSession::GetCandidatesFromPort(
410 const PortData& data,
411 std::vector<Candidate>* candidates) const {
412 RTC_CHECK(candidates != nullptr);
413 for (const Candidate& candidate : data.port()->Candidates()) {
414 if (!CheckCandidateFilter(candidate)) {
415 continue;
416 }
417 ProtocolType pvalue;
418 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
419 !data.sequence()->ProtocolEnabled(pvalue)) {
420 continue;
421 }
422 candidates->push_back(SanitizeRelatedAddress(candidate));
423 }
424}
425
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700426Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
427 const Candidate& c) const {
428 Candidate copy = c;
429 // If adapter enumeration is disabled or host candidates are disabled,
430 // clear the raddr of STUN candidates to avoid local address leakage.
431 bool filter_stun_related_address =
432 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
433 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
434 !(candidate_filter_ & CF_HOST);
435 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
436 // to avoid reflexive address leakage.
437 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
438 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
439 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
440 copy.set_related_address(
441 rtc::EmptySocketAddressWithFamily(copy.address().family()));
442 }
443 return copy;
444}
445
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700446bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
447 // Done only if all required AllocationSequence objects
448 // are created.
449 if (!allocation_sequences_created_) {
450 return false;
451 }
452
453 // Check that all port allocation sequences are complete (not running).
454 if (std::any_of(sequences_.begin(), sequences_.end(),
455 [](const AllocationSequence* sequence) {
456 return sequence->state() == AllocationSequence::kRunning;
457 })) {
458 return false;
459 }
460
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700461 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700462 // expected candidates. Session will trigger candidates allocation complete
463 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700464 return std::none_of(ports_.begin(), ports_.end(),
465 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700466}
467
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000468void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
469 switch (message->message_id) {
470 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800471 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472 GetPortConfigurations();
473 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800475 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
477 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800479 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 OnAllocate();
481 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000482 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800483 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484 OnAllocationSequenceObjectsCreated();
485 break;
486 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800487 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488 OnConfigStop();
489 break;
490 default:
nissec80e7412017-01-11 05:56:46 -0800491 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492 }
493}
494
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700495void BasicPortAllocatorSession::UpdateIceParametersInternal() {
496 for (PortData& port : ports_) {
497 port.port()->set_content_name(content_name());
498 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
499 }
500}
501
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000502void BasicPortAllocatorSession::GetPortConfigurations() {
503 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
504 username(),
505 password());
506
deadbeef653b8e02015-11-11 12:55:10 -0800507 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
508 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509 }
510 ConfigReady(config);
511}
512
513void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700514 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000515}
516
517// Adds a configuration to the list.
518void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800519 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000520 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800521 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000522
523 AllocatePorts();
524}
525
526void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800527 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000528
529 // If any of the allocated ports have not completed the candidates allocation,
530 // mark those as error. Since session doesn't need any new candidates
531 // at this stage of the allocation, it's safe to discard any new candidates.
532 bool send_signal = false;
533 for (std::vector<PortData>::iterator it = ports_.begin();
534 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700535 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536 // Updating port state to error, which didn't finish allocating candidates
537 // yet.
538 it->set_error();
539 send_signal = true;
540 }
541 }
542
543 // Did we stop any running sequences?
544 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
545 it != sequences_.end() && !send_signal; ++it) {
546 if ((*it)->state() == AllocationSequence::kStopped) {
547 send_signal = true;
548 }
549 }
550
551 // If we stopped anything that was running, send a done signal now.
552 if (send_signal) {
553 MaybeSignalCandidatesAllocationDone();
554 }
555}
556
557void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800558 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700559 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560}
561
562void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700563 if (network_manager_started_ && !IsStopped()) {
564 bool disable_equivalent_phases = true;
565 DoAllocate(disable_equivalent_phases);
566 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567
568 allocation_started_ = true;
569}
570
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700571std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
572 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700573 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800574 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700575 // If the network permission state is BLOCKED, we just act as if the flag has
576 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700577 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700578 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700579 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
580 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000581 // If the adapter enumeration is disabled, we'll just bind to any address
582 // instead of specific NIC. This is to ensure the same routing for http
583 // traffic by OS is also used here to avoid any local or public IP leakage
584 // during stun process.
585 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700586 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000587 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700588 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800589 // If network enumeration fails, use the ANY address as a fallback, so we
590 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700591 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
592 // set, we'll use ANY address candidates either way.
593 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800594 network_manager->GetAnyAddressNetworks(&networks);
595 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000596 }
deadbeef3427f532017-07-26 16:09:33 -0700597 // Do some more filtering, depending on the network ignore mask and "disable
598 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700599 networks.erase(std::remove_if(networks.begin(), networks.end(),
600 [this](rtc::Network* network) {
601 return allocator_->network_ignore_mask() &
602 network->type();
603 }),
604 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700605 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
606 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700607 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700608 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
609 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700610 networks.erase(std::remove_if(networks.begin(), networks.end(),
611 [lowest_cost](rtc::Network* network) {
612 return network->GetCost() >
613 lowest_cost + rtc::kNetworkCostLow;
614 }),
615 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700616 }
deadbeef3427f532017-07-26 16:09:33 -0700617 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
618 // default, it's 5), remove networks to ensure that limit is satisfied.
619 //
620 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
621 // networks, we could try to choose a set that's "most likely to work". It's
622 // hard to define what that means though; it's not just "lowest cost".
623 // Alternatively, we could just focus on making our ICE pinging logic smarter
624 // such that this filtering isn't necessary in the first place.
625 int ipv6_networks = 0;
626 for (auto it = networks.begin(); it != networks.end();) {
627 if ((*it)->prefix().family() == AF_INET6) {
628 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
629 it = networks.erase(it);
630 continue;
631 } else {
632 ++ipv6_networks;
633 }
634 }
635 ++it;
636 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700637 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700638}
639
640// For each network, see if we have a sequence that covers it already. If not,
641// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700642void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700643 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700644 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645 if (networks.empty()) {
646 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
647 done_signal_needed = true;
648 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700649 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700650 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200651 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200652 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
654 // If all the ports are disabled we should just fire the allocation
655 // done event and return.
656 done_signal_needed = true;
657 break;
658 }
659
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 if (!config || config->relays.empty()) {
661 // No relay ports specified in this config.
662 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
663 }
664
665 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000666 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000667 // Skip IPv6 networks unless the flag's been set.
668 continue;
669 }
670
zhihuangb09b3f92017-03-07 14:40:51 -0800671 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
672 networks[i]->GetBestIP().family() == AF_INET6 &&
673 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
674 // Skip IPv6 Wi-Fi networks unless the flag's been set.
675 continue;
676 }
677
Steve Anton300bf8e2017-07-14 10:13:10 -0700678 if (disable_equivalent) {
679 // Disable phases that would only create ports equivalent to
680 // ones that we have already made.
681 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000682
Steve Anton300bf8e2017-07-14 10:13:10 -0700683 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
684 // New AllocationSequence would have nothing to do, so don't make it.
685 continue;
686 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000687 }
688
689 AllocationSequence* sequence =
690 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691 sequence->SignalPortAllocationComplete.connect(
692 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700693 sequence->Init();
694 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700696 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000697 }
698 }
699 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700700 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000701 }
702}
703
704void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700705 std::vector<rtc::Network*> networks = GetNetworks();
706 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700707 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700708 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700709 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700710 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700711 std::find(networks.begin(), networks.end(), sequence->network()) ==
712 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700713 sequence->OnNetworkFailed();
714 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700715 }
716 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700717 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
718 if (!ports_to_prune.empty()) {
719 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
720 << " ports because their networks were gone";
721 PrunePortsAndRemoveCandidates(ports_to_prune);
722 }
honghaiz8c404fa2015-09-28 07:59:43 -0700723
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700724 if (allocation_started_ && !IsStopped()) {
725 if (network_manager_started_) {
726 // If the network manager has started, it must be regathering.
727 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
728 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700729 bool disable_equivalent_phases = true;
730 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700731 }
732
Honghai Zhang5048f572016-08-23 15:47:33 -0700733 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700734 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700735 network_manager_started_ = true;
736 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737}
738
739void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200740 rtc::Network* network,
741 PortConfiguration* config,
742 uint32_t* flags) {
743 for (uint32_t i = 0; i < sequences_.size() &&
744 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
745 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000746 sequences_[i]->DisableEquivalentPhases(network, config, flags);
747 }
748}
749
750void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
751 AllocationSequence * seq,
752 bool prepare_address) {
753 if (!port)
754 return;
755
756 LOG(LS_INFO) << "Adding allocated port for " << content_name();
757 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700758 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000759 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700760 if (allocator_->proxy().type != rtc::PROXY_NONE)
761 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700762 port->set_send_retransmit_count_attribute(
763 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000764
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000765 PortData data(port, seq);
766 ports_.push_back(data);
767
768 port->SignalCandidateReady.connect(
769 this, &BasicPortAllocatorSession::OnCandidateReady);
770 port->SignalPortComplete.connect(this,
771 &BasicPortAllocatorSession::OnPortComplete);
772 port->SignalDestroyed.connect(this,
773 &BasicPortAllocatorSession::OnPortDestroyed);
774 port->SignalPortError.connect(
775 this, &BasicPortAllocatorSession::OnPortError);
776 LOG_J(LS_INFO, port) << "Added port to allocator";
777
778 if (prepare_address)
779 port->PrepareAddress();
780}
781
782void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
783 allocation_sequences_created_ = true;
784 // Send candidate allocation complete signal if we have no sequences.
785 MaybeSignalCandidatesAllocationDone();
786}
787
788void BasicPortAllocatorSession::OnCandidateReady(
789 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800790 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800792 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700793 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000794 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700795 // already done with gathering.
796 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700797 LOG(LS_WARNING)
798 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700799 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700800 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700801
danilchapf4e8cf02016-06-30 01:55:03 -0700802 // Mark that the port has a pairable candidate, either because we have a
803 // usable candidate from the port, or simply because the port is bound to the
804 // any address and therefore has no host candidate. This will trigger the port
805 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700806 // checks. If port has already been marked as having a pairable candidate,
807 // do nothing here.
808 // Note: We should check whether any candidates may become ready after this
809 // because there we will check whether the candidate is generated by the ready
810 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700811 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700812 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700813 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700814
815 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700816 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700817 }
818 // If the current port is not pruned yet, SignalPortReady.
819 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700820 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700821 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700822 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700823 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700824 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700825
826 ProtocolType pvalue;
827 bool candidate_protocol_enabled =
828 StringToProto(c.protocol().c_str(), &pvalue) &&
829 data->sequence()->ProtocolEnabled(pvalue);
830
831 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
832 std::vector<Candidate> candidates;
833 candidates.push_back(SanitizeRelatedAddress(c));
834 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700835 } else if (!candidate_protocol_enabled) {
836 LOG(LS_INFO)
837 << "Not yet signaling candidate because protocol is not yet enabled.";
838 } else {
839 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700840 }
841
842 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700843 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700844 MaybeSignalCandidatesAllocationDone();
845 }
846}
847
848Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
849 const std::string& network_name) const {
850 Port* best_turn_port = nullptr;
851 for (const PortData& data : ports_) {
852 if (data.port()->Network()->name() == network_name &&
853 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
854 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
855 best_turn_port = data.port();
856 }
857 }
858 return best_turn_port;
859}
860
861bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700862 // Note: We determine the same network based only on their network names. So
863 // if an IPv4 address and an IPv6 address have the same network name, they
864 // are considered the same network here.
865 const std::string& network_name = newly_pairable_turn_port->Network()->name();
866 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
867 // |port| is already in the list of ports, so the best port cannot be nullptr.
868 RTC_CHECK(best_turn_port != nullptr);
869
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700870 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700871 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700872 for (PortData& data : ports_) {
873 if (data.port()->Network()->name() == network_name &&
874 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
875 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700876 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700877 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700878 // These ports will be pruned in PrunePortsAndRemoveCandidates.
879 ports_to_prune.push_back(&data);
880 } else {
881 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700882 }
883 }
884 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700885
886 if (!ports_to_prune.empty()) {
887 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
888 << " low-priority TURN ports";
889 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700890 }
891 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892}
893
Honghai Zhanga74363c2016-07-28 18:06:15 -0700894void BasicPortAllocatorSession::PruneAllPorts() {
895 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700896 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700897 }
898}
899
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800901 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700902 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800904 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905
906 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700907 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000908 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700909 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910
911 // Moving to COMPLETE state.
912 data->set_complete();
913 // Send candidate allocation complete signal if this was the last port.
914 MaybeSignalCandidatesAllocationDone();
915}
916
917void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800918 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700919 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800921 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700923 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700925 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926
927 // SignalAddressError is currently sent from StunPort/TurnPort.
928 // But this signal itself is generic.
929 data->set_error();
930 // Send candidate allocation complete signal if this was the last port.
931 MaybeSignalCandidatesAllocationDone();
932}
933
934void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
935 ProtocolType proto) {
936 std::vector<Candidate> candidates;
937 for (std::vector<PortData>::iterator it = ports_.begin();
938 it != ports_.end(); ++it) {
939 if (it->sequence() != seq)
940 continue;
941
942 const std::vector<Candidate>& potentials = it->port()->Candidates();
943 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700944 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000945 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700946 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700948 bool candidate_protocol_enabled =
949 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
950 pvalue == proto;
951 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700952 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
953 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000954 candidates.push_back(potentials[i]);
955 }
956 }
957 }
958
959 if (!candidates.empty()) {
960 SignalCandidatesReady(this, candidates);
961 }
962}
963
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700964bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700965 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000966
967 // When binding to any address, before sending packets out, the getsockname
968 // returns all 0s, but after sending packets, it'll be the NIC used to
969 // send. All 0s is not a valid ICE candidate address and should be filtered
970 // out.
971 if (c.address().IsAnyIP()) {
972 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 }
974
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000975 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000976 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000977 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000978 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000979 } else if (c.type() == LOCAL_PORT_TYPE) {
980 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
981 // We allow host candidates if the filter allows server-reflexive
982 // candidates and the candidate is a public IP. Because we don't generate
983 // server-reflexive candidates if they have the same IP as the host
984 // candidate (i.e. when the host candidate is a public IP), filtering to
985 // only server-reflexive candidates won't work right when the host
986 // candidates have public IPs.
987 return true;
988 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000989
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000990 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000991 }
992 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000993}
994
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700995bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
996 const Port* port) const {
997 bool candidate_signalable = CheckCandidateFilter(c);
998
999 // When device enumeration is disabled (to prevent non-default IP addresses
1000 // from leaking), we ping from some local candidates even though we don't
1001 // signal them. However, if host candidates are also disabled (for example, to
1002 // prevent even default IP addresses from leaking), we still don't want to
1003 // ping from them, even if device enumeration is disabled. Thus, we check for
1004 // both device enumeration and host candidates being disabled.
1005 bool network_enumeration_disabled = c.address().IsAnyIP();
1006 bool can_ping_from_candidate =
1007 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1008 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1009
1010 return candidate_signalable ||
1011 (network_enumeration_disabled && can_ping_from_candidate &&
1012 !host_candidates_disabled);
1013}
1014
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001015void BasicPortAllocatorSession::OnPortAllocationComplete(
1016 AllocationSequence* seq) {
1017 // Send candidate allocation complete signal if all ports are done.
1018 MaybeSignalCandidatesAllocationDone();
1019}
1020
1021void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001022 if (CandidatesAllocationDone()) {
1023 if (pooled()) {
1024 LOG(LS_INFO) << "All candidates gathered for pooled session.";
1025 } else {
1026 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
1027 << component() << ":" << generation();
1028 }
1029 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001031}
1032
1033void BasicPortAllocatorSession::OnPortDestroyed(
1034 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001035 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001036 for (std::vector<PortData>::iterator iter = ports_.begin();
1037 iter != ports_.end(); ++iter) {
1038 if (port == iter->port()) {
1039 ports_.erase(iter);
1040 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1041 << static_cast<int>(ports_.size()) << " remaining)";
1042 return;
1043 }
1044 }
nissec80e7412017-01-11 05:56:46 -08001045 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046}
1047
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1049 Port* port) {
1050 for (std::vector<PortData>::iterator it = ports_.begin();
1051 it != ports_.end(); ++it) {
1052 if (it->port() == port) {
1053 return &*it;
1054 }
1055 }
1056 return NULL;
1057}
1058
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001059std::vector<BasicPortAllocatorSession::PortData*>
1060BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001061 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001062 std::vector<PortData*> unpruned_ports;
1063 for (PortData& port : ports_) {
1064 if (!port.pruned() &&
1065 std::find(networks.begin(), networks.end(),
1066 port.sequence()->network()) != networks.end()) {
1067 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001068 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001069 }
1070 return unpruned_ports;
1071}
1072
1073void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1074 const std::vector<PortData*>& port_data_list) {
1075 std::vector<PortInterface*> pruned_ports;
1076 std::vector<Candidate> removed_candidates;
1077 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001078 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001079 data->Prune();
1080 pruned_ports.push_back(data->port());
1081 if (data->has_pairable_candidate()) {
1082 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001083 // Mark the port as having no pairable candidates so that its candidates
1084 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001085 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001086 }
1087 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001088 if (!pruned_ports.empty()) {
1089 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001090 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001091 if (!removed_candidates.empty()) {
1092 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1093 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001094 }
1095}
1096
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097// AllocationSequence
1098
1099AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1100 rtc::Network* network,
1101 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001102 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001103 : session_(session),
1104 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001105 config_(config),
1106 state_(kInit),
1107 flags_(flags),
1108 udp_socket_(),
1109 udp_port_(NULL),
1110 phase_(0) {
1111}
1112
Honghai Zhang5048f572016-08-23 15:47:33 -07001113void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001114 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1115 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001116 rtc::SocketAddress(network_->GetBestIP(), 0),
1117 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001118 if (udp_socket_) {
1119 udp_socket_->SignalReadPacket.connect(
1120 this, &AllocationSequence::OnReadPacket);
1121 }
1122 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1123 // are next available options to setup a communication channel.
1124 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125}
1126
1127void AllocationSequence::Clear() {
1128 udp_port_ = NULL;
1129 turn_ports_.clear();
1130}
1131
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001132void AllocationSequence::OnNetworkFailed() {
1133 RTC_DCHECK(!network_failed_);
1134 network_failed_ = true;
1135 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001136 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001137}
1138
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001139AllocationSequence::~AllocationSequence() {
1140 session_->network_thread()->Clear(this);
1141}
1142
1143void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001144 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001145 if (network_failed_) {
1146 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001147 // it won't be equivalent to the new network.
1148 return;
1149 }
1150
deadbeef5c3c1042017-08-04 15:01:57 -07001151 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001152 // Different network setup; nothing is equivalent.
1153 return;
1154 }
1155
1156 // Else turn off the stuff that we've already got covered.
1157
1158 // Every config implicitly specifies local, so turn that off right away.
1159 *flags |= PORTALLOCATOR_DISABLE_UDP;
1160 *flags |= PORTALLOCATOR_DISABLE_TCP;
1161
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
1198 const char* const PHASE_NAMES[kNumPhases] = {
1199 "Udp", "Relay", "Tcp", "SslTcp"
1200 };
1201
1202 // Perform all of the phases in the current step.
1203 LOG_J(LS_INFO, network_) << "Allocation Phase="
1204 << PHASE_NAMES[phase_];
1205
1206 switch (phase_) {
1207 case PHASE_UDP:
1208 CreateUDPPorts();
1209 CreateStunPorts();
1210 EnableProtocol(PROTO_UDP);
1211 break;
1212
1213 case PHASE_RELAY:
1214 CreateRelayPorts();
1215 break;
1216
1217 case PHASE_TCP:
1218 CreateTCPPorts();
1219 EnableProtocol(PROTO_TCP);
1220 break;
1221
1222 case PHASE_SSLTCP:
1223 state_ = kCompleted;
1224 EnableProtocol(PROTO_SSLTCP);
1225 break;
1226
1227 default:
nissec80e7412017-01-11 05:56:46 -08001228 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001229 }
1230
1231 if (state() == kRunning) {
1232 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001233 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1234 session_->allocator()->step_delay(),
1235 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001236 } else {
1237 // If all phases in AllocationSequence are completed, no allocation
1238 // steps needed further. Canceling pending signal.
1239 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1240 SignalPortAllocationComplete(this);
1241 }
1242}
1243
1244void AllocationSequence::EnableProtocol(ProtocolType proto) {
1245 if (!ProtocolEnabled(proto)) {
1246 protocols_.push_back(proto);
1247 session_->OnProtocolEnabled(this, proto);
1248 }
1249}
1250
1251bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1252 for (ProtocolList::const_iterator it = protocols_.begin();
1253 it != protocols_.end(); ++it) {
1254 if (*it == proto)
1255 return true;
1256 }
1257 return false;
1258}
1259
1260void AllocationSequence::CreateUDPPorts() {
1261 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1262 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1263 return;
1264 }
1265
1266 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1267 // is enabled completely.
1268 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001269 bool emit_local_candidate_for_anyaddress =
1270 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001271 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001272 port = UDPPort::Create(
1273 session_->network_thread(), session_->socket_factory(), network_,
1274 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001275 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001276 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001277 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001278 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001279 session_->allocator()->min_port(), session_->allocator()->max_port(),
1280 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001281 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001282 }
1283
1284 if (port) {
1285 // If shared socket is enabled, STUN candidate will be allocated by the
1286 // UDPPort.
1287 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1288 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001289 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001290
1291 // If STUN is not disabled, setting stun server address to port.
1292 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001293 if (config_ && !config_->StunServers().empty()) {
1294 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1295 << "STUN candidate generation.";
1296 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001297 }
1298 }
1299 }
1300
1301 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001302 }
1303}
1304
1305void AllocationSequence::CreateTCPPorts() {
1306 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1307 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1308 return;
1309 }
1310
deadbeef5c3c1042017-08-04 15:01:57 -07001311 Port* port = TCPPort::Create(
1312 session_->network_thread(), session_->socket_factory(), network_,
1313 session_->allocator()->min_port(), session_->allocator()->max_port(),
1314 session_->username(), session_->password(),
1315 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316 if (port) {
1317 session_->AddAllocatedPort(port, this, true);
1318 // Since TCPPort is not created using shared socket, |port| will not be
1319 // added to the dequeue.
1320 }
1321}
1322
1323void AllocationSequence::CreateStunPorts() {
1324 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1325 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1326 return;
1327 }
1328
1329 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1330 return;
1331 }
1332
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333 if (!(config_ && !config_->StunServers().empty())) {
1334 LOG(LS_WARNING)
1335 << "AllocationSequence: No STUN server configured, skipping.";
1336 return;
1337 }
1338
deadbeef5c3c1042017-08-04 15:01:57 -07001339 StunPort* port = StunPort::Create(
1340 session_->network_thread(), session_->socket_factory(), network_,
1341 session_->allocator()->min_port(), session_->allocator()->max_port(),
1342 session_->username(), session_->password(), config_->StunServers(),
1343 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001344 if (port) {
1345 session_->AddAllocatedPort(port, this, true);
1346 // Since StunPort is not created using shared socket, |port| will not be
1347 // added to the dequeue.
1348 }
1349}
1350
1351void AllocationSequence::CreateRelayPorts() {
1352 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1353 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1354 return;
1355 }
1356
1357 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1358 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001359 RTC_DCHECK(config_);
1360 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001361 if (!(config_ && !config_->relays.empty())) {
1362 LOG(LS_WARNING)
1363 << "AllocationSequence: No relay server configured, skipping.";
1364 return;
1365 }
1366
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001367 for (RelayServerConfig& relay : config_->relays) {
1368 if (relay.type == RELAY_GTURN) {
1369 CreateGturnPort(relay);
1370 } else if (relay.type == RELAY_TURN) {
1371 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372 } else {
nissec80e7412017-01-11 05:56:46 -08001373 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001374 }
1375 }
1376}
1377
1378void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1379 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001380 RelayPort* port = RelayPort::Create(
1381 session_->network_thread(), session_->socket_factory(), network_,
1382 session_->allocator()->min_port(), session_->allocator()->max_port(),
1383 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 if (port) {
1385 // Since RelayPort is not created using shared socket, |port| will not be
1386 // added to the dequeue.
1387 // Note: We must add the allocated port before we add addresses because
1388 // the latter will create candidates that need name and preference
1389 // settings. However, we also can't prepare the address (normally
1390 // done by AddAllocatedPort) until we have these addresses. So we
1391 // wait to do that until below.
1392 session_->AddAllocatedPort(port, this, false);
1393
1394 // Add the addresses of this protocol.
1395 PortList::const_iterator relay_port;
1396 for (relay_port = config.ports.begin();
1397 relay_port != config.ports.end();
1398 ++relay_port) {
1399 port->AddServerAddress(*relay_port);
1400 port->AddExternalAddress(*relay_port);
1401 }
1402 // Start fetching an address for this port.
1403 port->PrepareAddress();
1404 }
1405}
1406
1407void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1408 PortList::const_iterator relay_port;
1409 for (relay_port = config.ports.begin();
1410 relay_port != config.ports.end(); ++relay_port) {
1411 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001412
1413 // Skip UDP connections to relay servers if it's disallowed.
1414 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1415 relay_port->proto == PROTO_UDP) {
1416 continue;
1417 }
1418
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001419 // Do not create a port if the server address family is known and does
1420 // not match the local IP address family.
1421 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001422 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001423 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1424 LOG(LS_INFO) << "Server and local address families are not compatible. "
1425 << "Server address: "
1426 << relay_port->address.ipaddr().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -07001427 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001428 continue;
1429 }
1430
1431
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001432 // Shared socket mode must be enabled only for UDP based ports. Hence
1433 // don't pass shared socket for ports which will create TCP sockets.
1434 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1435 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1436 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001437 relay_port->proto == PROTO_UDP && udp_socket_) {
jonasoc251cb12017-08-29 03:20:58 -07001438 port = TurnPort::Create(
1439 session_->network_thread(), session_->socket_factory(), network_,
1440 udp_socket_.get(), session_->username(), session_->password(),
1441 *relay_port, config.credentials, config.priority,
1442 session_->allocator()->origin(), session_->event_log());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001443 turn_ports_.push_back(port);
1444 // Listen to the port destroyed signal, to allow AllocationSequence to
1445 // remove entrt from it's map.
1446 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1447 } else {
deadbeef5c3c1042017-08-04 15:01:57 -07001448 port = TurnPort::Create(
1449 session_->network_thread(), session_->socket_factory(), network_,
1450 session_->allocator()->min_port(), session_->allocator()->max_port(),
1451 session_->username(), session_->password(), *relay_port,
jonasoc251cb12017-08-29 03:20:58 -07001452 config.credentials, config.priority, session_->allocator()->origin(),
1453 session_->event_log());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001454 }
nisseede5da42017-01-12 05:15:36 -08001455 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001456 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457 session_->AddAllocatedPort(port, this, true);
1458 }
1459}
1460
1461void AllocationSequence::OnReadPacket(
1462 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1463 const rtc::SocketAddress& remote_addr,
1464 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001465 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001466
1467 bool turn_port_found = false;
1468
1469 // Try to find the TurnPort that matches the remote address. Note that the
1470 // message could be a STUN binding response if the TURN server is also used as
1471 // a STUN server. We don't want to parse every message here to check if it is
1472 // a STUN binding response, so we pass the message to TurnPort regardless of
1473 // the message type. The TurnPort will just ignore the message since it will
1474 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001475 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001476 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001477 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1478 packet_time)) {
1479 return;
1480 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001481 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001482 }
1483 }
1484
1485 if (udp_port_) {
1486 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1487
1488 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1489 // the TURN server is also a STUN server.
1490 if (!turn_port_found ||
1491 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001492 RTC_DCHECK(udp_port_->SharedSocket());
1493 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1494 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001495 }
1496 }
1497}
1498
1499void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1500 if (udp_port_ == port) {
1501 udp_port_ = NULL;
1502 return;
1503 }
1504
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001505 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1506 if (it != turn_ports_.end()) {
1507 turn_ports_.erase(it);
1508 } else {
1509 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001510 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001511 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001512}
1513
1514// PortConfiguration
1515PortConfiguration::PortConfiguration(
1516 const rtc::SocketAddress& stun_address,
1517 const std::string& username,
1518 const std::string& password)
1519 : stun_address(stun_address), username(username), password(password) {
1520 if (!stun_address.IsNil())
1521 stun_servers.insert(stun_address);
1522}
1523
1524PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1525 const std::string& username,
1526 const std::string& password)
1527 : stun_servers(stun_servers),
1528 username(username),
1529 password(password) {
1530 if (!stun_servers.empty())
1531 stun_address = *(stun_servers.begin());
1532}
1533
1534ServerAddresses PortConfiguration::StunServers() {
1535 if (!stun_address.IsNil() &&
1536 stun_servers.find(stun_address) == stun_servers.end()) {
1537 stun_servers.insert(stun_address);
1538 }
deadbeefc5d0d952015-07-16 10:22:21 -07001539 // Every UDP TURN server should also be used as a STUN server.
1540 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1541 for (const rtc::SocketAddress& turn_server : turn_servers) {
1542 if (stun_servers.find(turn_server) == stun_servers.end()) {
1543 stun_servers.insert(turn_server);
1544 }
1545 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001546 return stun_servers;
1547}
1548
1549void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1550 relays.push_back(config);
1551}
1552
1553bool PortConfiguration::SupportsProtocol(
1554 const RelayServerConfig& relay, ProtocolType type) const {
1555 PortList::const_iterator relay_port;
1556 for (relay_port = relay.ports.begin();
1557 relay_port != relay.ports.end();
1558 ++relay_port) {
1559 if (relay_port->proto == type)
1560 return true;
1561 }
1562 return false;
1563}
1564
1565bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1566 ProtocolType type) const {
1567 for (size_t i = 0; i < relays.size(); ++i) {
1568 if (relays[i].type == turn_type &&
1569 SupportsProtocol(relays[i], type))
1570 return true;
1571 }
1572 return false;
1573}
1574
1575ServerAddresses PortConfiguration::GetRelayServerAddresses(
1576 RelayType turn_type, ProtocolType type) const {
1577 ServerAddresses servers;
1578 for (size_t i = 0; i < relays.size(); ++i) {
1579 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1580 servers.insert(relays[i].ports.front().address);
1581 }
1582 }
1583 return servers;
1584}
1585
1586} // namespace cricket