blob: 2970987900b1390c956e45a5b775cc008ecbc9b3 [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,
101 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)
Taylor Brandstettera1c30352016-05-13 08:15:11 -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)
117 : 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)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700129 : network_manager_(network_manager), socket_factory_(NULL) {
130 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 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700591 networks.erase(std::remove_if(networks.begin(), networks.end(),
592 [this](rtc::Network* network) {
593 return allocator_->network_ignore_mask() &
594 network->type();
595 }),
596 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700597
598 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
599 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700600 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700601 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
602 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700603 networks.erase(std::remove_if(networks.begin(), networks.end(),
604 [lowest_cost](rtc::Network* network) {
605 return network->GetCost() >
606 lowest_cost + rtc::kNetworkCostLow;
607 }),
608 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700609 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700610 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700611}
612
613// For each network, see if we have a sequence that covers it already. If not,
614// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700615void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700616 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700617 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000618 if (networks.empty()) {
619 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
620 done_signal_needed = true;
621 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700622 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700623 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200624 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200625 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
627 // If all the ports are disabled we should just fire the allocation
628 // done event and return.
629 done_signal_needed = true;
630 break;
631 }
632
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633 if (!config || config->relays.empty()) {
634 // No relay ports specified in this config.
635 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
636 }
637
638 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640 // Skip IPv6 networks unless the flag's been set.
641 continue;
642 }
643
zhihuangb09b3f92017-03-07 14:40:51 -0800644 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
645 networks[i]->GetBestIP().family() == AF_INET6 &&
646 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
647 // Skip IPv6 Wi-Fi networks unless the flag's been set.
648 continue;
649 }
650
Steve Anton300bf8e2017-07-14 10:13:10 -0700651 if (disable_equivalent) {
652 // Disable phases that would only create ports equivalent to
653 // ones that we have already made.
654 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000655
Steve Anton300bf8e2017-07-14 10:13:10 -0700656 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
657 // New AllocationSequence would have nothing to do, so don't make it.
658 continue;
659 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 }
661
662 AllocationSequence* sequence =
663 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664 sequence->SignalPortAllocationComplete.connect(
665 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700666 sequence->Init();
667 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000668 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700669 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670 }
671 }
672 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700673 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000674 }
675}
676
677void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700678 std::vector<rtc::Network*> networks = GetNetworks();
679 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700680 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700681 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700682 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700683 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700684 std::find(networks.begin(), networks.end(), sequence->network()) ==
685 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700686 sequence->OnNetworkFailed();
687 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700688 }
689 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700690 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
691 if (!ports_to_prune.empty()) {
692 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
693 << " ports because their networks were gone";
694 PrunePortsAndRemoveCandidates(ports_to_prune);
695 }
honghaiz8c404fa2015-09-28 07:59:43 -0700696
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700697 if (allocation_started_ && !IsStopped()) {
698 if (network_manager_started_) {
699 // If the network manager has started, it must be regathering.
700 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
701 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700702 bool disable_equivalent_phases = true;
703 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700704 }
705
Honghai Zhang5048f572016-08-23 15:47:33 -0700706 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700707 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700708 network_manager_started_ = true;
709 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000710}
711
712void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200713 rtc::Network* network,
714 PortConfiguration* config,
715 uint32_t* flags) {
716 for (uint32_t i = 0; i < sequences_.size() &&
717 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
718 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000719 sequences_[i]->DisableEquivalentPhases(network, config, flags);
720 }
721}
722
723void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
724 AllocationSequence * seq,
725 bool prepare_address) {
726 if (!port)
727 return;
728
729 LOG(LS_INFO) << "Adding allocated port for " << content_name();
730 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700731 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000732 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700733 if (allocator_->proxy().type != rtc::PROXY_NONE)
734 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700735 port->set_send_retransmit_count_attribute(
736 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 PortData data(port, seq);
739 ports_.push_back(data);
740
741 port->SignalCandidateReady.connect(
742 this, &BasicPortAllocatorSession::OnCandidateReady);
743 port->SignalPortComplete.connect(this,
744 &BasicPortAllocatorSession::OnPortComplete);
745 port->SignalDestroyed.connect(this,
746 &BasicPortAllocatorSession::OnPortDestroyed);
747 port->SignalPortError.connect(
748 this, &BasicPortAllocatorSession::OnPortError);
749 LOG_J(LS_INFO, port) << "Added port to allocator";
750
751 if (prepare_address)
752 port->PrepareAddress();
753}
754
755void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
756 allocation_sequences_created_ = true;
757 // Send candidate allocation complete signal if we have no sequences.
758 MaybeSignalCandidatesAllocationDone();
759}
760
761void BasicPortAllocatorSession::OnCandidateReady(
762 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800763 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000764 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800765 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700766 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000767 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700768 // already done with gathering.
769 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700770 LOG(LS_WARNING)
771 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700772 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700773 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700774
danilchapf4e8cf02016-06-30 01:55:03 -0700775 // Mark that the port has a pairable candidate, either because we have a
776 // usable candidate from the port, or simply because the port is bound to the
777 // any address and therefore has no host candidate. This will trigger the port
778 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700779 // checks. If port has already been marked as having a pairable candidate,
780 // do nothing here.
781 // Note: We should check whether any candidates may become ready after this
782 // because there we will check whether the candidate is generated by the ready
783 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700784 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700785 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700786 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700787
788 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700789 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700790 }
791 // If the current port is not pruned yet, SignalPortReady.
792 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700793 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700794 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700795 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700796 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700797 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700798
799 ProtocolType pvalue;
800 bool candidate_protocol_enabled =
801 StringToProto(c.protocol().c_str(), &pvalue) &&
802 data->sequence()->ProtocolEnabled(pvalue);
803
804 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
805 std::vector<Candidate> candidates;
806 candidates.push_back(SanitizeRelatedAddress(c));
807 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700808 } else if (!candidate_protocol_enabled) {
809 LOG(LS_INFO)
810 << "Not yet signaling candidate because protocol is not yet enabled.";
811 } else {
812 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700813 }
814
815 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700816 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700817 MaybeSignalCandidatesAllocationDone();
818 }
819}
820
821Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
822 const std::string& network_name) const {
823 Port* best_turn_port = nullptr;
824 for (const PortData& data : ports_) {
825 if (data.port()->Network()->name() == network_name &&
826 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
827 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
828 best_turn_port = data.port();
829 }
830 }
831 return best_turn_port;
832}
833
834bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700835 // Note: We determine the same network based only on their network names. So
836 // if an IPv4 address and an IPv6 address have the same network name, they
837 // are considered the same network here.
838 const std::string& network_name = newly_pairable_turn_port->Network()->name();
839 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
840 // |port| is already in the list of ports, so the best port cannot be nullptr.
841 RTC_CHECK(best_turn_port != nullptr);
842
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700843 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700844 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700845 for (PortData& data : ports_) {
846 if (data.port()->Network()->name() == network_name &&
847 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
848 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700849 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700850 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700851 // These ports will be pruned in PrunePortsAndRemoveCandidates.
852 ports_to_prune.push_back(&data);
853 } else {
854 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700855 }
856 }
857 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700858
859 if (!ports_to_prune.empty()) {
860 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
861 << " low-priority TURN ports";
862 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700863 }
864 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000865}
866
Honghai Zhanga74363c2016-07-28 18:06:15 -0700867void BasicPortAllocatorSession::PruneAllPorts() {
868 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700869 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700870 }
871}
872
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000873void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800874 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700875 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800877 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000878
879 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700880 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700882 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000883
884 // Moving to COMPLETE state.
885 data->set_complete();
886 // Send candidate allocation complete signal if this was the last port.
887 MaybeSignalCandidatesAllocationDone();
888}
889
890void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800891 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700892 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800894 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700896 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700898 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000899
900 // SignalAddressError is currently sent from StunPort/TurnPort.
901 // But this signal itself is generic.
902 data->set_error();
903 // Send candidate allocation complete signal if this was the last port.
904 MaybeSignalCandidatesAllocationDone();
905}
906
907void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
908 ProtocolType proto) {
909 std::vector<Candidate> candidates;
910 for (std::vector<PortData>::iterator it = ports_.begin();
911 it != ports_.end(); ++it) {
912 if (it->sequence() != seq)
913 continue;
914
915 const std::vector<Candidate>& potentials = it->port()->Candidates();
916 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700917 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700919 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700921 bool candidate_protocol_enabled =
922 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
923 pvalue == proto;
924 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700925 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
926 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000927 candidates.push_back(potentials[i]);
928 }
929 }
930 }
931
932 if (!candidates.empty()) {
933 SignalCandidatesReady(this, candidates);
934 }
935}
936
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700937bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700938 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000939
940 // When binding to any address, before sending packets out, the getsockname
941 // returns all 0s, but after sending packets, it'll be the NIC used to
942 // send. All 0s is not a valid ICE candidate address and should be filtered
943 // out.
944 if (c.address().IsAnyIP()) {
945 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 }
947
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000948 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000949 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000950 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000951 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000952 } else if (c.type() == LOCAL_PORT_TYPE) {
953 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
954 // We allow host candidates if the filter allows server-reflexive
955 // candidates and the candidate is a public IP. Because we don't generate
956 // server-reflexive candidates if they have the same IP as the host
957 // candidate (i.e. when the host candidate is a public IP), filtering to
958 // only server-reflexive candidates won't work right when the host
959 // candidates have public IPs.
960 return true;
961 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000963 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000964 }
965 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000966}
967
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700968bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
969 const Port* port) const {
970 bool candidate_signalable = CheckCandidateFilter(c);
971
972 // When device enumeration is disabled (to prevent non-default IP addresses
973 // from leaking), we ping from some local candidates even though we don't
974 // signal them. However, if host candidates are also disabled (for example, to
975 // prevent even default IP addresses from leaking), we still don't want to
976 // ping from them, even if device enumeration is disabled. Thus, we check for
977 // both device enumeration and host candidates being disabled.
978 bool network_enumeration_disabled = c.address().IsAnyIP();
979 bool can_ping_from_candidate =
980 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
981 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
982
983 return candidate_signalable ||
984 (network_enumeration_disabled && can_ping_from_candidate &&
985 !host_candidates_disabled);
986}
987
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988void BasicPortAllocatorSession::OnPortAllocationComplete(
989 AllocationSequence* seq) {
990 // Send candidate allocation complete signal if all ports are done.
991 MaybeSignalCandidatesAllocationDone();
992}
993
994void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700995 if (CandidatesAllocationDone()) {
996 if (pooled()) {
997 LOG(LS_INFO) << "All candidates gathered for pooled session.";
998 } else {
999 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
1000 << component() << ":" << generation();
1001 }
1002 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001003 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001004}
1005
1006void BasicPortAllocatorSession::OnPortDestroyed(
1007 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -08001008 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001009 for (std::vector<PortData>::iterator iter = ports_.begin();
1010 iter != ports_.end(); ++iter) {
1011 if (port == iter->port()) {
1012 ports_.erase(iter);
1013 LOG_J(LS_INFO, port) << "Removed port from allocator ("
1014 << static_cast<int>(ports_.size()) << " remaining)";
1015 return;
1016 }
1017 }
nissec80e7412017-01-11 05:56:46 -08001018 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001019}
1020
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001021BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1022 Port* port) {
1023 for (std::vector<PortData>::iterator it = ports_.begin();
1024 it != ports_.end(); ++it) {
1025 if (it->port() == port) {
1026 return &*it;
1027 }
1028 }
1029 return NULL;
1030}
1031
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001032std::vector<BasicPortAllocatorSession::PortData*>
1033BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001034 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001035 std::vector<PortData*> unpruned_ports;
1036 for (PortData& port : ports_) {
1037 if (!port.pruned() &&
1038 std::find(networks.begin(), networks.end(),
1039 port.sequence()->network()) != networks.end()) {
1040 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001041 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001042 }
1043 return unpruned_ports;
1044}
1045
1046void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1047 const std::vector<PortData*>& port_data_list) {
1048 std::vector<PortInterface*> pruned_ports;
1049 std::vector<Candidate> removed_candidates;
1050 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001051 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001052 data->Prune();
1053 pruned_ports.push_back(data->port());
1054 if (data->has_pairable_candidate()) {
1055 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001056 // Mark the port as having no pairable candidates so that its candidates
1057 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001058 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001059 }
1060 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001061 if (!pruned_ports.empty()) {
1062 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001063 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001064 if (!removed_candidates.empty()) {
1065 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1066 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001067 }
1068}
1069
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001070// AllocationSequence
1071
1072AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1073 rtc::Network* network,
1074 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001075 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076 : session_(session),
1077 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001078 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001079 config_(config),
1080 state_(kInit),
1081 flags_(flags),
1082 udp_socket_(),
1083 udp_port_(NULL),
1084 phase_(0) {
1085}
1086
Honghai Zhang5048f572016-08-23 15:47:33 -07001087void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001088 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1089 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1090 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1091 session_->allocator()->max_port()));
1092 if (udp_socket_) {
1093 udp_socket_->SignalReadPacket.connect(
1094 this, &AllocationSequence::OnReadPacket);
1095 }
1096 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1097 // are next available options to setup a communication channel.
1098 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001099}
1100
1101void AllocationSequence::Clear() {
1102 udp_port_ = NULL;
1103 turn_ports_.clear();
1104}
1105
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001106void AllocationSequence::OnNetworkFailed() {
1107 RTC_DCHECK(!network_failed_);
1108 network_failed_ = true;
1109 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001110 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001111}
1112
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001113AllocationSequence::~AllocationSequence() {
1114 session_->network_thread()->Clear(this);
1115}
1116
1117void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001118 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001119 if (network_failed_) {
1120 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001121 // it won't be equivalent to the new network.
1122 return;
1123 }
1124
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001126 // Different network setup; nothing is equivalent.
1127 return;
1128 }
1129
1130 // Else turn off the stuff that we've already got covered.
1131
1132 // Every config implicitly specifies local, so turn that off right away.
1133 *flags |= PORTALLOCATOR_DISABLE_UDP;
1134 *flags |= PORTALLOCATOR_DISABLE_TCP;
1135
1136 if (config_ && config) {
1137 if (config_->StunServers() == config->StunServers()) {
1138 // Already got this STUN servers covered.
1139 *flags |= PORTALLOCATOR_DISABLE_STUN;
1140 }
1141 if (!config_->relays.empty()) {
1142 // Already got relays covered.
1143 // NOTE: This will even skip a _different_ set of relay servers if we
1144 // were to be given one, but that never happens in our codebase. Should
1145 // probably get rid of the list in PortConfiguration and just keep a
1146 // single relay server in each one.
1147 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1148 }
1149 }
1150}
1151
1152void AllocationSequence::Start() {
1153 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001154 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001155}
1156
1157void AllocationSequence::Stop() {
1158 // If the port is completed, don't set it to stopped.
1159 if (state_ == kRunning) {
1160 state_ = kStopped;
1161 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1162 }
1163}
1164
1165void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001166 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1167 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168
1169 const char* const PHASE_NAMES[kNumPhases] = {
1170 "Udp", "Relay", "Tcp", "SslTcp"
1171 };
1172
1173 // Perform all of the phases in the current step.
1174 LOG_J(LS_INFO, network_) << "Allocation Phase="
1175 << PHASE_NAMES[phase_];
1176
1177 switch (phase_) {
1178 case PHASE_UDP:
1179 CreateUDPPorts();
1180 CreateStunPorts();
1181 EnableProtocol(PROTO_UDP);
1182 break;
1183
1184 case PHASE_RELAY:
1185 CreateRelayPorts();
1186 break;
1187
1188 case PHASE_TCP:
1189 CreateTCPPorts();
1190 EnableProtocol(PROTO_TCP);
1191 break;
1192
1193 case PHASE_SSLTCP:
1194 state_ = kCompleted;
1195 EnableProtocol(PROTO_SSLTCP);
1196 break;
1197
1198 default:
nissec80e7412017-01-11 05:56:46 -08001199 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001200 }
1201
1202 if (state() == kRunning) {
1203 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001204 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1205 session_->allocator()->step_delay(),
1206 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001207 } else {
1208 // If all phases in AllocationSequence are completed, no allocation
1209 // steps needed further. Canceling pending signal.
1210 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1211 SignalPortAllocationComplete(this);
1212 }
1213}
1214
1215void AllocationSequence::EnableProtocol(ProtocolType proto) {
1216 if (!ProtocolEnabled(proto)) {
1217 protocols_.push_back(proto);
1218 session_->OnProtocolEnabled(this, proto);
1219 }
1220}
1221
1222bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1223 for (ProtocolList::const_iterator it = protocols_.begin();
1224 it != protocols_.end(); ++it) {
1225 if (*it == proto)
1226 return true;
1227 }
1228 return false;
1229}
1230
1231void AllocationSequence::CreateUDPPorts() {
1232 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1233 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1234 return;
1235 }
1236
1237 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1238 // is enabled completely.
1239 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001240 bool emit_local_candidate_for_anyaddress =
1241 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001242 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001243 port = UDPPort::Create(
1244 session_->network_thread(), session_->socket_factory(), network_,
1245 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001246 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001247 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001248 port = UDPPort::Create(
1249 session_->network_thread(), session_->socket_factory(), network_, ip_,
1250 session_->allocator()->min_port(), session_->allocator()->max_port(),
1251 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001252 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001253 }
1254
1255 if (port) {
1256 // If shared socket is enabled, STUN candidate will be allocated by the
1257 // UDPPort.
1258 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1259 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001260 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001261
1262 // If STUN is not disabled, setting stun server address to port.
1263 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001264 if (config_ && !config_->StunServers().empty()) {
1265 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1266 << "STUN candidate generation.";
1267 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001268 }
1269 }
1270 }
1271
1272 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 }
1274}
1275
1276void AllocationSequence::CreateTCPPorts() {
1277 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1278 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1279 return;
1280 }
1281
1282 Port* port = TCPPort::Create(session_->network_thread(),
1283 session_->socket_factory(),
1284 network_, ip_,
1285 session_->allocator()->min_port(),
1286 session_->allocator()->max_port(),
1287 session_->username(), session_->password(),
1288 session_->allocator()->allow_tcp_listen());
1289 if (port) {
1290 session_->AddAllocatedPort(port, this, true);
1291 // Since TCPPort is not created using shared socket, |port| will not be
1292 // added to the dequeue.
1293 }
1294}
1295
1296void AllocationSequence::CreateStunPorts() {
1297 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1298 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1299 return;
1300 }
1301
1302 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1303 return;
1304 }
1305
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306 if (!(config_ && !config_->StunServers().empty())) {
1307 LOG(LS_WARNING)
1308 << "AllocationSequence: No STUN server configured, skipping.";
1309 return;
1310 }
1311
1312 StunPort* port = StunPort::Create(session_->network_thread(),
1313 session_->socket_factory(),
1314 network_, ip_,
1315 session_->allocator()->min_port(),
1316 session_->allocator()->max_port(),
1317 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001318 config_->StunServers(),
1319 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001320 if (port) {
1321 session_->AddAllocatedPort(port, this, true);
1322 // Since StunPort is not created using shared socket, |port| will not be
1323 // added to the dequeue.
1324 }
1325}
1326
1327void AllocationSequence::CreateRelayPorts() {
1328 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1329 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1330 return;
1331 }
1332
1333 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1334 // ought to have a relay list for them here.
nisseede5da42017-01-12 05:15:36 -08001335 RTC_DCHECK(config_ && !config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336 if (!(config_ && !config_->relays.empty())) {
1337 LOG(LS_WARNING)
1338 << "AllocationSequence: No relay server configured, skipping.";
1339 return;
1340 }
1341
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001342 for (RelayServerConfig& relay : config_->relays) {
1343 if (relay.type == RELAY_GTURN) {
1344 CreateGturnPort(relay);
1345 } else if (relay.type == RELAY_TURN) {
1346 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001347 } else {
nissec80e7412017-01-11 05:56:46 -08001348 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001349 }
1350 }
1351}
1352
1353void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1354 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1355 RelayPort* port = RelayPort::Create(session_->network_thread(),
1356 session_->socket_factory(),
1357 network_, ip_,
1358 session_->allocator()->min_port(),
1359 session_->allocator()->max_port(),
1360 config_->username, config_->password);
1361 if (port) {
1362 // Since RelayPort is not created using shared socket, |port| will not be
1363 // added to the dequeue.
1364 // Note: We must add the allocated port before we add addresses because
1365 // the latter will create candidates that need name and preference
1366 // settings. However, we also can't prepare the address (normally
1367 // done by AddAllocatedPort) until we have these addresses. So we
1368 // wait to do that until below.
1369 session_->AddAllocatedPort(port, this, false);
1370
1371 // Add the addresses of this protocol.
1372 PortList::const_iterator relay_port;
1373 for (relay_port = config.ports.begin();
1374 relay_port != config.ports.end();
1375 ++relay_port) {
1376 port->AddServerAddress(*relay_port);
1377 port->AddExternalAddress(*relay_port);
1378 }
1379 // Start fetching an address for this port.
1380 port->PrepareAddress();
1381 }
1382}
1383
1384void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1385 PortList::const_iterator relay_port;
1386 for (relay_port = config.ports.begin();
1387 relay_port != config.ports.end(); ++relay_port) {
1388 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001389
1390 // Skip UDP connections to relay servers if it's disallowed.
1391 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1392 relay_port->proto == PROTO_UDP) {
1393 continue;
1394 }
1395
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001396 // Do not create a port if the server address family is known and does
1397 // not match the local IP address family.
1398 int server_ip_family = relay_port->address.ipaddr().family();
1399 int local_ip_family = ip_.family();
1400 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1401 LOG(LS_INFO) << "Server and local address families are not compatible. "
1402 << "Server address: "
1403 << relay_port->address.ipaddr().ToString()
1404 << " Local address: " << ip_.ToString();
1405 continue;
1406 }
1407
1408
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001409 // Shared socket mode must be enabled only for UDP based ports. Hence
1410 // don't pass shared socket for ports which will create TCP sockets.
1411 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1412 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1413 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001414 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001415 port = TurnPort::Create(session_->network_thread(),
1416 session_->socket_factory(),
1417 network_, udp_socket_.get(),
1418 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001419 *relay_port, config.credentials, config.priority,
1420 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421 turn_ports_.push_back(port);
1422 // Listen to the port destroyed signal, to allow AllocationSequence to
1423 // remove entrt from it's map.
1424 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1425 } else {
1426 port = TurnPort::Create(session_->network_thread(),
1427 session_->socket_factory(),
1428 network_, ip_,
1429 session_->allocator()->min_port(),
1430 session_->allocator()->max_port(),
1431 session_->username(),
1432 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001433 *relay_port, config.credentials, config.priority,
1434 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001435 }
nisseede5da42017-01-12 05:15:36 -08001436 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001437 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001438 session_->AddAllocatedPort(port, this, true);
1439 }
1440}
1441
1442void AllocationSequence::OnReadPacket(
1443 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1444 const rtc::SocketAddress& remote_addr,
1445 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001446 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001447
1448 bool turn_port_found = false;
1449
1450 // Try to find the TurnPort that matches the remote address. Note that the
1451 // message could be a STUN binding response if the TURN server is also used as
1452 // a STUN server. We don't want to parse every message here to check if it is
1453 // a STUN binding response, so we pass the message to TurnPort regardless of
1454 // the message type. The TurnPort will just ignore the message since it will
1455 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001456 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001458 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1459 packet_time)) {
1460 return;
1461 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463 }
1464 }
1465
1466 if (udp_port_) {
1467 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1468
1469 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1470 // the TURN server is also a STUN server.
1471 if (!turn_port_found ||
1472 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001473 RTC_DCHECK(udp_port_->SharedSocket());
1474 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1475 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001476 }
1477 }
1478}
1479
1480void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1481 if (udp_port_ == port) {
1482 udp_port_ = NULL;
1483 return;
1484 }
1485
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001486 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1487 if (it != turn_ports_.end()) {
1488 turn_ports_.erase(it);
1489 } else {
1490 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001491 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001492 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001493}
1494
1495// PortConfiguration
1496PortConfiguration::PortConfiguration(
1497 const rtc::SocketAddress& stun_address,
1498 const std::string& username,
1499 const std::string& password)
1500 : stun_address(stun_address), username(username), password(password) {
1501 if (!stun_address.IsNil())
1502 stun_servers.insert(stun_address);
1503}
1504
1505PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1506 const std::string& username,
1507 const std::string& password)
1508 : stun_servers(stun_servers),
1509 username(username),
1510 password(password) {
1511 if (!stun_servers.empty())
1512 stun_address = *(stun_servers.begin());
1513}
1514
1515ServerAddresses PortConfiguration::StunServers() {
1516 if (!stun_address.IsNil() &&
1517 stun_servers.find(stun_address) == stun_servers.end()) {
1518 stun_servers.insert(stun_address);
1519 }
deadbeefc5d0d952015-07-16 10:22:21 -07001520 // Every UDP TURN server should also be used as a STUN server.
1521 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1522 for (const rtc::SocketAddress& turn_server : turn_servers) {
1523 if (stun_servers.find(turn_server) == stun_servers.end()) {
1524 stun_servers.insert(turn_server);
1525 }
1526 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001527 return stun_servers;
1528}
1529
1530void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1531 relays.push_back(config);
1532}
1533
1534bool PortConfiguration::SupportsProtocol(
1535 const RelayServerConfig& relay, ProtocolType type) const {
1536 PortList::const_iterator relay_port;
1537 for (relay_port = relay.ports.begin();
1538 relay_port != relay.ports.end();
1539 ++relay_port) {
1540 if (relay_port->proto == type)
1541 return true;
1542 }
1543 return false;
1544}
1545
1546bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1547 ProtocolType type) const {
1548 for (size_t i = 0; i < relays.size(); ++i) {
1549 if (relays[i].type == turn_type &&
1550 SupportsProtocol(relays[i], type))
1551 return true;
1552 }
1553 return false;
1554}
1555
1556ServerAddresses PortConfiguration::GetRelayServerAddresses(
1557 RelayType turn_type, ProtocolType type) const {
1558 ServerAddresses servers;
1559 for (size_t i = 0; i < relays.size(); ++i) {
1560 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1561 servers.insert(relays[i].ports.front().address);
1562 }
1563 }
1564 return servers;
1565}
1566
1567} // namespace cricket