blob: f4c1fbdefa00006c513c225ed7f107b9fbad9655 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "p2p/client/basicportallocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000014#include <string>
15#include <vector>
16
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/umametrics.h"
18#include "p2p/base/basicpacketsocketfactory.h"
19#include "p2p/base/common.h"
20#include "p2p/base/port.h"
21#include "p2p/base/relayport.h"
22#include "p2p/base/stunport.h"
23#include "p2p/base/tcpport.h"
24#include "p2p/base/turnport.h"
25#include "p2p/base/udpport.h"
26#include "rtc_base/checks.h"
27#include "rtc_base/helpers.h"
28#include "rtc_base/logging.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000029
30using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32namespace {
33
34enum {
35 MSG_CONFIG_START,
36 MSG_CONFIG_READY,
37 MSG_ALLOCATE,
38 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000039 MSG_SEQUENCEOBJECTS_CREATED,
40 MSG_CONFIG_STOP,
41};
42
43const int PHASE_UDP = 0;
44const int PHASE_RELAY = 1;
45const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000046
deadbeef1c5e6d02017-09-15 17:46:56 -070047const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000048
zhihuang696f8ca2017-06-27 15:11:24 -070049// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070050int GetProtocolPriority(cricket::ProtocolType protocol) {
51 switch (protocol) {
52 case cricket::PROTO_UDP:
53 return 2;
54 case cricket::PROTO_TCP:
55 return 1;
56 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070057 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070058 return 0;
59 default:
nisseeb4ca4e2017-01-12 02:24:27 -080060 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070061 return 0;
62 }
63}
64// Gets address family priority: IPv6 > IPv4 > Unspecified.
65int GetAddressFamilyPriority(int ip_family) {
66 switch (ip_family) {
67 case AF_INET6:
68 return 2;
69 case AF_INET:
70 return 1;
71 default:
nisseeb4ca4e2017-01-12 02:24:27 -080072 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070073 return 0;
74 }
75}
76
77// Returns positive if a is better, negative if b is better, and 0 otherwise.
78int ComparePort(const cricket::Port* a, const cricket::Port* b) {
79 int a_protocol = GetProtocolPriority(a->GetProtocol());
80 int b_protocol = GetProtocolPriority(b->GetProtocol());
81 int cmp_protocol = a_protocol - b_protocol;
82 if (cmp_protocol != 0) {
83 return cmp_protocol;
84 }
85
86 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
87 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
88 return a_family - b_family;
89}
90
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091} // namespace
92
93namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020094const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070095 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
96 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097
98// BasicPortAllocator
Taylor Brandstettera1c30352016-05-13 08:15:11 -070099BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
maxmorine9ef9072017-08-29 04:49:00 -0700100 rtc::PacketSocketFactory* socket_factory)
101 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800102 RTC_DCHECK(network_manager_ != nullptr);
103 RTC_DCHECK(socket_factory_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000104 Construct();
105}
106
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800107BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700108 : network_manager_(network_manager), socket_factory_(nullptr) {
nisseede5da42017-01-12 05:15:36 -0800109 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110 Construct();
111}
112
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700113BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
114 rtc::PacketSocketFactory* socket_factory,
115 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700116 : network_manager_(network_manager), socket_factory_(socket_factory) {
nisseede5da42017-01-12 05:15:36 -0800117 RTC_DCHECK(socket_factory_ != NULL);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700118 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119 Construct();
120}
121
122BasicPortAllocator::BasicPortAllocator(
123 rtc::NetworkManager* network_manager,
124 const ServerAddresses& stun_servers,
125 const rtc::SocketAddress& relay_address_udp,
126 const rtc::SocketAddress& relay_address_tcp,
127 const rtc::SocketAddress& relay_address_ssl)
maxmorine9ef9072017-08-29 04:49:00 -0700128 : network_manager_(network_manager), socket_factory_(NULL) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700129 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800131 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800133 }
134 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800136 }
137 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800139 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140
deadbeef653b8e02015-11-11 12:55:10 -0800141 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700142 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800143 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000144
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700145 SetConfiguration(stun_servers, turn_servers, 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 Construct();
147}
148
149void BasicPortAllocator::Construct() {
150 allow_tcp_listen_ = true;
151}
152
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700153void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
154 IceRegatheringReason reason) {
155 if (!metrics_observer()) {
156 return;
157 }
158 // If the session has not been taken by an active channel, do not report the
159 // metric.
160 for (auto& allocator_session : pooled_sessions()) {
161 if (allocator_session.get() == session) {
162 return;
163 }
164 }
165
166 metrics_observer()->IncrementEnumCounter(
167 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
168 static_cast<int>(IceRegatheringReason::MAX_VALUE));
169}
170
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800172 // Our created port allocator sessions depend on us, so destroy our remaining
173 // pooled sessions before anything else.
174 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175}
176
deadbeefc5d0d952015-07-16 10:22:21 -0700177PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 const std::string& content_name, int component,
179 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700180 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700182 session->SignalIceRegathering.connect(this,
183 &BasicPortAllocator::OnIceRegathering);
184 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185}
186
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700187void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
188 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
189 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700190 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
191 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700192}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193
194// BasicPortAllocatorSession
195BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700196 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 const std::string& content_name,
198 int component,
199 const std::string& ice_ufrag,
200 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700201 : PortAllocatorSession(content_name,
202 component,
203 ice_ufrag,
204 ice_pwd,
205 allocator->flags()),
206 allocator_(allocator),
207 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000208 socket_factory_(allocator->socket_factory()),
209 allocation_started_(false),
210 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700211 allocation_sequences_created_(false),
212 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 allocator_->network_manager()->SignalNetworksChanged.connect(
214 this, &BasicPortAllocatorSession::OnNetworksChanged);
215 allocator_->network_manager()->StartUpdating();
216}
217
218BasicPortAllocatorSession::~BasicPortAllocatorSession() {
219 allocator_->network_manager()->StopUpdating();
220 if (network_thread_ != NULL)
221 network_thread_->Clear(this);
222
Peter Boström0c4e06b2015-10-07 12:23:21 +0200223 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000224 // AllocationSequence should clear it's map entry for turn ports before
225 // ports are destroyed.
226 sequences_[i]->Clear();
227 }
228
229 std::vector<PortData>::iterator it;
230 for (it = ports_.begin(); it != ports_.end(); it++)
231 delete it->port();
232
Peter Boström0c4e06b2015-10-07 12:23:21 +0200233 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 delete configs_[i];
235
Peter Boström0c4e06b2015-10-07 12:23:21 +0200236 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237 delete sequences_[i];
238}
239
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700240void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
241 if (filter == candidate_filter_) {
242 return;
243 }
244 // We assume the filter will only change from "ALL" to something else.
245 RTC_DCHECK(candidate_filter_ == CF_ALL);
246 candidate_filter_ = filter;
247 for (PortData& port : ports_) {
248 if (!port.has_pairable_candidate()) {
249 continue;
250 }
251 const auto& candidates = port.port()->Candidates();
252 // Setting a filter may cause a ready port to become non-ready
253 // if it no longer has any pairable candidates.
254 if (!std::any_of(candidates.begin(), candidates.end(),
255 [this, &port](const Candidate& candidate) {
256 return CandidatePairable(candidate, port.port());
257 })) {
258 port.set_has_pairable_candidate(false);
259 }
260 }
261}
262
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263void BasicPortAllocatorSession::StartGettingPorts() {
264 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700265 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 if (!socket_factory_) {
267 owned_socket_factory_.reset(
268 new rtc::BasicPacketSocketFactory(network_thread_));
269 socket_factory_ = owned_socket_factory_.get();
270 }
271
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700272 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700273
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700274 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700275 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000276}
277
278void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800279 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700280 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700281 // Note: this must be called after ClearGettingPorts because both may set the
282 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700283 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700284}
285
286void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800287 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700289 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700291 }
deadbeefb60a8192016-08-24 15:15:00 -0700292 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700293 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700294}
295
296std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
297 std::vector<rtc::Network*> networks = GetNetworks();
298
299 // A network interface may have both IPv4 and IPv6 networks. Only if
300 // neither of the networks has any connections, the network interface
301 // is considered failed and need to be regathered on.
302 std::set<std::string> networks_with_connection;
303 for (const PortData& data : ports_) {
304 Port* port = data.port();
305 if (!port->connections().empty()) {
306 networks_with_connection.insert(port->Network()->name());
307 }
308 }
309
310 networks.erase(
311 std::remove_if(networks.begin(), networks.end(),
312 [networks_with_connection](rtc::Network* network) {
313 // If a network does not have any connection, it is
314 // considered failed.
315 return networks_with_connection.find(network->name()) !=
316 networks_with_connection.end();
317 }),
318 networks.end());
319 return networks;
320}
321
322void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
323 // Find the list of networks that have no connection.
324 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
325 if (failed_networks.empty()) {
326 return;
327 }
328
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700329 LOG(LS_INFO) << "Regather candidates on failed networks";
330
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700331 // Mark a sequence as "network failed" if its network is in the list of failed
332 // networks, so that it won't be considered as equivalent when the session
333 // regathers ports and candidates.
334 for (AllocationSequence* sequence : sequences_) {
335 if (!sequence->network_failed() &&
336 std::find(failed_networks.begin(), failed_networks.end(),
337 sequence->network()) != failed_networks.end()) {
338 sequence->set_network_failed();
339 }
340 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700341
342 bool disable_equivalent_phases = true;
343 Regather(failed_networks, disable_equivalent_phases,
344 IceRegatheringReason::NETWORK_FAILURE);
345}
346
347void BasicPortAllocatorSession::RegatherOnAllNetworks() {
348 std::vector<rtc::Network*> networks = GetNetworks();
349 if (networks.empty()) {
350 return;
351 }
352
353 LOG(LS_INFO) << "Regather candidates on all networks";
354
355 // We expect to generate candidates that are equivalent to what we have now.
356 // Force DoAllocate to generate them instead of skipping.
357 bool disable_equivalent_phases = false;
358 Regather(networks, disable_equivalent_phases,
359 IceRegatheringReason::OCCASIONAL_REFRESH);
360}
361
362void BasicPortAllocatorSession::Regather(
363 const std::vector<rtc::Network*>& networks,
364 bool disable_equivalent_phases,
365 IceRegatheringReason reason) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700366 // Remove ports from being used locally and send signaling to remove
367 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700368 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700369 if (!ports_to_prune.empty()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700370 LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700371 PrunePortsAndRemoveCandidates(ports_to_prune);
372 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700373
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700374 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700375 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700376
Steve Anton300bf8e2017-07-14 10:13:10 -0700377 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700378 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379}
380
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700381std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
382 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700383 for (const PortData& data : ports_) {
384 if (data.ready()) {
385 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700386 }
387 }
388 return ret;
389}
390
391std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
392 std::vector<Candidate> candidates;
393 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700394 if (!data.ready()) {
395 continue;
396 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700397 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700398 }
399 return candidates;
400}
401
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700402void BasicPortAllocatorSession::GetCandidatesFromPort(
403 const PortData& data,
404 std::vector<Candidate>* candidates) const {
405 RTC_CHECK(candidates != nullptr);
406 for (const Candidate& candidate : data.port()->Candidates()) {
407 if (!CheckCandidateFilter(candidate)) {
408 continue;
409 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700410 candidates->push_back(SanitizeRelatedAddress(candidate));
411 }
412}
413
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700414Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
415 const Candidate& c) const {
416 Candidate copy = c;
417 // If adapter enumeration is disabled or host candidates are disabled,
418 // clear the raddr of STUN candidates to avoid local address leakage.
419 bool filter_stun_related_address =
420 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
421 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
422 !(candidate_filter_ & CF_HOST);
423 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
424 // to avoid reflexive address leakage.
425 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
426 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
427 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
428 copy.set_related_address(
429 rtc::EmptySocketAddressWithFamily(copy.address().family()));
430 }
431 return copy;
432}
433
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700434bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
435 // Done only if all required AllocationSequence objects
436 // are created.
437 if (!allocation_sequences_created_) {
438 return false;
439 }
440
441 // Check that all port allocation sequences are complete (not running).
442 if (std::any_of(sequences_.begin(), sequences_.end(),
443 [](const AllocationSequence* sequence) {
444 return sequence->state() == AllocationSequence::kRunning;
445 })) {
446 return false;
447 }
448
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700449 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700450 // expected candidates. Session will trigger candidates allocation complete
451 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700452 return std::none_of(ports_.begin(), ports_.end(),
453 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700454}
455
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
457 switch (message->message_id) {
458 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800459 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 GetPortConfigurations();
461 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800463 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
465 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800467 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000468 OnAllocate();
469 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000470 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800471 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472 OnAllocationSequenceObjectsCreated();
473 break;
474 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800475 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476 OnConfigStop();
477 break;
478 default:
nissec80e7412017-01-11 05:56:46 -0800479 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 }
481}
482
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700483void BasicPortAllocatorSession::UpdateIceParametersInternal() {
484 for (PortData& port : ports_) {
485 port.port()->set_content_name(content_name());
486 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
487 }
488}
489
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000490void BasicPortAllocatorSession::GetPortConfigurations() {
491 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
492 username(),
493 password());
494
deadbeef653b8e02015-11-11 12:55:10 -0800495 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
496 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497 }
498 ConfigReady(config);
499}
500
501void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700502 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000503}
504
505// Adds a configuration to the list.
506void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800507 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800509 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000510
511 AllocatePorts();
512}
513
514void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800515 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000516
517 // If any of the allocated ports have not completed the candidates allocation,
518 // mark those as error. Since session doesn't need any new candidates
519 // at this stage of the allocation, it's safe to discard any new candidates.
520 bool send_signal = false;
521 for (std::vector<PortData>::iterator it = ports_.begin();
522 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700523 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000524 // Updating port state to error, which didn't finish allocating candidates
525 // yet.
526 it->set_error();
527 send_signal = true;
528 }
529 }
530
531 // Did we stop any running sequences?
532 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
533 it != sequences_.end() && !send_signal; ++it) {
534 if ((*it)->state() == AllocationSequence::kStopped) {
535 send_signal = true;
536 }
537 }
538
539 // If we stopped anything that was running, send a done signal now.
540 if (send_signal) {
541 MaybeSignalCandidatesAllocationDone();
542 }
543}
544
545void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800546 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700547 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000548}
549
550void BasicPortAllocatorSession::OnAllocate() {
Steve Anton300bf8e2017-07-14 10:13:10 -0700551 if (network_manager_started_ && !IsStopped()) {
552 bool disable_equivalent_phases = true;
553 DoAllocate(disable_equivalent_phases);
554 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000555
556 allocation_started_ = true;
557}
558
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700559std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
560 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700561 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800562 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700563 // If the network permission state is BLOCKED, we just act as if the flag has
564 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700565 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700566 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700567 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
568 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000569 // If the adapter enumeration is disabled, we'll just bind to any address
570 // instead of specific NIC. This is to ensure the same routing for http
571 // traffic by OS is also used here to avoid any local or public IP leakage
572 // during stun process.
573 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700574 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000575 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700576 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800577 // If network enumeration fails, use the ANY address as a fallback, so we
578 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700579 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
580 // set, we'll use ANY address candidates either way.
581 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800582 network_manager->GetAnyAddressNetworks(&networks);
583 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000584 }
deadbeef3427f532017-07-26 16:09:33 -0700585 // Do some more filtering, depending on the network ignore mask and "disable
586 // costly networks" flag.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700587 networks.erase(std::remove_if(networks.begin(), networks.end(),
588 [this](rtc::Network* network) {
589 return allocator_->network_ignore_mask() &
590 network->type();
591 }),
592 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700593 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
594 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700595 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700596 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
597 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700598 networks.erase(std::remove_if(networks.begin(), networks.end(),
599 [lowest_cost](rtc::Network* network) {
600 return network->GetCost() >
601 lowest_cost + rtc::kNetworkCostLow;
602 }),
603 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700604 }
deadbeef3427f532017-07-26 16:09:33 -0700605 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
606 // default, it's 5), remove networks to ensure that limit is satisfied.
607 //
608 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
609 // networks, we could try to choose a set that's "most likely to work". It's
610 // hard to define what that means though; it's not just "lowest cost".
611 // Alternatively, we could just focus on making our ICE pinging logic smarter
612 // such that this filtering isn't necessary in the first place.
613 int ipv6_networks = 0;
614 for (auto it = networks.begin(); it != networks.end();) {
615 if ((*it)->prefix().family() == AF_INET6) {
616 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
617 it = networks.erase(it);
618 continue;
619 } else {
620 ++ipv6_networks;
621 }
622 }
623 ++it;
624 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700625 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700626}
627
628// For each network, see if we have a sequence that covers it already. If not,
629// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700630void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
honghaiz8c404fa2015-09-28 07:59:43 -0700631 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700632 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633 if (networks.empty()) {
634 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
635 done_signal_needed = true;
636 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700637 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700638 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200639 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200640 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
642 // If all the ports are disabled we should just fire the allocation
643 // done event and return.
644 done_signal_needed = true;
645 break;
646 }
647
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000648 if (!config || config->relays.empty()) {
649 // No relay ports specified in this config.
650 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
651 }
652
653 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000654 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000655 // Skip IPv6 networks unless the flag's been set.
656 continue;
657 }
658
zhihuangb09b3f92017-03-07 14:40:51 -0800659 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
660 networks[i]->GetBestIP().family() == AF_INET6 &&
661 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
662 // Skip IPv6 Wi-Fi networks unless the flag's been set.
663 continue;
664 }
665
Steve Anton300bf8e2017-07-14 10:13:10 -0700666 if (disable_equivalent) {
667 // Disable phases that would only create ports equivalent to
668 // ones that we have already made.
669 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670
Steve Anton300bf8e2017-07-14 10:13:10 -0700671 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
672 // New AllocationSequence would have nothing to do, so don't make it.
673 continue;
674 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000675 }
676
677 AllocationSequence* sequence =
678 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000679 sequence->SignalPortAllocationComplete.connect(
680 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700681 sequence->Init();
682 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000683 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700684 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 }
686 }
687 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700688 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689 }
690}
691
692void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700693 std::vector<rtc::Network*> networks = GetNetworks();
694 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700695 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700696 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700697 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700698 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700699 std::find(networks.begin(), networks.end(), sequence->network()) ==
700 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700701 sequence->OnNetworkFailed();
702 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700703 }
704 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700705 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
706 if (!ports_to_prune.empty()) {
707 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
708 << " ports because their networks were gone";
709 PrunePortsAndRemoveCandidates(ports_to_prune);
710 }
honghaiz8c404fa2015-09-28 07:59:43 -0700711
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700712 if (allocation_started_ && !IsStopped()) {
713 if (network_manager_started_) {
714 // If the network manager has started, it must be regathering.
715 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
716 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700717 bool disable_equivalent_phases = true;
718 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700719 }
720
Honghai Zhang5048f572016-08-23 15:47:33 -0700721 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700722 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700723 network_manager_started_ = true;
724 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000725}
726
727void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200728 rtc::Network* network,
729 PortConfiguration* config,
730 uint32_t* flags) {
731 for (uint32_t i = 0; i < sequences_.size() &&
732 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
733 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734 sequences_[i]->DisableEquivalentPhases(network, config, flags);
735 }
736}
737
738void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
739 AllocationSequence * seq,
740 bool prepare_address) {
741 if (!port)
742 return;
743
744 LOG(LS_INFO) << "Adding allocated port for " << content_name();
745 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700746 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000747 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700748 if (allocator_->proxy().type != rtc::PROXY_NONE)
749 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700750 port->set_send_retransmit_count_attribute(
751 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 PortData data(port, seq);
754 ports_.push_back(data);
755
756 port->SignalCandidateReady.connect(
757 this, &BasicPortAllocatorSession::OnCandidateReady);
758 port->SignalPortComplete.connect(this,
759 &BasicPortAllocatorSession::OnPortComplete);
760 port->SignalDestroyed.connect(this,
761 &BasicPortAllocatorSession::OnPortDestroyed);
762 port->SignalPortError.connect(
763 this, &BasicPortAllocatorSession::OnPortError);
764 LOG_J(LS_INFO, port) << "Added port to allocator";
765
766 if (prepare_address)
767 port->PrepareAddress();
768}
769
770void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
771 allocation_sequences_created_ = true;
772 // Send candidate allocation complete signal if we have no sequences.
773 MaybeSignalCandidatesAllocationDone();
774}
775
776void BasicPortAllocatorSession::OnCandidateReady(
777 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800778 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000779 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800780 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700781 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000782 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700783 // already done with gathering.
784 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700785 LOG(LS_WARNING)
786 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700787 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700788 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700789
danilchapf4e8cf02016-06-30 01:55:03 -0700790 // Mark that the port has a pairable candidate, either because we have a
791 // usable candidate from the port, or simply because the port is bound to the
792 // any address and therefore has no host candidate. This will trigger the port
793 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700794 // checks. If port has already been marked as having a pairable candidate,
795 // do nothing here.
796 // Note: We should check whether any candidates may become ready after this
797 // because there we will check whether the candidate is generated by the ready
798 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700799 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700800 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700801 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700802
803 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700804 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700805 }
806 // If the current port is not pruned yet, SignalPortReady.
807 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700808 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700809 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700810 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700811 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700812 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700813
deadbeef1c5e6d02017-09-15 17:46:56 -0700814 if (data->ready() && CheckCandidateFilter(c)) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700815 std::vector<Candidate> candidates;
816 candidates.push_back(SanitizeRelatedAddress(c));
817 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700818 } else {
819 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700820 }
821
822 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700823 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700824 MaybeSignalCandidatesAllocationDone();
825 }
826}
827
828Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
829 const std::string& network_name) const {
830 Port* best_turn_port = nullptr;
831 for (const PortData& data : ports_) {
832 if (data.port()->Network()->name() == network_name &&
833 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
834 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
835 best_turn_port = data.port();
836 }
837 }
838 return best_turn_port;
839}
840
841bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700842 // Note: We determine the same network based only on their network names. So
843 // if an IPv4 address and an IPv6 address have the same network name, they
844 // are considered the same network here.
845 const std::string& network_name = newly_pairable_turn_port->Network()->name();
846 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
847 // |port| is already in the list of ports, so the best port cannot be nullptr.
848 RTC_CHECK(best_turn_port != nullptr);
849
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700850 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700851 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700852 for (PortData& data : ports_) {
853 if (data.port()->Network()->name() == network_name &&
854 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
855 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700856 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700857 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700858 // These ports will be pruned in PrunePortsAndRemoveCandidates.
859 ports_to_prune.push_back(&data);
860 } else {
861 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700862 }
863 }
864 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700865
866 if (!ports_to_prune.empty()) {
867 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
868 << " low-priority TURN ports";
869 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700870 }
871 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872}
873
Honghai Zhanga74363c2016-07-28 18:06:15 -0700874void BasicPortAllocatorSession::PruneAllPorts() {
875 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700876 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700877 }
878}
879
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000880void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800881 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700882 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000883 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800884 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885
886 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700887 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700889 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000890
891 // Moving to COMPLETE state.
892 data->set_complete();
893 // Send candidate allocation complete signal if this was the last port.
894 MaybeSignalCandidatesAllocationDone();
895}
896
897void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800898 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700899 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800901 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700903 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000904 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700905 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906
907 // SignalAddressError is currently sent from StunPort/TurnPort.
908 // But this signal itself is generic.
909 data->set_error();
910 // Send candidate allocation complete signal if this was the last port.
911 MaybeSignalCandidatesAllocationDone();
912}
913
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700914bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700915 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000916
917 // When binding to any address, before sending packets out, the getsockname
918 // returns all 0s, but after sending packets, it'll be the NIC used to
919 // send. All 0s is not a valid ICE candidate address and should be filtered
920 // out.
921 if (c.address().IsAnyIP()) {
922 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 }
924
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000925 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000926 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000927 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000928 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000929 } else if (c.type() == LOCAL_PORT_TYPE) {
930 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
931 // We allow host candidates if the filter allows server-reflexive
932 // candidates and the candidate is a public IP. Because we don't generate
933 // server-reflexive candidates if they have the same IP as the host
934 // candidate (i.e. when the host candidate is a public IP), filtering to
935 // only server-reflexive candidates won't work right when the host
936 // candidates have public IPs.
937 return true;
938 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000939
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000940 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000941 }
942 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943}
944
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700945bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
946 const Port* port) const {
947 bool candidate_signalable = CheckCandidateFilter(c);
948
949 // When device enumeration is disabled (to prevent non-default IP addresses
950 // from leaking), we ping from some local candidates even though we don't
951 // signal them. However, if host candidates are also disabled (for example, to
952 // prevent even default IP addresses from leaking), we still don't want to
953 // ping from them, even if device enumeration is disabled. Thus, we check for
954 // both device enumeration and host candidates being disabled.
955 bool network_enumeration_disabled = c.address().IsAnyIP();
956 bool can_ping_from_candidate =
957 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
958 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
959
960 return candidate_signalable ||
961 (network_enumeration_disabled && can_ping_from_candidate &&
962 !host_candidates_disabled);
963}
964
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000965void BasicPortAllocatorSession::OnPortAllocationComplete(
966 AllocationSequence* seq) {
967 // Send candidate allocation complete signal if all ports are done.
968 MaybeSignalCandidatesAllocationDone();
969}
970
971void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700972 if (CandidatesAllocationDone()) {
973 if (pooled()) {
974 LOG(LS_INFO) << "All candidates gathered for pooled session.";
975 } else {
976 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
977 << component() << ":" << generation();
978 }
979 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000980 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981}
982
983void BasicPortAllocatorSession::OnPortDestroyed(
984 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800985 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986 for (std::vector<PortData>::iterator iter = ports_.begin();
987 iter != ports_.end(); ++iter) {
988 if (port == iter->port()) {
989 ports_.erase(iter);
990 LOG_J(LS_INFO, port) << "Removed port from allocator ("
991 << static_cast<int>(ports_.size()) << " remaining)";
992 return;
993 }
994 }
nissec80e7412017-01-11 05:56:46 -0800995 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000996}
997
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000998BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
999 Port* port) {
1000 for (std::vector<PortData>::iterator it = ports_.begin();
1001 it != ports_.end(); ++it) {
1002 if (it->port() == port) {
1003 return &*it;
1004 }
1005 }
1006 return NULL;
1007}
1008
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001009std::vector<BasicPortAllocatorSession::PortData*>
1010BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001011 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001012 std::vector<PortData*> unpruned_ports;
1013 for (PortData& port : ports_) {
1014 if (!port.pruned() &&
1015 std::find(networks.begin(), networks.end(),
1016 port.sequence()->network()) != networks.end()) {
1017 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001018 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001019 }
1020 return unpruned_ports;
1021}
1022
1023void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1024 const std::vector<PortData*>& port_data_list) {
1025 std::vector<PortInterface*> pruned_ports;
1026 std::vector<Candidate> removed_candidates;
1027 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001028 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001029 data->Prune();
1030 pruned_ports.push_back(data->port());
1031 if (data->has_pairable_candidate()) {
1032 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001033 // Mark the port as having no pairable candidates so that its candidates
1034 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001035 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001036 }
1037 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001038 if (!pruned_ports.empty()) {
1039 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001040 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001041 if (!removed_candidates.empty()) {
1042 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1043 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001044 }
1045}
1046
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047// AllocationSequence
1048
1049AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1050 rtc::Network* network,
1051 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001052 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001053 : session_(session),
1054 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001055 config_(config),
1056 state_(kInit),
1057 flags_(flags),
1058 udp_socket_(),
1059 udp_port_(NULL),
1060 phase_(0) {
1061}
1062
Honghai Zhang5048f572016-08-23 15:47:33 -07001063void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001064 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1065 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001066 rtc::SocketAddress(network_->GetBestIP(), 0),
1067 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001068 if (udp_socket_) {
1069 udp_socket_->SignalReadPacket.connect(
1070 this, &AllocationSequence::OnReadPacket);
1071 }
1072 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1073 // are next available options to setup a communication channel.
1074 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001075}
1076
1077void AllocationSequence::Clear() {
1078 udp_port_ = NULL;
1079 turn_ports_.clear();
1080}
1081
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001082void AllocationSequence::OnNetworkFailed() {
1083 RTC_DCHECK(!network_failed_);
1084 network_failed_ = true;
1085 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001086 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001087}
1088
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001089AllocationSequence::~AllocationSequence() {
1090 session_->network_thread()->Clear(this);
1091}
1092
1093void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001094 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001095 if (network_failed_) {
1096 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001097 // it won't be equivalent to the new network.
1098 return;
1099 }
1100
deadbeef5c3c1042017-08-04 15:01:57 -07001101 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001102 // Different network setup; nothing is equivalent.
1103 return;
1104 }
1105
1106 // Else turn off the stuff that we've already got covered.
1107
deadbeef1c46a352017-09-27 11:24:05 -07001108 // Every config implicitly specifies local, so turn that off right away if we
1109 // already have a port of the corresponding type. Look for a port that
1110 // matches this AllocationSequence's network, is the right protocol, and
1111 // hasn't encountered an error.
1112 // TODO(deadbeef): This doesn't take into account that there may be another
1113 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1114 // This can happen if, say, there's a network change event right before an
1115 // application-triggered ICE restart. Hopefully this problem will just go
1116 // away if we get rid of the gathering "phases" though, which is planned.
1117 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1118 [this](const BasicPortAllocatorSession::PortData& p) {
1119 return p.port()->Network() == network_ &&
1120 p.port()->GetProtocol() == PROTO_UDP && !p.error();
1121 })) {
1122 *flags |= PORTALLOCATOR_DISABLE_UDP;
1123 }
1124 if (std::any_of(session_->ports_.begin(), session_->ports_.end(),
1125 [this](const BasicPortAllocatorSession::PortData& p) {
1126 return p.port()->Network() == network_ &&
1127 p.port()->GetProtocol() == PROTO_TCP && !p.error();
1128 })) {
1129 *flags |= PORTALLOCATOR_DISABLE_TCP;
1130 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001131
1132 if (config_ && config) {
1133 if (config_->StunServers() == config->StunServers()) {
1134 // Already got this STUN servers covered.
1135 *flags |= PORTALLOCATOR_DISABLE_STUN;
1136 }
1137 if (!config_->relays.empty()) {
1138 // Already got relays covered.
1139 // NOTE: This will even skip a _different_ set of relay servers if we
1140 // were to be given one, but that never happens in our codebase. Should
1141 // probably get rid of the list in PortConfiguration and just keep a
1142 // single relay server in each one.
1143 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1144 }
1145 }
1146}
1147
1148void AllocationSequence::Start() {
1149 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001150 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001151 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1152 // called next time, we enable all phases if the best IP has since changed.
1153 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154}
1155
1156void AllocationSequence::Stop() {
1157 // If the port is completed, don't set it to stopped.
1158 if (state_ == kRunning) {
1159 state_ = kStopped;
1160 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1161 }
1162}
1163
1164void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001165 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1166 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001167
deadbeef1c5e6d02017-09-15 17:46:56 -07001168 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169
1170 // Perform all of the phases in the current step.
1171 LOG_J(LS_INFO, network_) << "Allocation Phase="
1172 << PHASE_NAMES[phase_];
1173
1174 switch (phase_) {
1175 case PHASE_UDP:
1176 CreateUDPPorts();
1177 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 break;
1179
1180 case PHASE_RELAY:
1181 CreateRelayPorts();
1182 break;
1183
1184 case PHASE_TCP:
1185 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001186 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187 break;
1188
1189 default:
nissec80e7412017-01-11 05:56:46 -08001190 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191 }
1192
1193 if (state() == kRunning) {
1194 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001195 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1196 session_->allocator()->step_delay(),
1197 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001198 } else {
1199 // If all phases in AllocationSequence are completed, no allocation
1200 // steps needed further. Canceling pending signal.
1201 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1202 SignalPortAllocationComplete(this);
1203 }
1204}
1205
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001206void AllocationSequence::CreateUDPPorts() {
1207 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1208 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1209 return;
1210 }
1211
1212 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1213 // is enabled completely.
1214 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001215 bool emit_local_candidate_for_anyaddress =
1216 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001218 port = UDPPort::Create(
1219 session_->network_thread(), session_->socket_factory(), network_,
1220 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001221 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001223 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001224 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001225 session_->allocator()->min_port(), session_->allocator()->max_port(),
1226 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001227 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228 }
1229
1230 if (port) {
1231 // If shared socket is enabled, STUN candidate will be allocated by the
1232 // UDPPort.
1233 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1234 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001235 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001236
1237 // If STUN is not disabled, setting stun server address to port.
1238 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001239 if (config_ && !config_->StunServers().empty()) {
1240 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1241 << "STUN candidate generation.";
1242 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243 }
1244 }
1245 }
1246
1247 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001248 }
1249}
1250
1251void AllocationSequence::CreateTCPPorts() {
1252 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1253 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1254 return;
1255 }
1256
deadbeef5c3c1042017-08-04 15:01:57 -07001257 Port* port = TCPPort::Create(
1258 session_->network_thread(), session_->socket_factory(), network_,
1259 session_->allocator()->min_port(), session_->allocator()->max_port(),
1260 session_->username(), session_->password(),
1261 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001262 if (port) {
1263 session_->AddAllocatedPort(port, this, true);
1264 // Since TCPPort is not created using shared socket, |port| will not be
1265 // added to the dequeue.
1266 }
1267}
1268
1269void AllocationSequence::CreateStunPorts() {
1270 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1271 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1272 return;
1273 }
1274
1275 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1276 return;
1277 }
1278
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001279 if (!(config_ && !config_->StunServers().empty())) {
1280 LOG(LS_WARNING)
1281 << "AllocationSequence: No STUN server configured, skipping.";
1282 return;
1283 }
1284
deadbeef5c3c1042017-08-04 15:01:57 -07001285 StunPort* port = StunPort::Create(
1286 session_->network_thread(), session_->socket_factory(), network_,
1287 session_->allocator()->min_port(), session_->allocator()->max_port(),
1288 session_->username(), session_->password(), config_->StunServers(),
1289 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001290 if (port) {
1291 session_->AddAllocatedPort(port, this, true);
1292 // Since StunPort is not created using shared socket, |port| will not be
1293 // added to the dequeue.
1294 }
1295}
1296
1297void AllocationSequence::CreateRelayPorts() {
1298 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1299 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1300 return;
1301 }
1302
1303 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1304 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001305 RTC_DCHECK(config_);
1306 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307 if (!(config_ && !config_->relays.empty())) {
1308 LOG(LS_WARNING)
1309 << "AllocationSequence: No relay server configured, skipping.";
1310 return;
1311 }
1312
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001313 for (RelayServerConfig& relay : config_->relays) {
1314 if (relay.type == RELAY_GTURN) {
1315 CreateGturnPort(relay);
1316 } else if (relay.type == RELAY_TURN) {
1317 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318 } else {
nissec80e7412017-01-11 05:56:46 -08001319 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001320 }
1321 }
1322}
1323
1324void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1325 // TODO(mallinath) - Rename RelayPort to GTurnPort.
deadbeef5c3c1042017-08-04 15:01:57 -07001326 RelayPort* port = RelayPort::Create(
1327 session_->network_thread(), session_->socket_factory(), network_,
1328 session_->allocator()->min_port(), session_->allocator()->max_port(),
1329 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001330 if (port) {
1331 // Since RelayPort is not created using shared socket, |port| will not be
1332 // added to the dequeue.
1333 // Note: We must add the allocated port before we add addresses because
1334 // the latter will create candidates that need name and preference
1335 // settings. However, we also can't prepare the address (normally
1336 // done by AddAllocatedPort) until we have these addresses. So we
1337 // wait to do that until below.
1338 session_->AddAllocatedPort(port, this, false);
1339
1340 // Add the addresses of this protocol.
1341 PortList::const_iterator relay_port;
1342 for (relay_port = config.ports.begin();
1343 relay_port != config.ports.end();
1344 ++relay_port) {
1345 port->AddServerAddress(*relay_port);
1346 port->AddExternalAddress(*relay_port);
1347 }
1348 // Start fetching an address for this port.
1349 port->PrepareAddress();
1350 }
1351}
1352
1353void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1354 PortList::const_iterator relay_port;
1355 for (relay_port = config.ports.begin();
1356 relay_port != config.ports.end(); ++relay_port) {
1357 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001358
1359 // Skip UDP connections to relay servers if it's disallowed.
1360 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1361 relay_port->proto == PROTO_UDP) {
1362 continue;
1363 }
1364
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001365 // Do not create a port if the server address family is known and does
1366 // not match the local IP address family.
1367 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001368 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001369 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1370 LOG(LS_INFO) << "Server and local address families are not compatible. "
1371 << "Server address: "
1372 << relay_port->address.ipaddr().ToString()
deadbeef5c3c1042017-08-04 15:01:57 -07001373 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001374 continue;
1375 }
1376
1377
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378 // Shared socket mode must be enabled only for UDP based ports. Hence
1379 // don't pass shared socket for ports which will create TCP sockets.
1380 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1381 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1382 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001383 relay_port->proto == PROTO_UDP && udp_socket_) {
maxmorine9ef9072017-08-29 04:49:00 -07001384 port = TurnPort::Create(session_->network_thread(),
1385 session_->socket_factory(),
1386 network_, udp_socket_.get(),
1387 session_->username(), session_->password(),
1388 *relay_port, config.credentials, config.priority,
1389 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 turn_ports_.push_back(port);
1391 // Listen to the port destroyed signal, to allow AllocationSequence to
1392 // remove entrt from it's map.
1393 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1394 } else {
deadbeef5c3c1042017-08-04 15:01:57 -07001395 port = TurnPort::Create(
1396 session_->network_thread(), session_->socket_factory(), network_,
1397 session_->allocator()->min_port(), session_->allocator()->max_port(),
1398 session_->username(), session_->password(), *relay_port,
Diogo Real1dca9d52017-08-29 12:18:32 -07001399 config.credentials, config.priority, session_->allocator()->origin(),
Diogo Real7bd1f1b2017-09-08 12:50:41 -07001400 config.tls_alpn_protocols, config.tls_elliptic_curves);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001401 }
nisseede5da42017-01-12 05:15:36 -08001402 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001403 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001404 session_->AddAllocatedPort(port, this, true);
1405 }
1406}
1407
1408void AllocationSequence::OnReadPacket(
1409 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1410 const rtc::SocketAddress& remote_addr,
1411 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001412 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001413
1414 bool turn_port_found = false;
1415
1416 // Try to find the TurnPort that matches the remote address. Note that the
1417 // message could be a STUN binding response if the TURN server is also used as
1418 // a STUN server. We don't want to parse every message here to check if it is
1419 // a STUN binding response, so we pass the message to TurnPort regardless of
1420 // the message type. The TurnPort will just ignore the message since it will
1421 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001422 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001423 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001424 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1425 packet_time)) {
1426 return;
1427 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001428 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 }
1430 }
1431
1432 if (udp_port_) {
1433 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1434
1435 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1436 // the TURN server is also a STUN server.
1437 if (!turn_port_found ||
1438 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001439 RTC_DCHECK(udp_port_->SharedSocket());
1440 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1441 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001442 }
1443 }
1444}
1445
1446void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1447 if (udp_port_ == port) {
1448 udp_port_ = NULL;
1449 return;
1450 }
1451
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001452 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1453 if (it != turn_ports_.end()) {
1454 turn_ports_.erase(it);
1455 } else {
1456 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001457 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001458 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001459}
1460
1461// PortConfiguration
1462PortConfiguration::PortConfiguration(
1463 const rtc::SocketAddress& stun_address,
1464 const std::string& username,
1465 const std::string& password)
1466 : stun_address(stun_address), username(username), password(password) {
1467 if (!stun_address.IsNil())
1468 stun_servers.insert(stun_address);
1469}
1470
1471PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1472 const std::string& username,
1473 const std::string& password)
1474 : stun_servers(stun_servers),
1475 username(username),
1476 password(password) {
1477 if (!stun_servers.empty())
1478 stun_address = *(stun_servers.begin());
1479}
1480
1481ServerAddresses PortConfiguration::StunServers() {
1482 if (!stun_address.IsNil() &&
1483 stun_servers.find(stun_address) == stun_servers.end()) {
1484 stun_servers.insert(stun_address);
1485 }
deadbeefc5d0d952015-07-16 10:22:21 -07001486 // Every UDP TURN server should also be used as a STUN server.
1487 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1488 for (const rtc::SocketAddress& turn_server : turn_servers) {
1489 if (stun_servers.find(turn_server) == stun_servers.end()) {
1490 stun_servers.insert(turn_server);
1491 }
1492 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001493 return stun_servers;
1494}
1495
1496void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1497 relays.push_back(config);
1498}
1499
1500bool PortConfiguration::SupportsProtocol(
1501 const RelayServerConfig& relay, ProtocolType type) const {
1502 PortList::const_iterator relay_port;
1503 for (relay_port = relay.ports.begin();
1504 relay_port != relay.ports.end();
1505 ++relay_port) {
1506 if (relay_port->proto == type)
1507 return true;
1508 }
1509 return false;
1510}
1511
1512bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1513 ProtocolType type) const {
1514 for (size_t i = 0; i < relays.size(); ++i) {
1515 if (relays[i].type == turn_type &&
1516 SupportsProtocol(relays[i], type))
1517 return true;
1518 }
1519 return false;
1520}
1521
1522ServerAddresses PortConfiguration::GetRelayServerAddresses(
1523 RelayType turn_type, ProtocolType type) const {
1524 ServerAddresses servers;
1525 for (size_t i = 0; i < relays.size(); ++i) {
1526 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1527 servers.insert(relays[i].ports.front().address);
1528 }
1529 }
1530 return servers;
1531}
1532
1533} // namespace cricket