blob: 992aee6acc9338812cb31f4207e7c35205b02a21 [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,
maxmorine9ef9072017-08-29 04:49:00 -0700101 rtc::PacketSocketFactory* socket_factory)
102 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800103 RTC_DCHECK(network_manager_ != nullptr);
104 RTC_DCHECK(socket_factory_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000105 Construct();
106}
107
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800108BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700109 : network_manager_(network_manager), socket_factory_(nullptr) {
nisseede5da42017-01-12 05:15:36 -0800110 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000111 Construct();
112}
113
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700114BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
115 rtc::PacketSocketFactory* socket_factory,
116 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700117 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800118 RTC_DCHECK(socket_factory_ != NULL);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700119 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120 Construct();
121}
122
123BasicPortAllocator::BasicPortAllocator(
124 rtc::NetworkManager* network_manager,
125 const ServerAddresses& stun_servers,
126 const rtc::SocketAddress& relay_address_udp,
127 const rtc::SocketAddress& relay_address_tcp,
128 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700129 : network_manager_(network_manager), socket_factory_(NULL) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700130 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000131 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800132 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800134 }
135 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000136 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800137 }
138 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800140 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141
deadbeef653b8e02015-11-11 12:55:10 -0800142 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700143 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800144 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700146 SetConfiguration(stun_servers, turn_servers, 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147 Construct();
148}
149
150void BasicPortAllocator::Construct() {
151 allow_tcp_listen_ = true;
152}
153
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700154void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
155 IceRegatheringReason reason) {
156 if (!metrics_observer()) {
157 return;
158 }
159 // If the session has not been taken by an active channel, do not report the
160 // metric.
161 for (auto& allocator_session : pooled_sessions()) {
162 if (allocator_session.get() == session) {
163 return;
164 }
165 }
166
167 metrics_observer()->IncrementEnumCounter(
168 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
169 static_cast<int>(IceRegatheringReason::MAX_VALUE));
170}
171
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800173 // Our created port allocator sessions depend on us, so destroy our remaining
174 // pooled sessions before anything else.
175 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176}
177
deadbeefc5d0d952015-07-16 10:22:21 -0700178PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179 const std::string& content_name, int component,
180 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700181 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700183 session->SignalIceRegathering.connect(this,
184 &BasicPortAllocator::OnIceRegathering);
185 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000186}
187
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700188void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
189 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
190 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700191 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
192 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700193}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194
195// BasicPortAllocatorSession
196BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700197 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000198 const std::string& content_name,
199 int component,
200 const std::string& ice_ufrag,
201 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700202 : PortAllocatorSession(content_name,
203 component,
204 ice_ufrag,
205 ice_pwd,
206 allocator->flags()),
207 allocator_(allocator),
208 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 socket_factory_(allocator->socket_factory()),
210 allocation_started_(false),
211 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700212 allocation_sequences_created_(false),
213 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000214 allocator_->network_manager()->SignalNetworksChanged.connect(
215 this, &BasicPortAllocatorSession::OnNetworksChanged);
216 allocator_->network_manager()->StartUpdating();
217}
218
219BasicPortAllocatorSession::~BasicPortAllocatorSession() {
220 allocator_->network_manager()->StopUpdating();
221 if (network_thread_ != NULL)
222 network_thread_->Clear(this);
223
Peter Boström0c4e06b2015-10-07 12:23:21 +0200224 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000225 // AllocationSequence should clear it's map entry for turn ports before
226 // ports are destroyed.
227 sequences_[i]->Clear();
228 }
229
230 std::vector<PortData>::iterator it;
231 for (it = ports_.begin(); it != ports_.end(); it++)
232 delete it->port();
233
Peter Boström0c4e06b2015-10-07 12:23:21 +0200234 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235 delete configs_[i];
236
Peter Boström0c4e06b2015-10-07 12:23:21 +0200237 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000238 delete sequences_[i];
239}
240
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700241void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
242 if (filter == candidate_filter_) {
243 return;
244 }
245 // We assume the filter will only change from "ALL" to something else.
246 RTC_DCHECK(candidate_filter_ == CF_ALL);
247 candidate_filter_ = filter;
248 for (PortData& port : ports_) {
249 if (!port.has_pairable_candidate()) {
250 continue;
251 }
252 const auto& candidates = port.port()->Candidates();
253 // Setting a filter may cause a ready port to become non-ready
254 // if it no longer has any pairable candidates.
255 if (!std::any_of(candidates.begin(), candidates.end(),
256 [this, &port](const Candidate& candidate) {
257 return CandidatePairable(candidate, port.port());
258 })) {
259 port.set_has_pairable_candidate(false);
260 }
261 }
262}
263
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264void BasicPortAllocatorSession::StartGettingPorts() {
265 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700266 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 if (!socket_factory_) {
268 owned_socket_factory_.reset(
269 new rtc::BasicPacketSocketFactory(network_thread_));
270 socket_factory_ = owned_socket_factory_.get();
271 }
272
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700273 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700274
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700275 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700276 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277}
278
279void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800280 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700281 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700282 // Note: this must be called after ClearGettingPorts because both may set the
283 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700284 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700285}
286
287void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800288 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700290 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700292 }
deadbeefb60a8192016-08-24 15:15:00 -0700293 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700294 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700295}
296
297std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
298 std::vector<rtc::Network*> networks = GetNetworks();
299
300 // A network interface may have both IPv4 and IPv6 networks. Only if
301 // neither of the networks has any connections, the network interface
302 // is considered failed and need to be regathered on.
303 std::set<std::string> networks_with_connection;
304 for (const PortData& data : ports_) {
305 Port* port = data.port();
306 if (!port->connections().empty()) {
307 networks_with_connection.insert(port->Network()->name());
308 }
309 }
310
311 networks.erase(
312 std::remove_if(networks.begin(), networks.end(),
313 [networks_with_connection](rtc::Network* network) {
314 // If a network does not have any connection, it is
315 // considered failed.
316 return networks_with_connection.find(network->name()) !=
317 networks_with_connection.end();
318 }),
319 networks.end());
320 return networks;
321}
322
323void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
324 // Find the list of networks that have no connection.
325 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
326 if (failed_networks.empty()) {
327 return;
328 }
329
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700330 LOG(LS_INFO) << "Regather candidates on failed networks";
331
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700332 // Mark a sequence as "network failed" if its network is in the list of failed
333 // networks, so that it won't be considered as equivalent when the session
334 // regathers ports and candidates.
335 for (AllocationSequence* sequence : sequences_) {
336 if (!sequence->network_failed() &&
337 std::find(failed_networks.begin(), failed_networks.end(),
338 sequence->network()) != failed_networks.end()) {
339 sequence->set_network_failed();
340 }
341 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700342
343 bool disable_equivalent_phases = true;
344 Regather(failed_networks, disable_equivalent_phases,
345 IceRegatheringReason::NETWORK_FAILURE);
346}
347
348void BasicPortAllocatorSession::RegatherOnAllNetworks() {
349 std::vector<rtc::Network*> networks = GetNetworks();
350 if (networks.empty()) {
351 return;
352 }
353
354 LOG(LS_INFO) << "Regather candidates on all networks";
355
356 // We expect to generate candidates that are equivalent to what we have now.
357 // Force DoAllocate to generate them instead of skipping.
358 bool disable_equivalent_phases = false;
359 Regather(networks, disable_equivalent_phases,
360 IceRegatheringReason::OCCASIONAL_REFRESH);
361}
362
363void BasicPortAllocatorSession::Regather(
364 const std::vector<rtc::Network*>& networks,
365 bool disable_equivalent_phases,
366 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700367 // Remove ports from being used locally and send signaling to remove
368 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700369 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700370 if (!ports_to_prune.empty()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700371 LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700372 PrunePortsAndRemoveCandidates(ports_to_prune);
373 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700374
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700375 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700376 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700377
Steve Anton300bf8e2017-07-14 10:13:10 -0700378 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700379 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000380}
381
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700382std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
383 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700384 for (const PortData& data : ports_) {
385 if (data.ready()) {
386 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700387 }
388 }
389 return ret;
390}
391
392std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
393 std::vector<Candidate> candidates;
394 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700395 if (!data.ready()) {
396 continue;
397 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700398 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700399 }
400 return candidates;
401}
402
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700403void BasicPortAllocatorSession::GetCandidatesFromPort(
404 const PortData& data,
405 std::vector<Candidate>* candidates) const {
406 RTC_CHECK(candidates != nullptr);
407 for (const Candidate& candidate : data.port()->Candidates()) {
408 if (!CheckCandidateFilter(candidate)) {
409 continue;
410 }
411 ProtocolType pvalue;
412 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
413 !data.sequence()->ProtocolEnabled(pvalue)) {
414 continue;
415 }
416 candidates->push_back(SanitizeRelatedAddress(candidate));
417 }
418}
419
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700420Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
421 const Candidate& c) const {
422 Candidate copy = c;
423 // If adapter enumeration is disabled or host candidates are disabled,
424 // clear the raddr of STUN candidates to avoid local address leakage.
425 bool filter_stun_related_address =
426 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
427 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
428 !(candidate_filter_ & CF_HOST);
429 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
430 // to avoid reflexive address leakage.
431 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
432 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
433 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
434 copy.set_related_address(
435 rtc::EmptySocketAddressWithFamily(copy.address().family()));
436 }
437 return copy;
438}
439
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700440bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
441 // Done only if all required AllocationSequence objects
442 // are created.
443 if (!allocation_sequences_created_) {
444 return false;
445 }
446
447 // Check that all port allocation sequences are complete (not running).
448 if (std::any_of(sequences_.begin(), sequences_.end(),
449 [](const AllocationSequence* sequence) {
450 return sequence->state() == AllocationSequence::kRunning;
451 })) {
452 return false;
453 }
454
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700455 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700456 // expected candidates. Session will trigger candidates allocation complete
457 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700458 return std::none_of(ports_.begin(), ports_.end(),
459 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700460}
461
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
463 switch (message->message_id) {
464 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800465 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 GetPortConfigurations();
467 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000468 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800469 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000470 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
471 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800473 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 OnAllocate();
475 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800477 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 OnAllocationSequenceObjectsCreated();
479 break;
480 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800481 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000482 OnConfigStop();
483 break;
484 default:
nissec80e7412017-01-11 05:56:46 -0800485 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000486 }
487}
488
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700489void BasicPortAllocatorSession::UpdateIceParametersInternal() {
490 for (PortData& port : ports_) {
491 port.port()->set_content_name(content_name());
492 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
493 }
494}
495
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496void BasicPortAllocatorSession::GetPortConfigurations() {
497 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
498 username(),
499 password());
500
deadbeef653b8e02015-11-11 12:55:10 -0800501 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
502 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000503 }
504 ConfigReady(config);
505}
506
507void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700508 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000509}
510
511// Adds a configuration to the list.
512void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800513 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000514 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800515 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000516
517 AllocatePorts();
518}
519
520void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800521 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000522
523 // If any of the allocated ports have not completed the candidates allocation,
524 // mark those as error. Since session doesn't need any new candidates
525 // at this stage of the allocation, it's safe to discard any new candidates.
526 bool send_signal = false;
527 for (std::vector<PortData>::iterator it = ports_.begin();
528 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700529 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 // Updating port state to error, which didn't finish allocating candidates
531 // yet.
532 it->set_error();
533 send_signal = true;
534 }
535 }
536
537 // Did we stop any running sequences?
538 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
539 it != sequences_.end() && !send_signal; ++it) {
540 if ((*it)->state() == AllocationSequence::kStopped) {
541 send_signal = true;
542 }
543 }
544
545 // If we stopped anything that was running, send a done signal now.
546 if (send_signal) {
547 MaybeSignalCandidatesAllocationDone();
548 }
549}
550
551void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800552 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700553 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554}
555
556void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700557 if (network_manager_started_ && !IsStopped()) {
558 bool disable_equivalent_phases = true;
559 DoAllocate(disable_equivalent_phases);
560 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000561
562 allocation_started_ = true;
563}
564
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700565std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
566 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700567 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800568 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700569 // If the network permission state is BLOCKED, we just act as if the flag has
570 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700571 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700572 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700573 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
574 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000575 // If the adapter enumeration is disabled, we'll just bind to any address
576 // instead of specific NIC. This is to ensure the same routing for http
577 // traffic by OS is also used here to avoid any local or public IP leakage
578 // during stun process.
579 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700580 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000581 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700582 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800583 // If network enumeration fails, use the ANY address as a fallback, so we
584 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700585 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
586 // set, we'll use ANY address candidates either way.
587 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800588 network_manager->GetAnyAddressNetworks(&networks);
589 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000590 }
deadbeef3427f532017-07-26 16:09:33 -0700591 // Do some more filtering, depending on the network ignore mask and "disable
592 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700593 networks.erase(std::remove_if(networks.begin(), networks.end(),
594 [this](rtc::Network* network) {
595 return allocator_->network_ignore_mask() &
596 network->type();
597 }),
598 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700599 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
600 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700601 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700602 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
603 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700604 networks.erase(std::remove_if(networks.begin(), networks.end(),
605 [lowest_cost](rtc::Network* network) {
606 return network->GetCost() >
607 lowest_cost + rtc::kNetworkCostLow;
608 }),
609 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700610 }
deadbeef3427f532017-07-26 16:09:33 -0700611 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
612 // default, it's 5), remove networks to ensure that limit is satisfied.
613 //
614 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
615 // networks, we could try to choose a set that's "most likely to work". It's
616 // hard to define what that means though; it's not just "lowest cost".
617 // Alternatively, we could just focus on making our ICE pinging logic smarter
618 // such that this filtering isn't necessary in the first place.
619 int ipv6_networks = 0;
620 for (auto it = networks.begin(); it != networks.end();) {
621 if ((*it)->prefix().family() == AF_INET6) {
622 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
623 it = networks.erase(it);
624 continue;
625 } else {
626 ++ipv6_networks;
627 }
628 }
629 ++it;
630 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700631 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700632}
633
634// For each network, see if we have a sequence that covers it already. If not,
635// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700636void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700637 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700638 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 if (networks.empty()) {
640 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
641 done_signal_needed = true;
642 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700643 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700644 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200645 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200646 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000647 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
648 // If all the ports are disabled we should just fire the allocation
649 // done event and return.
650 done_signal_needed = true;
651 break;
652 }
653
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000654 if (!config || config->relays.empty()) {
655 // No relay ports specified in this config.
656 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
657 }
658
659 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661 // Skip IPv6 networks unless the flag's been set.
662 continue;
663 }
664
zhihuangb09b3f92017-03-07 14:40:51 -0800665 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
666 networks[i]->GetBestIP().family() == AF_INET6 &&
667 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
668 // Skip IPv6 Wi-Fi networks unless the flag's been set.
669 continue;
670 }
671
Steve Anton300bf8e2017-07-14 10:13:10 -0700672 if (disable_equivalent) {
673 // Disable phases that would only create ports equivalent to
674 // ones that we have already made.
675 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000676
Steve Anton300bf8e2017-07-14 10:13:10 -0700677 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
678 // New AllocationSequence would have nothing to do, so don't make it.
679 continue;
680 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000681 }
682
683 AllocationSequence* sequence =
684 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 sequence->SignalPortAllocationComplete.connect(
686 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700687 sequence->Init();
688 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700690 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691 }
692 }
693 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700694 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695 }
696}
697
698void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700699 std::vector<rtc::Network*> networks = GetNetworks();
700 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700701 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700702 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700703 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700704 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700705 std::find(networks.begin(), networks.end(), sequence->network()) ==
706 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700707 sequence->OnNetworkFailed();
708 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700709 }
710 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700711 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
712 if (!ports_to_prune.empty()) {
713 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
714 << " ports because their networks were gone";
715 PrunePortsAndRemoveCandidates(ports_to_prune);
716 }
honghaiz8c404fa2015-09-28 07:59:43 -0700717
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700718 if (allocation_started_ && !IsStopped()) {
719 if (network_manager_started_) {
720 // If the network manager has started, it must be regathering.
721 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
722 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700723 bool disable_equivalent_phases = true;
724 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700725 }
726
Honghai Zhang5048f572016-08-23 15:47:33 -0700727 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700728 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700729 network_manager_started_ = true;
730 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731}
732
733void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200734 rtc::Network* network,
735 PortConfiguration* config,
736 uint32_t* flags) {
737 for (uint32_t i = 0; i < sequences_.size() &&
738 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
739 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000740 sequences_[i]->DisableEquivalentPhases(network, config, flags);
741 }
742}
743
744void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
745 AllocationSequence * seq,
746 bool prepare_address) {
747 if (!port)
748 return;
749
750 LOG(LS_INFO) << "Adding allocated port for " << content_name();
751 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700752 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700754 if (allocator_->proxy().type != rtc::PROXY_NONE)
755 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700756 port->set_send_retransmit_count_attribute(
757 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000759 PortData data(port, seq);
760 ports_.push_back(data);
761
762 port->SignalCandidateReady.connect(
763 this, &BasicPortAllocatorSession::OnCandidateReady);
764 port->SignalPortComplete.connect(this,
765 &BasicPortAllocatorSession::OnPortComplete);
766 port->SignalDestroyed.connect(this,
767 &BasicPortAllocatorSession::OnPortDestroyed);
768 port->SignalPortError.connect(
769 this, &BasicPortAllocatorSession::OnPortError);
770 LOG_J(LS_INFO, port) << "Added port to allocator";
771
772 if (prepare_address)
773 port->PrepareAddress();
774}
775
776void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
777 allocation_sequences_created_ = true;
778 // Send candidate allocation complete signal if we have no sequences.
779 MaybeSignalCandidatesAllocationDone();
780}
781
782void BasicPortAllocatorSession::OnCandidateReady(
783 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800784 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000785 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800786 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700787 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000788 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700789 // already done with gathering.
790 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700791 LOG(LS_WARNING)
792 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700793 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700794 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700795
danilchapf4e8cf02016-06-30 01:55:03 -0700796 // Mark that the port has a pairable candidate, either because we have a
797 // usable candidate from the port, or simply because the port is bound to the
798 // any address and therefore has no host candidate. This will trigger the port
799 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700800 // checks. If port has already been marked as having a pairable candidate,
801 // do nothing here.
802 // Note: We should check whether any candidates may become ready after this
803 // because there we will check whether the candidate is generated by the ready
804 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700805 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700806 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700807 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700808
809 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700810 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700811 }
812 // If the current port is not pruned yet, SignalPortReady.
813 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700814 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700815 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700816 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700817 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700818 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700819
820 ProtocolType pvalue;
821 bool candidate_protocol_enabled =
822 StringToProto(c.protocol().c_str(), &pvalue) &&
823 data->sequence()->ProtocolEnabled(pvalue);
824
825 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
826 std::vector<Candidate> candidates;
827 candidates.push_back(SanitizeRelatedAddress(c));
828 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700829 } else if (!candidate_protocol_enabled) {
830 LOG(LS_INFO)
831 << "Not yet signaling candidate because protocol is not yet enabled.";
832 } else {
833 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700834 }
835
836 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700837 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700838 MaybeSignalCandidatesAllocationDone();
839 }
840}
841
842Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
843 const std::string& network_name) const {
844 Port* best_turn_port = nullptr;
845 for (const PortData& data : ports_) {
846 if (data.port()->Network()->name() == network_name &&
847 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
848 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
849 best_turn_port = data.port();
850 }
851 }
852 return best_turn_port;
853}
854
855bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700856 // Note: We determine the same network based only on their network names. So
857 // if an IPv4 address and an IPv6 address have the same network name, they
858 // are considered the same network here.
859 const std::string& network_name = newly_pairable_turn_port->Network()->name();
860 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
861 // |port| is already in the list of ports, so the best port cannot be nullptr.
862 RTC_CHECK(best_turn_port != nullptr);
863
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700864 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700865 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700866 for (PortData& data : ports_) {
867 if (data.port()->Network()->name() == network_name &&
868 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
869 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700870 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700871 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700872 // These ports will be pruned in PrunePortsAndRemoveCandidates.
873 ports_to_prune.push_back(&data);
874 } else {
875 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700876 }
877 }
878 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700879
880 if (!ports_to_prune.empty()) {
881 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
882 << " low-priority TURN ports";
883 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700884 }
885 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000886}
887
Honghai Zhanga74363c2016-07-28 18:06:15 -0700888void BasicPortAllocatorSession::PruneAllPorts() {
889 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700890 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700891 }
892}
893
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000894void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800895 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700896 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800898 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000899
900 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700901 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700903 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904
905 // Moving to COMPLETE state.
906 data->set_complete();
907 // Send candidate allocation complete signal if this was the last port.
908 MaybeSignalCandidatesAllocationDone();
909}
910
911void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800912 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700913 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800915 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700917 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700919 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920
921 // SignalAddressError is currently sent from StunPort/TurnPort.
922 // But this signal itself is generic.
923 data->set_error();
924 // Send candidate allocation complete signal if this was the last port.
925 MaybeSignalCandidatesAllocationDone();
926}
927
928void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
929 ProtocolType proto) {
930 std::vector<Candidate> candidates;
931 for (std::vector<PortData>::iterator it = ports_.begin();
932 it != ports_.end(); ++it) {
933 if (it->sequence() != seq)
934 continue;
935
936 const std::vector<Candidate>& potentials = it->port()->Candidates();
937 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700938 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700940 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000941 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700942 bool candidate_protocol_enabled =
943 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
944 pvalue == proto;
945 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700946 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
947 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000948 candidates.push_back(potentials[i]);
949 }
950 }
951 }
952
953 if (!candidates.empty()) {
954 SignalCandidatesReady(this, candidates);
955 }
956}
957
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700958bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700959 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000960
961 // When binding to any address, before sending packets out, the getsockname
962 // returns all 0s, but after sending packets, it'll be the NIC used to
963 // send. All 0s is not a valid ICE candidate address and should be filtered
964 // out.
965 if (c.address().IsAnyIP()) {
966 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967 }
968
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000969 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000970 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000971 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000972 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000973 } else if (c.type() == LOCAL_PORT_TYPE) {
974 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
975 // We allow host candidates if the filter allows server-reflexive
976 // candidates and the candidate is a public IP. Because we don't generate
977 // server-reflexive candidates if they have the same IP as the host
978 // candidate (i.e. when the host candidate is a public IP), filtering to
979 // only server-reflexive candidates won't work right when the host
980 // candidates have public IPs.
981 return true;
982 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000983
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000984 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000985 }
986 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000987}
988
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700989bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
990 const Port* port) const {
991 bool candidate_signalable = CheckCandidateFilter(c);
992
993 // When device enumeration is disabled (to prevent non-default IP addresses
994 // from leaking), we ping from some local candidates even though we don't
995 // signal them. However, if host candidates are also disabled (for example, to
996 // prevent even default IP addresses from leaking), we still don't want to
997 // ping from them, even if device enumeration is disabled. Thus, we check for
998 // both device enumeration and host candidates being disabled.
999 bool network_enumeration_disabled = c.address().IsAnyIP();
1000 bool can_ping_from_candidate =
1001 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1002 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1003
1004 return candidate_signalable ||
1005 (network_enumeration_disabled && can_ping_from_candidate &&
1006 !host_candidates_disabled);
1007}
1008
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009void BasicPortAllocatorSession::OnPortAllocationComplete(
1010 AllocationSequence* seq) {
1011 // Send candidate allocation complete signal if all ports are done.
1012 MaybeSignalCandidatesAllocationDone();
1013}
1014
1015void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001016 if (CandidatesAllocationDone()) {
1017 if (pooled()) {
1018 LOG(LS_INFO) << "All candidates gathered for pooled session.";
1019 } else {
1020 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
1021 << component() << ":" << generation();
1022 }
1023 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001024 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001025}
1026
1027void BasicPortAllocatorSession::OnPortDestroyed(
1028 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001029 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030 for (std::vector<PortData>::iterator iter = ports_.begin();
1031 iter != ports_.end(); ++iter) {
1032 if (port == iter->port()) {
1033 ports_.erase(iter);
1034 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1035 << static_cast<int>(ports_.size()) << " remaining)";
1036 return;
1037 }
1038 }
nissec80e7412017-01-11 05:56:46 -08001039 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040}
1041
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001042BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1043 Port* port) {
1044 for (std::vector<PortData>::iterator it = ports_.begin();
1045 it != ports_.end(); ++it) {
1046 if (it->port() == port) {
1047 return &*it;
1048 }
1049 }
1050 return NULL;
1051}
1052
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001053std::vector<BasicPortAllocatorSession::PortData*>
1054BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001055 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001056 std::vector<PortData*> unpruned_ports;
1057 for (PortData& port : ports_) {
1058 if (!port.pruned() &&
1059 std::find(networks.begin(), networks.end(),
1060 port.sequence()->network()) != networks.end()) {
1061 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001062 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001063 }
1064 return unpruned_ports;
1065}
1066
1067void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1068 const std::vector<PortData*>& port_data_list) {
1069 std::vector<PortInterface*> pruned_ports;
1070 std::vector<Candidate> removed_candidates;
1071 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001072 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001073 data->Prune();
1074 pruned_ports.push_back(data->port());
1075 if (data->has_pairable_candidate()) {
1076 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001077 // Mark the port as having no pairable candidates so that its candidates
1078 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001079 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001080 }
1081 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001082 if (!pruned_ports.empty()) {
1083 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001084 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001085 if (!removed_candidates.empty()) {
1086 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1087 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001088 }
1089}
1090
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001091// AllocationSequence
1092
1093AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1094 rtc::Network* network,
1095 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001096 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 : session_(session),
1098 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001099 config_(config),
1100 state_(kInit),
1101 flags_(flags),
1102 udp_socket_(),
1103 udp_port_(NULL),
1104 phase_(0) {
1105}
1106
Honghai Zhang5048f572016-08-23 15:47:33 -07001107void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001108 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1109 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001110 rtc::SocketAddress(network_->GetBestIP(), 0),
1111 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112 if (udp_socket_) {
1113 udp_socket_->SignalReadPacket.connect(
1114 this, &AllocationSequence::OnReadPacket);
1115 }
1116 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1117 // are next available options to setup a communication channel.
1118 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001119}
1120
1121void AllocationSequence::Clear() {
1122 udp_port_ = NULL;
1123 turn_ports_.clear();
1124}
1125
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001126void AllocationSequence::OnNetworkFailed() {
1127 RTC_DCHECK(!network_failed_);
1128 network_failed_ = true;
1129 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001130 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001131}
1132
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133AllocationSequence::~AllocationSequence() {
1134 session_->network_thread()->Clear(this);
1135}
1136
1137void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001138 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001139 if (network_failed_) {
1140 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001141 // it won't be equivalent to the new network.
1142 return;
1143 }
1144
deadbeef5c3c1042017-08-04 15:01:57 -07001145 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001146 // Different network setup; nothing is equivalent.
1147 return;
1148 }
1149
1150 // Else turn off the stuff that we've already got covered.
1151
1152 // Every config implicitly specifies local, so turn that off right away.
1153 *flags |= PORTALLOCATOR_DISABLE_UDP;
1154 *flags |= PORTALLOCATOR_DISABLE_TCP;
1155
1156 if (config_ && config) {
1157 if (config_->StunServers() == config->StunServers()) {
1158 // Already got this STUN servers covered.
1159 *flags |= PORTALLOCATOR_DISABLE_STUN;
1160 }
1161 if (!config_->relays.empty()) {
1162 // Already got relays covered.
1163 // NOTE: This will even skip a _different_ set of relay servers if we
1164 // were to be given one, but that never happens in our codebase. Should
1165 // probably get rid of the list in PortConfiguration and just keep a
1166 // single relay server in each one.
1167 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1168 }
1169 }
1170}
1171
1172void AllocationSequence::Start() {
1173 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001174 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001175 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1176 // called next time, we enable all phases if the best IP has since changed.
1177 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178}
1179
1180void AllocationSequence::Stop() {
1181 // If the port is completed, don't set it to stopped.
1182 if (state_ == kRunning) {
1183 state_ = kStopped;
1184 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1185 }
1186}
1187
1188void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001189 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1190 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191
1192 const char* const PHASE_NAMES[kNumPhases] = {
1193 "Udp", "Relay", "Tcp", "SslTcp"
1194 };
1195
1196 // Perform all of the phases in the current step.
1197 LOG_J(LS_INFO, network_) << "Allocation Phase="
1198 << PHASE_NAMES[phase_];
1199
1200 switch (phase_) {
1201 case PHASE_UDP:
1202 CreateUDPPorts();
1203 CreateStunPorts();
1204 EnableProtocol(PROTO_UDP);
1205 break;
1206
1207 case PHASE_RELAY:
1208 CreateRelayPorts();
1209 break;
1210
1211 case PHASE_TCP:
1212 CreateTCPPorts();
1213 EnableProtocol(PROTO_TCP);
1214 break;
1215
1216 case PHASE_SSLTCP:
1217 state_ = kCompleted;
1218 EnableProtocol(PROTO_SSLTCP);
1219 break;
1220
1221 default:
nissec80e7412017-01-11 05:56:46 -08001222 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001223 }
1224
1225 if (state() == kRunning) {
1226 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001227 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1228 session_->allocator()->step_delay(),
1229 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001230 } else {
1231 // If all phases in AllocationSequence are completed, no allocation
1232 // steps needed further. Canceling pending signal.
1233 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1234 SignalPortAllocationComplete(this);
1235 }
1236}
1237
1238void AllocationSequence::EnableProtocol(ProtocolType proto) {
1239 if (!ProtocolEnabled(proto)) {
1240 protocols_.push_back(proto);
1241 session_->OnProtocolEnabled(this, proto);
1242 }
1243}
1244
1245bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1246 for (ProtocolList::const_iterator it = protocols_.begin();
1247 it != protocols_.end(); ++it) {
1248 if (*it == proto)
1249 return true;
1250 }
1251 return false;
1252}
1253
1254void AllocationSequence::CreateUDPPorts() {
1255 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1256 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1257 return;
1258 }
1259
1260 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1261 // is enabled completely.
1262 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001263 bool emit_local_candidate_for_anyaddress =
1264 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001265 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001266 port = UDPPort::Create(
1267 session_->network_thread(), session_->socket_factory(), network_,
1268 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001269 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001271 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001272 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001273 session_->allocator()->min_port(), session_->allocator()->max_port(),
1274 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 }
1277
1278 if (port) {
1279 // If shared socket is enabled, STUN candidate will be allocated by the
1280 // UDPPort.
1281 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1282 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001283 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001284
1285 // If STUN is not disabled, setting stun server address to port.
1286 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001287 if (config_ && !config_->StunServers().empty()) {
1288 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1289 << "STUN candidate generation.";
1290 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001291 }
1292 }
1293 }
1294
1295 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001296 }
1297}
1298
1299void AllocationSequence::CreateTCPPorts() {
1300 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1301 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1302 return;
1303 }
1304
deadbeef5c3c1042017-08-04 15:01:57 -07001305 Port* port = TCPPort::Create(
1306 session_->network_thread(), session_->socket_factory(), network_,
1307 session_->allocator()->min_port(), session_->allocator()->max_port(),
1308 session_->username(), session_->password(),
1309 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001310 if (port) {
1311 session_->AddAllocatedPort(port, this, true);
1312 // Since TCPPort is not created using shared socket, |port| will not be
1313 // added to the dequeue.
1314 }
1315}
1316
1317void AllocationSequence::CreateStunPorts() {
1318 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1319 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1320 return;
1321 }
1322
1323 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1324 return;
1325 }
1326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001327 if (!(config_ && !config_->StunServers().empty())) {
1328 LOG(LS_WARNING)
1329 << "AllocationSequence: No STUN server configured, skipping.";
1330 return;
1331 }
1332
deadbeef5c3c1042017-08-04 15:01:57 -07001333 StunPort* port = StunPort::Create(
1334 session_->network_thread(), session_->socket_factory(), network_,
1335 session_->allocator()->min_port(), session_->allocator()->max_port(),
1336 session_->username(), session_->password(), config_->StunServers(),
1337 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001338 if (port) {
1339 session_->AddAllocatedPort(port, this, true);
1340 // Since StunPort is not created using shared socket, |port| will not be
1341 // added to the dequeue.
1342 }
1343}
1344
1345void AllocationSequence::CreateRelayPorts() {
1346 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1347 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1348 return;
1349 }
1350
1351 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1352 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001353 RTC_DCHECK(config_);
1354 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001355 if (!(config_ && !config_->relays.empty())) {
1356 LOG(LS_WARNING)
1357 << "AllocationSequence: No relay server configured, skipping.";
1358 return;
1359 }
1360
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001361 for (RelayServerConfig& relay : config_->relays) {
1362 if (relay.type == RELAY_GTURN) {
1363 CreateGturnPort(relay);
1364 } else if (relay.type == RELAY_TURN) {
1365 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001366 } else {
nissec80e7412017-01-11 05:56:46 -08001367 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001368 }
1369 }
1370}
1371
1372void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1373 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001374 RelayPort* port = RelayPort::Create(
1375 session_->network_thread(), session_->socket_factory(), network_,
1376 session_->allocator()->min_port(), session_->allocator()->max_port(),
1377 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378 if (port) {
1379 // Since RelayPort is not created using shared socket, |port| will not be
1380 // added to the dequeue.
1381 // Note: We must add the allocated port before we add addresses because
1382 // the latter will create candidates that need name and preference
1383 // settings. However, we also can't prepare the address (normally
1384 // done by AddAllocatedPort) until we have these addresses. So we
1385 // wait to do that until below.
1386 session_->AddAllocatedPort(port, this, false);
1387
1388 // Add the addresses of this protocol.
1389 PortList::const_iterator relay_port;
1390 for (relay_port = config.ports.begin();
1391 relay_port != config.ports.end();
1392 ++relay_port) {
1393 port->AddServerAddress(*relay_port);
1394 port->AddExternalAddress(*relay_port);
1395 }
1396 // Start fetching an address for this port.
1397 port->PrepareAddress();
1398 }
1399}
1400
1401void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1402 PortList::const_iterator relay_port;
1403 for (relay_port = config.ports.begin();
1404 relay_port != config.ports.end(); ++relay_port) {
1405 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001406
1407 // Skip UDP connections to relay servers if it's disallowed.
1408 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1409 relay_port->proto == PROTO_UDP) {
1410 continue;
1411 }
1412
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001413 // Do not create a port if the server address family is known and does
1414 // not match the local IP address family.
1415 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001416 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001417 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1418 LOG(LS_INFO) << "Server and local address families are not compatible. "
1419 << "Server address: "
1420 << relay_port->address.ipaddr().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -07001421 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001422 continue;
1423 }
1424
1425
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426 // Shared socket mode must be enabled only for UDP based ports. Hence
1427 // don't pass shared socket for ports which will create TCP sockets.
1428 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1429 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1430 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001431 relay_port->proto == PROTO_UDP && udp_socket_) {
maxmorine9ef9072017-08-29 04:49:00 -07001432 port = TurnPort::Create(session_->network_thread(),
1433 session_->socket_factory(),
1434 network_, udp_socket_.get(),
1435 session_->username(), session_->password(),
1436 *relay_port, config.credentials, config.priority,
1437 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001438 turn_ports_.push_back(port);
1439 // Listen to the port destroyed signal, to allow AllocationSequence to
1440 // remove entrt from it's map.
1441 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1442 } else {
deadbeef5c3c1042017-08-04 15:01:57 -07001443 port = TurnPort::Create(
1444 session_->network_thread(), session_->socket_factory(), network_,
1445 session_->allocator()->min_port(), session_->allocator()->max_port(),
1446 session_->username(), session_->password(), *relay_port,
Diogo Real1dca9d52017-08-29 12:18:32 -07001447 config.credentials, config.priority, session_->allocator()->origin(),
Diogo Real7bd1f1b2017-09-08 12:50:41 -07001448 config.tls_alpn_protocols, config.tls_elliptic_curves);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001449 }
nisseede5da42017-01-12 05:15:36 -08001450 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001451 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001452 session_->AddAllocatedPort(port, this, true);
1453 }
1454}
1455
1456void AllocationSequence::OnReadPacket(
1457 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1458 const rtc::SocketAddress& remote_addr,
1459 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001460 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001461
1462 bool turn_port_found = false;
1463
1464 // Try to find the TurnPort that matches the remote address. Note that the
1465 // message could be a STUN binding response if the TURN server is also used as
1466 // a STUN server. We don't want to parse every message here to check if it is
1467 // a STUN binding response, so we pass the message to TurnPort regardless of
1468 // the message type. The TurnPort will just ignore the message since it will
1469 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001470 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001471 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001472 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1473 packet_time)) {
1474 return;
1475 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001476 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001477 }
1478 }
1479
1480 if (udp_port_) {
1481 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1482
1483 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1484 // the TURN server is also a STUN server.
1485 if (!turn_port_found ||
1486 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001487 RTC_DCHECK(udp_port_->SharedSocket());
1488 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1489 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001490 }
1491 }
1492}
1493
1494void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1495 if (udp_port_ == port) {
1496 udp_port_ = NULL;
1497 return;
1498 }
1499
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001500 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1501 if (it != turn_ports_.end()) {
1502 turn_ports_.erase(it);
1503 } else {
1504 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001505 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001506 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001507}
1508
1509// PortConfiguration
1510PortConfiguration::PortConfiguration(
1511 const rtc::SocketAddress& stun_address,
1512 const std::string& username,
1513 const std::string& password)
1514 : stun_address(stun_address), username(username), password(password) {
1515 if (!stun_address.IsNil())
1516 stun_servers.insert(stun_address);
1517}
1518
1519PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1520 const std::string& username,
1521 const std::string& password)
1522 : stun_servers(stun_servers),
1523 username(username),
1524 password(password) {
1525 if (!stun_servers.empty())
1526 stun_address = *(stun_servers.begin());
1527}
1528
1529ServerAddresses PortConfiguration::StunServers() {
1530 if (!stun_address.IsNil() &&
1531 stun_servers.find(stun_address) == stun_servers.end()) {
1532 stun_servers.insert(stun_address);
1533 }
deadbeefc5d0d952015-07-16 10:22:21 -07001534 // Every UDP TURN server should also be used as a STUN server.
1535 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1536 for (const rtc::SocketAddress& turn_server : turn_servers) {
1537 if (stun_servers.find(turn_server) == stun_servers.end()) {
1538 stun_servers.insert(turn_server);
1539 }
1540 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001541 return stun_servers;
1542}
1543
1544void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1545 relays.push_back(config);
1546}
1547
1548bool PortConfiguration::SupportsProtocol(
1549 const RelayServerConfig& relay, ProtocolType type) const {
1550 PortList::const_iterator relay_port;
1551 for (relay_port = relay.ports.begin();
1552 relay_port != relay.ports.end();
1553 ++relay_port) {
1554 if (relay_port->proto == type)
1555 return true;
1556 }
1557 return false;
1558}
1559
1560bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1561 ProtocolType type) const {
1562 for (size_t i = 0; i < relays.size(); ++i) {
1563 if (relays[i].type == turn_type &&
1564 SupportsProtocol(relays[i], type))
1565 return true;
1566 }
1567 return false;
1568}
1569
1570ServerAddresses PortConfiguration::GetRelayServerAddresses(
1571 RelayType turn_type, ProtocolType type) const {
1572 ServerAddresses servers;
1573 for (size_t i = 0; i < relays.size(); ++i) {
1574 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1575 servers.insert(relays[i].ports.front().address);
1576 }
1577 }
1578 return servers;
1579}
1580
1581} // namespace cricket