blob: 5ddc4754938f761b87a93e56cf865bd43137f0e3 [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"
kjellanderc3771cc2017-06-30 13:42:44 -070026#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 }
342 // Remove ports from being used locally and send signaling to remove
343 // the candidates on the remote side.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700344 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
345 if (!ports_to_prune.empty()) {
346 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
347 << " ports because their networks failed";
348 PrunePortsAndRemoveCandidates(ports_to_prune);
349 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700350
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700351 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
352 SignalIceRegathering(this, IceRegatheringReason::NETWORK_FAILURE);
353
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700354 DoAllocate();
355 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356}
357
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700358std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
359 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700360 for (const PortData& data : ports_) {
361 if (data.ready()) {
362 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700363 }
364 }
365 return ret;
366}
367
368std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
369 std::vector<Candidate> candidates;
370 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700371 if (!data.ready()) {
372 continue;
373 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700374 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700375 }
376 return candidates;
377}
378
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700379void BasicPortAllocatorSession::GetCandidatesFromPort(
380 const PortData& data,
381 std::vector<Candidate>* candidates) const {
382 RTC_CHECK(candidates != nullptr);
383 for (const Candidate& candidate : data.port()->Candidates()) {
384 if (!CheckCandidateFilter(candidate)) {
385 continue;
386 }
387 ProtocolType pvalue;
388 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
389 !data.sequence()->ProtocolEnabled(pvalue)) {
390 continue;
391 }
392 candidates->push_back(SanitizeRelatedAddress(candidate));
393 }
394}
395
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700396Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
397 const Candidate& c) const {
398 Candidate copy = c;
399 // If adapter enumeration is disabled or host candidates are disabled,
400 // clear the raddr of STUN candidates to avoid local address leakage.
401 bool filter_stun_related_address =
402 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
403 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
404 !(candidate_filter_ & CF_HOST);
405 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
406 // to avoid reflexive address leakage.
407 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
408 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
409 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
410 copy.set_related_address(
411 rtc::EmptySocketAddressWithFamily(copy.address().family()));
412 }
413 return copy;
414}
415
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700416bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
417 // Done only if all required AllocationSequence objects
418 // are created.
419 if (!allocation_sequences_created_) {
420 return false;
421 }
422
423 // Check that all port allocation sequences are complete (not running).
424 if (std::any_of(sequences_.begin(), sequences_.end(),
425 [](const AllocationSequence* sequence) {
426 return sequence->state() == AllocationSequence::kRunning;
427 })) {
428 return false;
429 }
430
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700431 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700432 // expected candidates. Session will trigger candidates allocation complete
433 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700434 return std::none_of(ports_.begin(), ports_.end(),
435 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700436}
437
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
439 switch (message->message_id) {
440 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800441 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 GetPortConfigurations();
443 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800445 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
447 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800449 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 OnAllocate();
451 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000452 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800453 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000454 OnAllocationSequenceObjectsCreated();
455 break;
456 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800457 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 OnConfigStop();
459 break;
460 default:
nissec80e7412017-01-11 05:56:46 -0800461 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462 }
463}
464
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700465void BasicPortAllocatorSession::UpdateIceParametersInternal() {
466 for (PortData& port : ports_) {
467 port.port()->set_content_name(content_name());
468 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
469 }
470}
471
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472void BasicPortAllocatorSession::GetPortConfigurations() {
473 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
474 username(),
475 password());
476
deadbeef653b8e02015-11-11 12:55:10 -0800477 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
478 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000479 }
480 ConfigReady(config);
481}
482
483void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700484 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000485}
486
487// Adds a configuration to the list.
488void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800489 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000490 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800491 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000492
493 AllocatePorts();
494}
495
496void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800497 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000498
499 // If any of the allocated ports have not completed the candidates allocation,
500 // mark those as error. Since session doesn't need any new candidates
501 // at this stage of the allocation, it's safe to discard any new candidates.
502 bool send_signal = false;
503 for (std::vector<PortData>::iterator it = ports_.begin();
504 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700505 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000506 // Updating port state to error, which didn't finish allocating candidates
507 // yet.
508 it->set_error();
509 send_signal = true;
510 }
511 }
512
513 // Did we stop any running sequences?
514 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
515 it != sequences_.end() && !send_signal; ++it) {
516 if ((*it)->state() == AllocationSequence::kStopped) {
517 send_signal = true;
518 }
519 }
520
521 // If we stopped anything that was running, send a done signal now.
522 if (send_signal) {
523 MaybeSignalCandidatesAllocationDone();
524 }
525}
526
527void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800528 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700529 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530}
531
532void BasicPortAllocatorSession::OnAllocate() {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700533 if (network_manager_started_ && !IsStopped())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000534 DoAllocate();
535
536 allocation_started_ = true;
537}
538
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700539std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
540 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700541 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800542 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700543 // If the network permission state is BLOCKED, we just act as if the flag has
544 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700545 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700546 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700547 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
548 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000549 // If the adapter enumeration is disabled, we'll just bind to any address
550 // instead of specific NIC. This is to ensure the same routing for http
551 // traffic by OS is also used here to avoid any local or public IP leakage
552 // during stun process.
553 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700554 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000555 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700556 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800557 // If network enumeration fails, use the ANY address as a fallback, so we
558 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700559 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
560 // set, we'll use ANY address candidates either way.
561 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800562 network_manager->GetAnyAddressNetworks(&networks);
563 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000564 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700565 networks.erase(std::remove_if(networks.begin(), networks.end(),
566 [this](rtc::Network* network) {
567 return allocator_->network_ignore_mask() &
568 network->type();
569 }),
570 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700571
572 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
573 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700574 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700575 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
576 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700577 networks.erase(std::remove_if(networks.begin(), networks.end(),
578 [lowest_cost](rtc::Network* network) {
579 return network->GetCost() >
580 lowest_cost + rtc::kNetworkCostLow;
581 }),
582 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700583 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700584 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700585}
586
587// For each network, see if we have a sequence that covers it already. If not,
588// create a new sequence to create the appropriate ports.
589void BasicPortAllocatorSession::DoAllocate() {
590 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700591 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 if (networks.empty()) {
593 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
594 done_signal_needed = true;
595 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700596 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700597 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200598 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200599 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000600 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
601 // If all the ports are disabled we should just fire the allocation
602 // done event and return.
603 done_signal_needed = true;
604 break;
605 }
606
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000607 if (!config || config->relays.empty()) {
608 // No relay ports specified in this config.
609 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
610 }
611
612 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614 // Skip IPv6 networks unless the flag's been set.
615 continue;
616 }
617
zhihuangb09b3f92017-03-07 14:40:51 -0800618 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
619 networks[i]->GetBestIP().family() == AF_INET6 &&
620 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
621 // Skip IPv6 Wi-Fi networks unless the flag's been set.
622 continue;
623 }
624
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000625 // Disable phases that would only create ports equivalent to
626 // ones that we have already made.
627 DisableEquivalentPhases(networks[i], config, &sequence_flags);
628
629 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
630 // New AllocationSequence would have nothing to do, so don't make it.
631 continue;
632 }
633
634 AllocationSequence* sequence =
635 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636 sequence->SignalPortAllocationComplete.connect(
637 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700638 sequence->Init();
639 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700641 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000642 }
643 }
644 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700645 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646 }
647}
648
649void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700650 std::vector<rtc::Network*> networks = GetNetworks();
651 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700652 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700653 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700654 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700655 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700656 std::find(networks.begin(), networks.end(), sequence->network()) ==
657 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700658 sequence->OnNetworkFailed();
659 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700660 }
661 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700662 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
663 if (!ports_to_prune.empty()) {
664 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
665 << " ports because their networks were gone";
666 PrunePortsAndRemoveCandidates(ports_to_prune);
667 }
honghaiz8c404fa2015-09-28 07:59:43 -0700668
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700669 if (allocation_started_ && !IsStopped()) {
670 if (network_manager_started_) {
671 // If the network manager has started, it must be regathering.
672 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
673 }
674 DoAllocate();
675 }
676
Honghai Zhang5048f572016-08-23 15:47:33 -0700677 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700678 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700679 network_manager_started_ = true;
680 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000681}
682
683void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200684 rtc::Network* network,
685 PortConfiguration* config,
686 uint32_t* flags) {
687 for (uint32_t i = 0; i < sequences_.size() &&
688 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
689 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690 sequences_[i]->DisableEquivalentPhases(network, config, flags);
691 }
692}
693
694void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
695 AllocationSequence * seq,
696 bool prepare_address) {
697 if (!port)
698 return;
699
700 LOG(LS_INFO) << "Adding allocated port for " << content_name();
701 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700702 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000703 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700704 if (allocator_->proxy().type != rtc::PROXY_NONE)
705 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700706 port->set_send_retransmit_count_attribute(
707 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000709 PortData data(port, seq);
710 ports_.push_back(data);
711
712 port->SignalCandidateReady.connect(
713 this, &BasicPortAllocatorSession::OnCandidateReady);
714 port->SignalPortComplete.connect(this,
715 &BasicPortAllocatorSession::OnPortComplete);
716 port->SignalDestroyed.connect(this,
717 &BasicPortAllocatorSession::OnPortDestroyed);
718 port->SignalPortError.connect(
719 this, &BasicPortAllocatorSession::OnPortError);
720 LOG_J(LS_INFO, port) << "Added port to allocator";
721
722 if (prepare_address)
723 port->PrepareAddress();
724}
725
726void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
727 allocation_sequences_created_ = true;
728 // Send candidate allocation complete signal if we have no sequences.
729 MaybeSignalCandidatesAllocationDone();
730}
731
732void BasicPortAllocatorSession::OnCandidateReady(
733 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800734 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000735 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800736 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700737 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000738 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700739 // already done with gathering.
740 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700741 LOG(LS_WARNING)
742 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700743 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700744 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700745
danilchapf4e8cf02016-06-30 01:55:03 -0700746 // Mark that the port has a pairable candidate, either because we have a
747 // usable candidate from the port, or simply because the port is bound to the
748 // any address and therefore has no host candidate. This will trigger the port
749 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700750 // checks. If port has already been marked as having a pairable candidate,
751 // do nothing here.
752 // Note: We should check whether any candidates may become ready after this
753 // because there we will check whether the candidate is generated by the ready
754 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700755 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700756 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700757 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700758
759 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700760 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700761 }
762 // If the current port is not pruned yet, SignalPortReady.
763 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700764 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700765 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700766 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700767 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700768 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700769
770 ProtocolType pvalue;
771 bool candidate_protocol_enabled =
772 StringToProto(c.protocol().c_str(), &pvalue) &&
773 data->sequence()->ProtocolEnabled(pvalue);
774
775 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
776 std::vector<Candidate> candidates;
777 candidates.push_back(SanitizeRelatedAddress(c));
778 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700779 } else if (!candidate_protocol_enabled) {
780 LOG(LS_INFO)
781 << "Not yet signaling candidate because protocol is not yet enabled.";
782 } else {
783 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700784 }
785
786 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700787 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700788 MaybeSignalCandidatesAllocationDone();
789 }
790}
791
792Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
793 const std::string& network_name) const {
794 Port* best_turn_port = nullptr;
795 for (const PortData& data : ports_) {
796 if (data.port()->Network()->name() == network_name &&
797 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
798 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
799 best_turn_port = data.port();
800 }
801 }
802 return best_turn_port;
803}
804
805bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700806 // Note: We determine the same network based only on their network names. So
807 // if an IPv4 address and an IPv6 address have the same network name, they
808 // are considered the same network here.
809 const std::string& network_name = newly_pairable_turn_port->Network()->name();
810 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
811 // |port| is already in the list of ports, so the best port cannot be nullptr.
812 RTC_CHECK(best_turn_port != nullptr);
813
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700814 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700815 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700816 for (PortData& data : ports_) {
817 if (data.port()->Network()->name() == network_name &&
818 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
819 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700820 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700821 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700822 // These ports will be pruned in PrunePortsAndRemoveCandidates.
823 ports_to_prune.push_back(&data);
824 } else {
825 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700826 }
827 }
828 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700829
830 if (!ports_to_prune.empty()) {
831 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
832 << " low-priority TURN ports";
833 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700834 }
835 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000836}
837
Honghai Zhanga74363c2016-07-28 18:06:15 -0700838void BasicPortAllocatorSession::PruneAllPorts() {
839 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700840 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700841 }
842}
843
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800845 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700846 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800848 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849
850 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700851 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854
855 // Moving to COMPLETE state.
856 data->set_complete();
857 // Send candidate allocation complete signal if this was the last port.
858 MaybeSignalCandidatesAllocationDone();
859}
860
861void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800862 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700863 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800865 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700867 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000868 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700869 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870
871 // SignalAddressError is currently sent from StunPort/TurnPort.
872 // But this signal itself is generic.
873 data->set_error();
874 // Send candidate allocation complete signal if this was the last port.
875 MaybeSignalCandidatesAllocationDone();
876}
877
878void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
879 ProtocolType proto) {
880 std::vector<Candidate> candidates;
881 for (std::vector<PortData>::iterator it = ports_.begin();
882 it != ports_.end(); ++it) {
883 if (it->sequence() != seq)
884 continue;
885
886 const std::vector<Candidate>& potentials = it->port()->Candidates();
887 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700888 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700890 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700892 bool candidate_protocol_enabled =
893 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
894 pvalue == proto;
895 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700896 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
897 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 candidates.push_back(potentials[i]);
899 }
900 }
901 }
902
903 if (!candidates.empty()) {
904 SignalCandidatesReady(this, candidates);
905 }
906}
907
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700908bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700909 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000910
911 // When binding to any address, before sending packets out, the getsockname
912 // returns all 0s, but after sending packets, it'll be the NIC used to
913 // send. All 0s is not a valid ICE candidate address and should be filtered
914 // out.
915 if (c.address().IsAnyIP()) {
916 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000917 }
918
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000919 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000920 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000921 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000922 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000923 } else if (c.type() == LOCAL_PORT_TYPE) {
924 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
925 // We allow host candidates if the filter allows server-reflexive
926 // candidates and the candidate is a public IP. Because we don't generate
927 // server-reflexive candidates if they have the same IP as the host
928 // candidate (i.e. when the host candidate is a public IP), filtering to
929 // only server-reflexive candidates won't work right when the host
930 // candidates have public IPs.
931 return true;
932 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000934 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000935 }
936 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937}
938
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700939bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
940 const Port* port) const {
941 bool candidate_signalable = CheckCandidateFilter(c);
942
943 // When device enumeration is disabled (to prevent non-default IP addresses
944 // from leaking), we ping from some local candidates even though we don't
945 // signal them. However, if host candidates are also disabled (for example, to
946 // prevent even default IP addresses from leaking), we still don't want to
947 // ping from them, even if device enumeration is disabled. Thus, we check for
948 // both device enumeration and host candidates being disabled.
949 bool network_enumeration_disabled = c.address().IsAnyIP();
950 bool can_ping_from_candidate =
951 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
952 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
953
954 return candidate_signalable ||
955 (network_enumeration_disabled && can_ping_from_candidate &&
956 !host_candidates_disabled);
957}
958
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000959void BasicPortAllocatorSession::OnPortAllocationComplete(
960 AllocationSequence* seq) {
961 // Send candidate allocation complete signal if all ports are done.
962 MaybeSignalCandidatesAllocationDone();
963}
964
965void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700966 if (CandidatesAllocationDone()) {
967 if (pooled()) {
968 LOG(LS_INFO) << "All candidates gathered for pooled session.";
969 } else {
970 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
971 << component() << ":" << generation();
972 }
973 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000974 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975}
976
977void BasicPortAllocatorSession::OnPortDestroyed(
978 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800979 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000980 for (std::vector<PortData>::iterator iter = ports_.begin();
981 iter != ports_.end(); ++iter) {
982 if (port == iter->port()) {
983 ports_.erase(iter);
984 LOG_J(LS_INFO, port) << "Removed port from allocator ("
985 << static_cast<int>(ports_.size()) << " remaining)";
986 return;
987 }
988 }
nissec80e7412017-01-11 05:56:46 -0800989 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000990}
991
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000992BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
993 Port* port) {
994 for (std::vector<PortData>::iterator it = ports_.begin();
995 it != ports_.end(); ++it) {
996 if (it->port() == port) {
997 return &*it;
998 }
999 }
1000 return NULL;
1001}
1002
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001003std::vector<BasicPortAllocatorSession::PortData*>
1004BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001005 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001006 std::vector<PortData*> unpruned_ports;
1007 for (PortData& port : ports_) {
1008 if (!port.pruned() &&
1009 std::find(networks.begin(), networks.end(),
1010 port.sequence()->network()) != networks.end()) {
1011 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001012 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001013 }
1014 return unpruned_ports;
1015}
1016
1017void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1018 const std::vector<PortData*>& port_data_list) {
1019 std::vector<PortInterface*> pruned_ports;
1020 std::vector<Candidate> removed_candidates;
1021 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001022 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001023 data->Prune();
1024 pruned_ports.push_back(data->port());
1025 if (data->has_pairable_candidate()) {
1026 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001027 // Mark the port as having no pairable candidates so that its candidates
1028 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001029 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001030 }
1031 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001032 if (!pruned_ports.empty()) {
1033 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001034 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001035 if (!removed_candidates.empty()) {
1036 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1037 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001038 }
1039}
1040
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001041// AllocationSequence
1042
1043AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1044 rtc::Network* network,
1045 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001046 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047 : session_(session),
1048 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001049 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001050 config_(config),
1051 state_(kInit),
1052 flags_(flags),
1053 udp_socket_(),
1054 udp_port_(NULL),
1055 phase_(0) {
1056}
1057
Honghai Zhang5048f572016-08-23 15:47:33 -07001058void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001059 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1060 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1061 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1062 session_->allocator()->max_port()));
1063 if (udp_socket_) {
1064 udp_socket_->SignalReadPacket.connect(
1065 this, &AllocationSequence::OnReadPacket);
1066 }
1067 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1068 // are next available options to setup a communication channel.
1069 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001070}
1071
1072void AllocationSequence::Clear() {
1073 udp_port_ = NULL;
1074 turn_ports_.clear();
1075}
1076
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001077void AllocationSequence::OnNetworkFailed() {
1078 RTC_DCHECK(!network_failed_);
1079 network_failed_ = true;
1080 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001081 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001082}
1083
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001084AllocationSequence::~AllocationSequence() {
1085 session_->network_thread()->Clear(this);
1086}
1087
1088void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001089 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001090 if (network_failed_) {
1091 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001092 // it won't be equivalent to the new network.
1093 return;
1094 }
1095
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001096 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001097 // Different network setup; nothing is equivalent.
1098 return;
1099 }
1100
1101 // Else turn off the stuff that we've already got covered.
1102
1103 // Every config implicitly specifies local, so turn that off right away.
1104 *flags |= PORTALLOCATOR_DISABLE_UDP;
1105 *flags |= PORTALLOCATOR_DISABLE_TCP;
1106
1107 if (config_ && config) {
1108 if (config_->StunServers() == config->StunServers()) {
1109 // Already got this STUN servers covered.
1110 *flags |= PORTALLOCATOR_DISABLE_STUN;
1111 }
1112 if (!config_->relays.empty()) {
1113 // Already got relays covered.
1114 // NOTE: This will even skip a _different_ set of relay servers if we
1115 // were to be given one, but that never happens in our codebase. Should
1116 // probably get rid of the list in PortConfiguration and just keep a
1117 // single relay server in each one.
1118 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1119 }
1120 }
1121}
1122
1123void AllocationSequence::Start() {
1124 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001125 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001126}
1127
1128void AllocationSequence::Stop() {
1129 // If the port is completed, don't set it to stopped.
1130 if (state_ == kRunning) {
1131 state_ = kStopped;
1132 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1133 }
1134}
1135
1136void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001137 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1138 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001139
1140 const char* const PHASE_NAMES[kNumPhases] = {
1141 "Udp", "Relay", "Tcp", "SslTcp"
1142 };
1143
1144 // Perform all of the phases in the current step.
1145 LOG_J(LS_INFO, network_) << "Allocation Phase="
1146 << PHASE_NAMES[phase_];
1147
1148 switch (phase_) {
1149 case PHASE_UDP:
1150 CreateUDPPorts();
1151 CreateStunPorts();
1152 EnableProtocol(PROTO_UDP);
1153 break;
1154
1155 case PHASE_RELAY:
1156 CreateRelayPorts();
1157 break;
1158
1159 case PHASE_TCP:
1160 CreateTCPPorts();
1161 EnableProtocol(PROTO_TCP);
1162 break;
1163
1164 case PHASE_SSLTCP:
1165 state_ = kCompleted;
1166 EnableProtocol(PROTO_SSLTCP);
1167 break;
1168
1169 default:
nissec80e7412017-01-11 05:56:46 -08001170 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001171 }
1172
1173 if (state() == kRunning) {
1174 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001175 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1176 session_->allocator()->step_delay(),
1177 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001178 } else {
1179 // If all phases in AllocationSequence are completed, no allocation
1180 // steps needed further. Canceling pending signal.
1181 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1182 SignalPortAllocationComplete(this);
1183 }
1184}
1185
1186void AllocationSequence::EnableProtocol(ProtocolType proto) {
1187 if (!ProtocolEnabled(proto)) {
1188 protocols_.push_back(proto);
1189 session_->OnProtocolEnabled(this, proto);
1190 }
1191}
1192
1193bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1194 for (ProtocolList::const_iterator it = protocols_.begin();
1195 it != protocols_.end(); ++it) {
1196 if (*it == proto)
1197 return true;
1198 }
1199 return false;
1200}
1201
1202void AllocationSequence::CreateUDPPorts() {
1203 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1204 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1205 return;
1206 }
1207
1208 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1209 // is enabled completely.
1210 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001211 bool emit_local_candidate_for_anyaddress =
1212 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001213 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001214 port = UDPPort::Create(
1215 session_->network_thread(), session_->socket_factory(), network_,
1216 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001217 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001219 port = UDPPort::Create(
1220 session_->network_thread(), session_->socket_factory(), network_, ip_,
1221 session_->allocator()->min_port(), session_->allocator()->max_port(),
1222 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001223 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001224 }
1225
1226 if (port) {
1227 // If shared socket is enabled, STUN candidate will be allocated by the
1228 // UDPPort.
1229 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1230 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001231 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001232
1233 // If STUN is not disabled, setting stun server address to port.
1234 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001235 if (config_ && !config_->StunServers().empty()) {
1236 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1237 << "STUN candidate generation.";
1238 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001239 }
1240 }
1241 }
1242
1243 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001244 }
1245}
1246
1247void AllocationSequence::CreateTCPPorts() {
1248 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1249 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1250 return;
1251 }
1252
1253 Port* port = TCPPort::Create(session_->network_thread(),
1254 session_->socket_factory(),
1255 network_, ip_,
1256 session_->allocator()->min_port(),
1257 session_->allocator()->max_port(),
1258 session_->username(), session_->password(),
1259 session_->allocator()->allow_tcp_listen());
1260 if (port) {
1261 session_->AddAllocatedPort(port, this, true);
1262 // Since TCPPort is not created using shared socket, |port| will not be
1263 // added to the dequeue.
1264 }
1265}
1266
1267void AllocationSequence::CreateStunPorts() {
1268 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1269 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1270 return;
1271 }
1272
1273 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1274 return;
1275 }
1276
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001277 if (!(config_ && !config_->StunServers().empty())) {
1278 LOG(LS_WARNING)
1279 << "AllocationSequence: No STUN server configured, skipping.";
1280 return;
1281 }
1282
1283 StunPort* port = StunPort::Create(session_->network_thread(),
1284 session_->socket_factory(),
1285 network_, ip_,
1286 session_->allocator()->min_port(),
1287 session_->allocator()->max_port(),
1288 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001289 config_->StunServers(),
1290 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001291 if (port) {
1292 session_->AddAllocatedPort(port, this, true);
1293 // Since StunPort is not created using shared socket, |port| will not be
1294 // added to the dequeue.
1295 }
1296}
1297
1298void AllocationSequence::CreateRelayPorts() {
1299 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1300 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1301 return;
1302 }
1303
1304 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1305 // ought to have a relay list for them here.
nisseede5da42017-01-12 05:15:36 -08001306 RTC_DCHECK(config_ && !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.
1326 RelayPort* port = RelayPort::Create(session_->network_thread(),
1327 session_->socket_factory(),
1328 network_, ip_,
1329 session_->allocator()->min_port(),
1330 session_->allocator()->max_port(),
1331 config_->username, config_->password);
1332 if (port) {
1333 // Since RelayPort is not created using shared socket, |port| will not be
1334 // added to the dequeue.
1335 // Note: We must add the allocated port before we add addresses because
1336 // the latter will create candidates that need name and preference
1337 // settings. However, we also can't prepare the address (normally
1338 // done by AddAllocatedPort) until we have these addresses. So we
1339 // wait to do that until below.
1340 session_->AddAllocatedPort(port, this, false);
1341
1342 // Add the addresses of this protocol.
1343 PortList::const_iterator relay_port;
1344 for (relay_port = config.ports.begin();
1345 relay_port != config.ports.end();
1346 ++relay_port) {
1347 port->AddServerAddress(*relay_port);
1348 port->AddExternalAddress(*relay_port);
1349 }
1350 // Start fetching an address for this port.
1351 port->PrepareAddress();
1352 }
1353}
1354
1355void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1356 PortList::const_iterator relay_port;
1357 for (relay_port = config.ports.begin();
1358 relay_port != config.ports.end(); ++relay_port) {
1359 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001360
1361 // Skip UDP connections to relay servers if it's disallowed.
1362 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1363 relay_port->proto == PROTO_UDP) {
1364 continue;
1365 }
1366
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001367 // Do not create a port if the server address family is known and does
1368 // not match the local IP address family.
1369 int server_ip_family = relay_port->address.ipaddr().family();
1370 int local_ip_family = ip_.family();
1371 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1372 LOG(LS_INFO) << "Server and local address families are not compatible. "
1373 << "Server address: "
1374 << relay_port->address.ipaddr().ToString()
1375 << " Local address: " << ip_.ToString();
1376 continue;
1377 }
1378
1379
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001380 // Shared socket mode must be enabled only for UDP based ports. Hence
1381 // don't pass shared socket for ports which will create TCP sockets.
1382 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1383 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1384 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001385 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001386 port = TurnPort::Create(session_->network_thread(),
1387 session_->socket_factory(),
1388 network_, udp_socket_.get(),
1389 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001390 *relay_port, config.credentials, config.priority,
1391 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001392 turn_ports_.push_back(port);
1393 // Listen to the port destroyed signal, to allow AllocationSequence to
1394 // remove entrt from it's map.
1395 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1396 } else {
1397 port = TurnPort::Create(session_->network_thread(),
1398 session_->socket_factory(),
1399 network_, ip_,
1400 session_->allocator()->min_port(),
1401 session_->allocator()->max_port(),
1402 session_->username(),
1403 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001404 *relay_port, config.credentials, config.priority,
1405 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 }
nisseede5da42017-01-12 05:15:36 -08001407 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001408 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001409 session_->AddAllocatedPort(port, this, true);
1410 }
1411}
1412
1413void AllocationSequence::OnReadPacket(
1414 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1415 const rtc::SocketAddress& remote_addr,
1416 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001417 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001418
1419 bool turn_port_found = false;
1420
1421 // Try to find the TurnPort that matches the remote address. Note that the
1422 // message could be a STUN binding response if the TURN server is also used as
1423 // a STUN server. We don't want to parse every message here to check if it is
1424 // a STUN binding response, so we pass the message to TurnPort regardless of
1425 // the message type. The TurnPort will just ignore the message since it will
1426 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001427 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001428 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001429 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1430 packet_time)) {
1431 return;
1432 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001433 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001434 }
1435 }
1436
1437 if (udp_port_) {
1438 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1439
1440 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1441 // the TURN server is also a STUN server.
1442 if (!turn_port_found ||
1443 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001444 RTC_DCHECK(udp_port_->SharedSocket());
1445 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1446 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001447 }
1448 }
1449}
1450
1451void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1452 if (udp_port_ == port) {
1453 udp_port_ = NULL;
1454 return;
1455 }
1456
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001457 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1458 if (it != turn_ports_.end()) {
1459 turn_ports_.erase(it);
1460 } else {
1461 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001462 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001463 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001464}
1465
1466// PortConfiguration
1467PortConfiguration::PortConfiguration(
1468 const rtc::SocketAddress& stun_address,
1469 const std::string& username,
1470 const std::string& password)
1471 : stun_address(stun_address), username(username), password(password) {
1472 if (!stun_address.IsNil())
1473 stun_servers.insert(stun_address);
1474}
1475
1476PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1477 const std::string& username,
1478 const std::string& password)
1479 : stun_servers(stun_servers),
1480 username(username),
1481 password(password) {
1482 if (!stun_servers.empty())
1483 stun_address = *(stun_servers.begin());
1484}
1485
1486ServerAddresses PortConfiguration::StunServers() {
1487 if (!stun_address.IsNil() &&
1488 stun_servers.find(stun_address) == stun_servers.end()) {
1489 stun_servers.insert(stun_address);
1490 }
deadbeefc5d0d952015-07-16 10:22:21 -07001491 // Every UDP TURN server should also be used as a STUN server.
1492 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1493 for (const rtc::SocketAddress& turn_server : turn_servers) {
1494 if (stun_servers.find(turn_server) == stun_servers.end()) {
1495 stun_servers.insert(turn_server);
1496 }
1497 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001498 return stun_servers;
1499}
1500
1501void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1502 relays.push_back(config);
1503}
1504
1505bool PortConfiguration::SupportsProtocol(
1506 const RelayServerConfig& relay, ProtocolType type) const {
1507 PortList::const_iterator relay_port;
1508 for (relay_port = relay.ports.begin();
1509 relay_port != relay.ports.end();
1510 ++relay_port) {
1511 if (relay_port->proto == type)
1512 return true;
1513 }
1514 return false;
1515}
1516
1517bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1518 ProtocolType type) const {
1519 for (size_t i = 0; i < relays.size(); ++i) {
1520 if (relays[i].type == turn_type &&
1521 SupportsProtocol(relays[i], type))
1522 return true;
1523 }
1524 return false;
1525}
1526
1527ServerAddresses PortConfiguration::GetRelayServerAddresses(
1528 RelayType turn_type, ProtocolType type) const {
1529 ServerAddresses servers;
1530 for (size_t i = 0; i < relays.size(); ++i) {
1531 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1532 servers.insert(relays[i].ports.front().address);
1533 }
1534 }
1535 return servers;
1536}
1537
1538} // namespace cricket