blob: 46c28926c8db4e5ce844d0de6e6d268a589aaed2 [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
17#include "webrtc/p2p/base/basicpacketsocketfactory.h"
18#include "webrtc/p2p/base/common.h"
19#include "webrtc/p2p/base/port.h"
20#include "webrtc/p2p/base/relayport.h"
21#include "webrtc/p2p/base/stunport.h"
22#include "webrtc/p2p/base/tcpport.h"
23#include "webrtc/p2p/base/turnport.h"
24#include "webrtc/p2p/base/udpport.h"
Guo-wei Shieh38f88932015-08-13 22:24:02 -070025#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000026#include "webrtc/base/common.h"
27#include "webrtc/base/helpers.h"
28#include "webrtc/base/logging.h"
29
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
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070050// Gets protocol priority: UDP > TCP > SSLTCP.
51int 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:
58 return 0;
59 default:
60 RTC_DCHECK(false);
61 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:
72 RTC_DCHECK(false);
73 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,
100 rtc::PacketSocketFactory* socket_factory)
101 : network_manager_(network_manager), socket_factory_(socket_factory) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800102 ASSERT(network_manager_ != nullptr);
103 ASSERT(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)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700108 : network_manager_(network_manager), socket_factory_(nullptr) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800109 ASSERT(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)
116 : network_manager_(network_manager), socket_factory_(socket_factory) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000117 ASSERT(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)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700128 : network_manager_(network_manager), socket_factory_(NULL) {
129 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
153BasicPortAllocator::~BasicPortAllocator() {
154}
155
deadbeefc5d0d952015-07-16 10:22:21 -0700156PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 const std::string& content_name, int component,
158 const std::string& ice_ufrag, const std::string& ice_pwd) {
159 return new BasicPortAllocatorSession(
160 this, content_name, component, ice_ufrag, ice_pwd);
161}
162
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700163void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
164 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
165 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700166 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
167 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700168}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169
170// BasicPortAllocatorSession
171BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700172 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 const std::string& content_name,
174 int component,
175 const std::string& ice_ufrag,
176 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700177 : PortAllocatorSession(content_name,
178 component,
179 ice_ufrag,
180 ice_pwd,
181 allocator->flags()),
182 allocator_(allocator),
183 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 socket_factory_(allocator->socket_factory()),
185 allocation_started_(false),
186 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700187 allocation_sequences_created_(false),
188 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 allocator_->network_manager()->SignalNetworksChanged.connect(
190 this, &BasicPortAllocatorSession::OnNetworksChanged);
191 allocator_->network_manager()->StartUpdating();
192}
193
194BasicPortAllocatorSession::~BasicPortAllocatorSession() {
195 allocator_->network_manager()->StopUpdating();
196 if (network_thread_ != NULL)
197 network_thread_->Clear(this);
198
Peter Boström0c4e06b2015-10-07 12:23:21 +0200199 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 // AllocationSequence should clear it's map entry for turn ports before
201 // ports are destroyed.
202 sequences_[i]->Clear();
203 }
204
205 std::vector<PortData>::iterator it;
206 for (it = ports_.begin(); it != ports_.end(); it++)
207 delete it->port();
208
Peter Boström0c4e06b2015-10-07 12:23:21 +0200209 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210 delete configs_[i];
211
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 delete sequences_[i];
214}
215
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700216void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
217 if (filter == candidate_filter_) {
218 return;
219 }
220 // We assume the filter will only change from "ALL" to something else.
221 RTC_DCHECK(candidate_filter_ == CF_ALL);
222 candidate_filter_ = filter;
223 for (PortData& port : ports_) {
224 if (!port.has_pairable_candidate()) {
225 continue;
226 }
227 const auto& candidates = port.port()->Candidates();
228 // Setting a filter may cause a ready port to become non-ready
229 // if it no longer has any pairable candidates.
230 if (!std::any_of(candidates.begin(), candidates.end(),
231 [this, &port](const Candidate& candidate) {
232 return CandidatePairable(candidate, port.port());
233 })) {
234 port.set_has_pairable_candidate(false);
235 }
236 }
237}
238
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239void BasicPortAllocatorSession::StartGettingPorts() {
240 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700241 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242 if (!socket_factory_) {
243 owned_socket_factory_.reset(
244 new rtc::BasicPacketSocketFactory(network_thread_));
245 socket_factory_ = owned_socket_factory_.get();
246 }
247
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700248 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700249
250 LOG(LS_INFO) << "Pruning turn ports "
251 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252}
253
254void BasicPortAllocatorSession::StopGettingPorts() {
255 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700256 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
honghaiz98db68f2015-09-29 07:58:17 -0700257 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700258 // Note: this must be called after ClearGettingPorts because both may set the
259 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700260 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700261}
262
263void BasicPortAllocatorSession::ClearGettingPorts() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700264 ASSERT(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700266 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700268 }
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700269 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700270}
271
272std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
273 std::vector<rtc::Network*> networks = GetNetworks();
274
275 // A network interface may have both IPv4 and IPv6 networks. Only if
276 // neither of the networks has any connections, the network interface
277 // is considered failed and need to be regathered on.
278 std::set<std::string> networks_with_connection;
279 for (const PortData& data : ports_) {
280 Port* port = data.port();
281 if (!port->connections().empty()) {
282 networks_with_connection.insert(port->Network()->name());
283 }
284 }
285
286 networks.erase(
287 std::remove_if(networks.begin(), networks.end(),
288 [networks_with_connection](rtc::Network* network) {
289 // If a network does not have any connection, it is
290 // considered failed.
291 return networks_with_connection.find(network->name()) !=
292 networks_with_connection.end();
293 }),
294 networks.end());
295 return networks;
296}
297
298void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
299 // Find the list of networks that have no connection.
300 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
301 if (failed_networks.empty()) {
302 return;
303 }
304
305 // Mark a sequence as "network failed" if its network is in the list of failed
306 // networks, so that it won't be considered as equivalent when the session
307 // regathers ports and candidates.
308 for (AllocationSequence* sequence : sequences_) {
309 if (!sequence->network_failed() &&
310 std::find(failed_networks.begin(), failed_networks.end(),
311 sequence->network()) != failed_networks.end()) {
312 sequence->set_network_failed();
313 }
314 }
315 // Remove ports from being used locally and send signaling to remove
316 // the candidates on the remote side.
317 RemovePortsAndCandidates(failed_networks);
318
319 if (allocation_started_ && network_manager_started_) {
320 DoAllocate();
321 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322}
323
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700324std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
325 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700326 for (const PortData& data : ports_) {
327 if (data.ready()) {
328 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700329 }
330 }
331 return ret;
332}
333
334std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
335 std::vector<Candidate> candidates;
336 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700337 if (!data.ready()) {
338 continue;
339 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700340 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700341 }
342 return candidates;
343}
344
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700345void BasicPortAllocatorSession::GetCandidatesFromPort(
346 const PortData& data,
347 std::vector<Candidate>* candidates) const {
348 RTC_CHECK(candidates != nullptr);
349 for (const Candidate& candidate : data.port()->Candidates()) {
350 if (!CheckCandidateFilter(candidate)) {
351 continue;
352 }
353 ProtocolType pvalue;
354 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
355 !data.sequence()->ProtocolEnabled(pvalue)) {
356 continue;
357 }
358 candidates->push_back(SanitizeRelatedAddress(candidate));
359 }
360}
361
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700362Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
363 const Candidate& c) const {
364 Candidate copy = c;
365 // If adapter enumeration is disabled or host candidates are disabled,
366 // clear the raddr of STUN candidates to avoid local address leakage.
367 bool filter_stun_related_address =
368 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
369 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
370 !(candidate_filter_ & CF_HOST);
371 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
372 // to avoid reflexive address leakage.
373 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
374 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
375 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
376 copy.set_related_address(
377 rtc::EmptySocketAddressWithFamily(copy.address().family()));
378 }
379 return copy;
380}
381
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700382bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
383 // Done only if all required AllocationSequence objects
384 // are created.
385 if (!allocation_sequences_created_) {
386 return false;
387 }
388
389 // Check that all port allocation sequences are complete (not running).
390 if (std::any_of(sequences_.begin(), sequences_.end(),
391 [](const AllocationSequence* sequence) {
392 return sequence->state() == AllocationSequence::kRunning;
393 })) {
394 return false;
395 }
396
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700397 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700398 // expected candidates. Session will trigger candidates allocation complete
399 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700400 return std::none_of(ports_.begin(), ports_.end(),
401 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700402}
403
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
405 switch (message->message_id) {
406 case MSG_CONFIG_START:
407 ASSERT(rtc::Thread::Current() == network_thread_);
408 GetPortConfigurations();
409 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 case MSG_CONFIG_READY:
411 ASSERT(rtc::Thread::Current() == network_thread_);
412 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
413 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 case MSG_ALLOCATE:
415 ASSERT(rtc::Thread::Current() == network_thread_);
416 OnAllocate();
417 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 case MSG_SEQUENCEOBJECTS_CREATED:
419 ASSERT(rtc::Thread::Current() == network_thread_);
420 OnAllocationSequenceObjectsCreated();
421 break;
422 case MSG_CONFIG_STOP:
423 ASSERT(rtc::Thread::Current() == network_thread_);
424 OnConfigStop();
425 break;
426 default:
427 ASSERT(false);
428 }
429}
430
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700431void BasicPortAllocatorSession::UpdateIceParametersInternal() {
432 for (PortData& port : ports_) {
433 port.port()->set_content_name(content_name());
434 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
435 }
436}
437
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438void BasicPortAllocatorSession::GetPortConfigurations() {
439 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
440 username(),
441 password());
442
deadbeef653b8e02015-11-11 12:55:10 -0800443 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
444 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 }
446 ConfigReady(config);
447}
448
449void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700450 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451}
452
453// Adds a configuration to the list.
454void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800455 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800457 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458
459 AllocatePorts();
460}
461
462void BasicPortAllocatorSession::OnConfigStop() {
463 ASSERT(rtc::Thread::Current() == network_thread_);
464
465 // If any of the allocated ports have not completed the candidates allocation,
466 // mark those as error. Since session doesn't need any new candidates
467 // at this stage of the allocation, it's safe to discard any new candidates.
468 bool send_signal = false;
469 for (std::vector<PortData>::iterator it = ports_.begin();
470 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700471 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472 // Updating port state to error, which didn't finish allocating candidates
473 // yet.
474 it->set_error();
475 send_signal = true;
476 }
477 }
478
479 // Did we stop any running sequences?
480 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
481 it != sequences_.end() && !send_signal; ++it) {
482 if ((*it)->state() == AllocationSequence::kStopped) {
483 send_signal = true;
484 }
485 }
486
487 // If we stopped anything that was running, send a done signal now.
488 if (send_signal) {
489 MaybeSignalCandidatesAllocationDone();
490 }
491}
492
493void BasicPortAllocatorSession::AllocatePorts() {
494 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700495 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496}
497
498void BasicPortAllocatorSession::OnAllocate() {
499 if (network_manager_started_)
500 DoAllocate();
501
502 allocation_started_ = true;
503}
504
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700505std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
506 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700507 rtc::NetworkManager* network_manager = allocator_->network_manager();
508 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700509 // If the network permission state is BLOCKED, we just act as if the flag has
510 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700511 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700512 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700513 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
514 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000515 // If the adapter enumeration is disabled, we'll just bind to any address
516 // instead of specific NIC. This is to ensure the same routing for http
517 // traffic by OS is also used here to avoid any local or public IP leakage
518 // during stun process.
519 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700520 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000521 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700522 network_manager->GetNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000523 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700524 networks.erase(std::remove_if(networks.begin(), networks.end(),
525 [this](rtc::Network* network) {
526 return allocator_->network_ignore_mask() &
527 network->type();
528 }),
529 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700530
531 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
532 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700533 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700534 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
535 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700536 networks.erase(std::remove_if(networks.begin(), networks.end(),
537 [lowest_cost](rtc::Network* network) {
538 return network->GetCost() >
539 lowest_cost + rtc::kNetworkCostLow;
540 }),
541 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700542 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700543 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700544}
545
546// For each network, see if we have a sequence that covers it already. If not,
547// create a new sequence to create the appropriate ports.
548void BasicPortAllocatorSession::DoAllocate() {
549 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700550 std::vector<rtc::Network*> networks = GetNetworks();
honghaiz8c404fa2015-09-28 07:59:43 -0700551
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 if (networks.empty()) {
553 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
554 done_signal_needed = true;
555 } else {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700556 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200557 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200558 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
560 // If all the ports are disabled we should just fire the allocation
561 // done event and return.
562 done_signal_needed = true;
563 break;
564 }
565
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000566 if (!config || config->relays.empty()) {
567 // No relay ports specified in this config.
568 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
569 }
570
571 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000573 // Skip IPv6 networks unless the flag's been set.
574 continue;
575 }
576
577 // Disable phases that would only create ports equivalent to
578 // ones that we have already made.
579 DisableEquivalentPhases(networks[i], config, &sequence_flags);
580
581 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
582 // New AllocationSequence would have nothing to do, so don't make it.
583 continue;
584 }
585
586 AllocationSequence* sequence =
587 new AllocationSequence(this, networks[i], config, sequence_flags);
588 if (!sequence->Init()) {
589 delete sequence;
590 continue;
591 }
592 done_signal_needed = true;
593 sequence->SignalPortAllocationComplete.connect(
594 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700595 if (!IsStopped()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000596 sequence->Start();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700597 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 sequences_.push_back(sequence);
599 }
600 }
601 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700602 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000603 }
604}
605
606void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700607 std::vector<rtc::Network*> networks = GetNetworks();
608 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700609 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700610 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700611 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700612 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700613 std::find(networks.begin(), networks.end(), sequence->network()) ==
614 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700615 sequence->OnNetworkFailed();
616 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700617 }
618 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700619 RemovePortsAndCandidates(failed_networks);
honghaiz8c404fa2015-09-28 07:59:43 -0700620
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621 network_manager_started_ = true;
622 if (allocation_started_)
623 DoAllocate();
624}
625
626void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200627 rtc::Network* network,
628 PortConfiguration* config,
629 uint32_t* flags) {
630 for (uint32_t i = 0; i < sequences_.size() &&
631 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
632 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633 sequences_[i]->DisableEquivalentPhases(network, config, flags);
634 }
635}
636
637void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
638 AllocationSequence * seq,
639 bool prepare_address) {
640 if (!port)
641 return;
642
643 LOG(LS_INFO) << "Adding allocated port for " << content_name();
644 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700645 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646 port->set_generation(generation());
647 if (allocator_->proxy().type != rtc::PROXY_NONE)
648 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700649 port->set_send_retransmit_count_attribute(
650 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000652 PortData data(port, seq);
653 ports_.push_back(data);
654
655 port->SignalCandidateReady.connect(
656 this, &BasicPortAllocatorSession::OnCandidateReady);
657 port->SignalPortComplete.connect(this,
658 &BasicPortAllocatorSession::OnPortComplete);
659 port->SignalDestroyed.connect(this,
660 &BasicPortAllocatorSession::OnPortDestroyed);
661 port->SignalPortError.connect(
662 this, &BasicPortAllocatorSession::OnPortError);
663 LOG_J(LS_INFO, port) << "Added port to allocator";
664
665 if (prepare_address)
666 port->PrepareAddress();
667}
668
669void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
670 allocation_sequences_created_ = true;
671 // Send candidate allocation complete signal if we have no sequences.
672 MaybeSignalCandidatesAllocationDone();
673}
674
675void BasicPortAllocatorSession::OnCandidateReady(
676 Port* port, const Candidate& c) {
677 ASSERT(rtc::Thread::Current() == network_thread_);
678 PortData* data = FindPort(port);
679 ASSERT(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700680 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000681 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700682 // already done with gathering.
683 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700684 LOG(LS_WARNING)
685 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700686 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700687 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700688
danilchapf4e8cf02016-06-30 01:55:03 -0700689 // Mark that the port has a pairable candidate, either because we have a
690 // usable candidate from the port, or simply because the port is bound to the
691 // any address and therefore has no host candidate. This will trigger the port
692 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700693 // checks. If port has already been marked as having a pairable candidate,
694 // do nothing here.
695 // Note: We should check whether any candidates may become ready after this
696 // because there we will check whether the candidate is generated by the ready
697 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700698 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700699 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700700 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700701
702 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700703 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700704 }
705 // If the current port is not pruned yet, SignalPortReady.
706 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700707 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700708 SignalPortReady(this, port);
709 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700710 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700711
712 ProtocolType pvalue;
713 bool candidate_protocol_enabled =
714 StringToProto(c.protocol().c_str(), &pvalue) &&
715 data->sequence()->ProtocolEnabled(pvalue);
716
717 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
718 std::vector<Candidate> candidates;
719 candidates.push_back(SanitizeRelatedAddress(c));
720 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700721 } else if (!candidate_protocol_enabled) {
722 LOG(LS_INFO)
723 << "Not yet signaling candidate because protocol is not yet enabled.";
724 } else {
725 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700726 }
727
728 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700729 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700730 MaybeSignalCandidatesAllocationDone();
731 }
732}
733
734Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
735 const std::string& network_name) const {
736 Port* best_turn_port = nullptr;
737 for (const PortData& data : ports_) {
738 if (data.port()->Network()->name() == network_name &&
739 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
740 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
741 best_turn_port = data.port();
742 }
743 }
744 return best_turn_port;
745}
746
747bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700748 // Note: We determine the same network based only on their network names. So
749 // if an IPv4 address and an IPv6 address have the same network name, they
750 // are considered the same network here.
751 const std::string& network_name = newly_pairable_turn_port->Network()->name();
752 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
753 // |port| is already in the list of ports, so the best port cannot be nullptr.
754 RTC_CHECK(best_turn_port != nullptr);
755
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700756 bool pruned = false;
757 std::vector<PortInterface*> pruned_ports;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700758 for (PortData& data : ports_) {
759 if (data.port()->Network()->name() == network_name &&
760 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
761 ComparePort(data.port(), best_turn_port) < 0) {
762 data.set_pruned();
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700763 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700764 if (data.port() != newly_pairable_turn_port) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700765 pruned_ports.push_back(data.port());
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700766 }
767 }
768 }
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700769 if (!pruned_ports.empty()) {
770 LOG(LS_INFO) << "Pruned " << pruned_ports.size() << " ports";
771 SignalPortsPruned(this, pruned_ports);
772 }
773 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000774}
775
776void BasicPortAllocatorSession::OnPortComplete(Port* port) {
777 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700778 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000779 PortData* data = FindPort(port);
780 ASSERT(data != NULL);
781
782 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700783 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000784 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700785 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786
787 // Moving to COMPLETE state.
788 data->set_complete();
789 // Send candidate allocation complete signal if this was the last port.
790 MaybeSignalCandidatesAllocationDone();
791}
792
793void BasicPortAllocatorSession::OnPortError(Port* port) {
794 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700795 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000796 PortData* data = FindPort(port);
797 ASSERT(data != NULL);
798 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700799 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000800 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700801 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802
803 // SignalAddressError is currently sent from StunPort/TurnPort.
804 // But this signal itself is generic.
805 data->set_error();
806 // Send candidate allocation complete signal if this was the last port.
807 MaybeSignalCandidatesAllocationDone();
808}
809
810void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
811 ProtocolType proto) {
812 std::vector<Candidate> candidates;
813 for (std::vector<PortData>::iterator it = ports_.begin();
814 it != ports_.end(); ++it) {
815 if (it->sequence() != seq)
816 continue;
817
818 const std::vector<Candidate>& potentials = it->port()->Candidates();
819 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700820 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000821 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700822 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000823 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700824 bool candidate_protocol_enabled =
825 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
826 pvalue == proto;
827 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700828 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
829 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000830 candidates.push_back(potentials[i]);
831 }
832 }
833 }
834
835 if (!candidates.empty()) {
836 SignalCandidatesReady(this, candidates);
837 }
838}
839
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700840bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700841 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000842
843 // When binding to any address, before sending packets out, the getsockname
844 // returns all 0s, but after sending packets, it'll be the NIC used to
845 // send. All 0s is not a valid ICE candidate address and should be filtered
846 // out.
847 if (c.address().IsAnyIP()) {
848 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 }
850
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000851 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000852 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000853 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000854 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000855 } else if (c.type() == LOCAL_PORT_TYPE) {
856 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
857 // We allow host candidates if the filter allows server-reflexive
858 // candidates and the candidate is a public IP. Because we don't generate
859 // server-reflexive candidates if they have the same IP as the host
860 // candidate (i.e. when the host candidate is a public IP), filtering to
861 // only server-reflexive candidates won't work right when the host
862 // candidates have public IPs.
863 return true;
864 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000865
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000866 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000867 }
868 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000869}
870
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700871bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
872 const Port* port) const {
873 bool candidate_signalable = CheckCandidateFilter(c);
874
875 // When device enumeration is disabled (to prevent non-default IP addresses
876 // from leaking), we ping from some local candidates even though we don't
877 // signal them. However, if host candidates are also disabled (for example, to
878 // prevent even default IP addresses from leaking), we still don't want to
879 // ping from them, even if device enumeration is disabled. Thus, we check for
880 // both device enumeration and host candidates being disabled.
881 bool network_enumeration_disabled = c.address().IsAnyIP();
882 bool can_ping_from_candidate =
883 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
884 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
885
886 return candidate_signalable ||
887 (network_enumeration_disabled && can_ping_from_candidate &&
888 !host_candidates_disabled);
889}
890
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891void BasicPortAllocatorSession::OnPortAllocationComplete(
892 AllocationSequence* seq) {
893 // Send candidate allocation complete signal if all ports are done.
894 MaybeSignalCandidatesAllocationDone();
895}
896
897void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700898 if (CandidatesAllocationDone()) {
899 if (pooled()) {
900 LOG(LS_INFO) << "All candidates gathered for pooled session.";
901 } else {
902 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
903 << component() << ":" << generation();
904 }
905 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000907}
908
909void BasicPortAllocatorSession::OnPortDestroyed(
910 PortInterface* port) {
911 ASSERT(rtc::Thread::Current() == network_thread_);
912 for (std::vector<PortData>::iterator iter = ports_.begin();
913 iter != ports_.end(); ++iter) {
914 if (port == iter->port()) {
915 ports_.erase(iter);
916 LOG_J(LS_INFO, port) << "Removed port from allocator ("
917 << static_cast<int>(ports_.size()) << " remaining)";
918 return;
919 }
920 }
921 ASSERT(false);
922}
923
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000924BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
925 Port* port) {
926 for (std::vector<PortData>::iterator it = ports_.begin();
927 it != ports_.end(); ++it) {
928 if (it->port() == port) {
929 return &*it;
930 }
931 }
932 return NULL;
933}
934
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700935// Removes ports and candidates created on a given list of networks.
936void BasicPortAllocatorSession::RemovePortsAndCandidates(
937 const std::vector<rtc::Network*>& networks) {
938 std::vector<PortInterface*> ports_to_remove;
939 std::vector<Candidate> candidates_to_remove;
940 for (PortData& data : ports_) {
941 if (std::find(networks.begin(), networks.end(),
942 data.sequence()->network()) == networks.end()) {
943 continue;
944 }
945 ports_to_remove.push_back(data.port());
946 if (data.has_pairable_candidate()) {
947 GetCandidatesFromPort(data, &candidates_to_remove);
948 // Mark the port as having no pairable candidates so that its candidates
949 // won't be removed multiple times.
950 data.set_has_pairable_candidate(false);
951 }
952 }
953 if (!ports_to_remove.empty()) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700954 LOG(LS_INFO) << "Removed " << ports_to_remove.size() << " ports";
955 SignalPortsPruned(this, ports_to_remove);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700956 }
957 if (!candidates_to_remove.empty()) {
958 SignalCandidatesRemoved(this, candidates_to_remove);
959 }
960}
961
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962// AllocationSequence
963
964AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
965 rtc::Network* network,
966 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200967 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000968 : session_(session),
969 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971 config_(config),
972 state_(kInit),
973 flags_(flags),
974 udp_socket_(),
975 udp_port_(NULL),
976 phase_(0) {
977}
978
979bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000980 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
981 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
982 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
983 session_->allocator()->max_port()));
984 if (udp_socket_) {
985 udp_socket_->SignalReadPacket.connect(
986 this, &AllocationSequence::OnReadPacket);
987 }
988 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
989 // are next available options to setup a communication channel.
990 }
991 return true;
992}
993
994void AllocationSequence::Clear() {
995 udp_port_ = NULL;
996 turn_ports_.clear();
997}
998
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700999void AllocationSequence::OnNetworkFailed() {
1000 RTC_DCHECK(!network_failed_);
1001 network_failed_ = true;
1002 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001003 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001004}
1005
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006AllocationSequence::~AllocationSequence() {
1007 session_->network_thread()->Clear(this);
1008}
1009
1010void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001011 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001012 if (network_failed_) {
1013 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001014 // it won't be equivalent to the new network.
1015 return;
1016 }
1017
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001018 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001019 // Different network setup; nothing is equivalent.
1020 return;
1021 }
1022
1023 // Else turn off the stuff that we've already got covered.
1024
1025 // Every config implicitly specifies local, so turn that off right away.
1026 *flags |= PORTALLOCATOR_DISABLE_UDP;
1027 *flags |= PORTALLOCATOR_DISABLE_TCP;
1028
1029 if (config_ && config) {
1030 if (config_->StunServers() == config->StunServers()) {
1031 // Already got this STUN servers covered.
1032 *flags |= PORTALLOCATOR_DISABLE_STUN;
1033 }
1034 if (!config_->relays.empty()) {
1035 // Already got relays covered.
1036 // NOTE: This will even skip a _different_ set of relay servers if we
1037 // were to be given one, but that never happens in our codebase. Should
1038 // probably get rid of the list in PortConfiguration and just keep a
1039 // single relay server in each one.
1040 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1041 }
1042 }
1043}
1044
1045void AllocationSequence::Start() {
1046 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001047 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048}
1049
1050void AllocationSequence::Stop() {
1051 // If the port is completed, don't set it to stopped.
1052 if (state_ == kRunning) {
1053 state_ = kStopped;
1054 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1055 }
1056}
1057
1058void AllocationSequence::OnMessage(rtc::Message* msg) {
1059 ASSERT(rtc::Thread::Current() == session_->network_thread());
1060 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
1061
1062 const char* const PHASE_NAMES[kNumPhases] = {
1063 "Udp", "Relay", "Tcp", "SslTcp"
1064 };
1065
1066 // Perform all of the phases in the current step.
1067 LOG_J(LS_INFO, network_) << "Allocation Phase="
1068 << PHASE_NAMES[phase_];
1069
1070 switch (phase_) {
1071 case PHASE_UDP:
1072 CreateUDPPorts();
1073 CreateStunPorts();
1074 EnableProtocol(PROTO_UDP);
1075 break;
1076
1077 case PHASE_RELAY:
1078 CreateRelayPorts();
1079 break;
1080
1081 case PHASE_TCP:
1082 CreateTCPPorts();
1083 EnableProtocol(PROTO_TCP);
1084 break;
1085
1086 case PHASE_SSLTCP:
1087 state_ = kCompleted;
1088 EnableProtocol(PROTO_SSLTCP);
1089 break;
1090
1091 default:
1092 ASSERT(false);
1093 }
1094
1095 if (state() == kRunning) {
1096 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001097 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1098 session_->allocator()->step_delay(),
1099 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100 } else {
1101 // If all phases in AllocationSequence are completed, no allocation
1102 // steps needed further. Canceling pending signal.
1103 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1104 SignalPortAllocationComplete(this);
1105 }
1106}
1107
1108void AllocationSequence::EnableProtocol(ProtocolType proto) {
1109 if (!ProtocolEnabled(proto)) {
1110 protocols_.push_back(proto);
1111 session_->OnProtocolEnabled(this, proto);
1112 }
1113}
1114
1115bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1116 for (ProtocolList::const_iterator it = protocols_.begin();
1117 it != protocols_.end(); ++it) {
1118 if (*it == proto)
1119 return true;
1120 }
1121 return false;
1122}
1123
1124void AllocationSequence::CreateUDPPorts() {
1125 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1126 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1127 return;
1128 }
1129
1130 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1131 // is enabled completely.
1132 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001133 bool emit_local_candidate_for_anyaddress =
1134 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001135 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001136 port = UDPPort::Create(
1137 session_->network_thread(), session_->socket_factory(), network_,
1138 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001139 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001140 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001141 port = UDPPort::Create(
1142 session_->network_thread(), session_->socket_factory(), network_, ip_,
1143 session_->allocator()->min_port(), session_->allocator()->max_port(),
1144 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001145 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001146 }
1147
1148 if (port) {
1149 // If shared socket is enabled, STUN candidate will be allocated by the
1150 // UDPPort.
1151 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1152 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001153 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001154
1155 // If STUN is not disabled, setting stun server address to port.
1156 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001157 if (config_ && !config_->StunServers().empty()) {
1158 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1159 << "STUN candidate generation.";
1160 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001161 }
1162 }
1163 }
1164
1165 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001166 }
1167}
1168
1169void AllocationSequence::CreateTCPPorts() {
1170 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1171 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1172 return;
1173 }
1174
1175 Port* port = TCPPort::Create(session_->network_thread(),
1176 session_->socket_factory(),
1177 network_, ip_,
1178 session_->allocator()->min_port(),
1179 session_->allocator()->max_port(),
1180 session_->username(), session_->password(),
1181 session_->allocator()->allow_tcp_listen());
1182 if (port) {
1183 session_->AddAllocatedPort(port, this, true);
1184 // Since TCPPort is not created using shared socket, |port| will not be
1185 // added to the dequeue.
1186 }
1187}
1188
1189void AllocationSequence::CreateStunPorts() {
1190 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1191 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1192 return;
1193 }
1194
1195 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1196 return;
1197 }
1198
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001199 if (!(config_ && !config_->StunServers().empty())) {
1200 LOG(LS_WARNING)
1201 << "AllocationSequence: No STUN server configured, skipping.";
1202 return;
1203 }
1204
1205 StunPort* port = StunPort::Create(session_->network_thread(),
1206 session_->socket_factory(),
1207 network_, ip_,
1208 session_->allocator()->min_port(),
1209 session_->allocator()->max_port(),
1210 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001211 config_->StunServers(),
1212 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001213 if (port) {
1214 session_->AddAllocatedPort(port, this, true);
1215 // Since StunPort is not created using shared socket, |port| will not be
1216 // added to the dequeue.
1217 }
1218}
1219
1220void AllocationSequence::CreateRelayPorts() {
1221 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1222 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1223 return;
1224 }
1225
1226 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1227 // ought to have a relay list for them here.
1228 ASSERT(config_ && !config_->relays.empty());
1229 if (!(config_ && !config_->relays.empty())) {
1230 LOG(LS_WARNING)
1231 << "AllocationSequence: No relay server configured, skipping.";
1232 return;
1233 }
1234
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001235 for (RelayServerConfig& relay : config_->relays) {
1236 if (relay.type == RELAY_GTURN) {
1237 CreateGturnPort(relay);
1238 } else if (relay.type == RELAY_TURN) {
1239 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240 } else {
1241 ASSERT(false);
1242 }
1243 }
1244}
1245
1246void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1247 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1248 RelayPort* port = RelayPort::Create(session_->network_thread(),
1249 session_->socket_factory(),
1250 network_, ip_,
1251 session_->allocator()->min_port(),
1252 session_->allocator()->max_port(),
1253 config_->username, config_->password);
1254 if (port) {
1255 // Since RelayPort is not created using shared socket, |port| will not be
1256 // added to the dequeue.
1257 // Note: We must add the allocated port before we add addresses because
1258 // the latter will create candidates that need name and preference
1259 // settings. However, we also can't prepare the address (normally
1260 // done by AddAllocatedPort) until we have these addresses. So we
1261 // wait to do that until below.
1262 session_->AddAllocatedPort(port, this, false);
1263
1264 // Add the addresses of this protocol.
1265 PortList::const_iterator relay_port;
1266 for (relay_port = config.ports.begin();
1267 relay_port != config.ports.end();
1268 ++relay_port) {
1269 port->AddServerAddress(*relay_port);
1270 port->AddExternalAddress(*relay_port);
1271 }
1272 // Start fetching an address for this port.
1273 port->PrepareAddress();
1274 }
1275}
1276
1277void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1278 PortList::const_iterator relay_port;
1279 for (relay_port = config.ports.begin();
1280 relay_port != config.ports.end(); ++relay_port) {
1281 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001282
1283 // Skip UDP connections to relay servers if it's disallowed.
1284 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1285 relay_port->proto == PROTO_UDP) {
1286 continue;
1287 }
1288
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001289 // Shared socket mode must be enabled only for UDP based ports. Hence
1290 // don't pass shared socket for ports which will create TCP sockets.
1291 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1292 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1293 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001294 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001295 port = TurnPort::Create(session_->network_thread(),
1296 session_->socket_factory(),
1297 network_, udp_socket_.get(),
1298 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001299 *relay_port, config.credentials, config.priority,
1300 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001301 turn_ports_.push_back(port);
1302 // Listen to the port destroyed signal, to allow AllocationSequence to
1303 // remove entrt from it's map.
1304 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1305 } else {
1306 port = TurnPort::Create(session_->network_thread(),
1307 session_->socket_factory(),
1308 network_, ip_,
1309 session_->allocator()->min_port(),
1310 session_->allocator()->max_port(),
1311 session_->username(),
1312 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001313 *relay_port, config.credentials, config.priority,
1314 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001315 }
1316 ASSERT(port != NULL);
1317 session_->AddAllocatedPort(port, this, true);
1318 }
1319}
1320
1321void AllocationSequence::OnReadPacket(
1322 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1323 const rtc::SocketAddress& remote_addr,
1324 const rtc::PacketTime& packet_time) {
1325 ASSERT(socket == udp_socket_.get());
1326
1327 bool turn_port_found = false;
1328
1329 // Try to find the TurnPort that matches the remote address. Note that the
1330 // message could be a STUN binding response if the TURN server is also used as
1331 // a STUN server. We don't want to parse every message here to check if it is
1332 // a STUN binding response, so we pass the message to TurnPort regardless of
1333 // the message type. The TurnPort will just ignore the message since it will
1334 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001335 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001337 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1338 packet_time)) {
1339 return;
1340 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001341 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001342 }
1343 }
1344
1345 if (udp_port_) {
1346 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1347
1348 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1349 // the TURN server is also a STUN server.
1350 if (!turn_port_found ||
1351 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001352 RTC_DCHECK(udp_port_->SharedSocket());
1353 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1354 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001355 }
1356 }
1357}
1358
1359void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1360 if (udp_port_ == port) {
1361 udp_port_ = NULL;
1362 return;
1363 }
1364
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001365 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1366 if (it != turn_ports_.end()) {
1367 turn_ports_.erase(it);
1368 } else {
1369 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1370 ASSERT(false);
1371 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001372}
1373
1374// PortConfiguration
1375PortConfiguration::PortConfiguration(
1376 const rtc::SocketAddress& stun_address,
1377 const std::string& username,
1378 const std::string& password)
1379 : stun_address(stun_address), username(username), password(password) {
1380 if (!stun_address.IsNil())
1381 stun_servers.insert(stun_address);
1382}
1383
1384PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1385 const std::string& username,
1386 const std::string& password)
1387 : stun_servers(stun_servers),
1388 username(username),
1389 password(password) {
1390 if (!stun_servers.empty())
1391 stun_address = *(stun_servers.begin());
1392}
1393
1394ServerAddresses PortConfiguration::StunServers() {
1395 if (!stun_address.IsNil() &&
1396 stun_servers.find(stun_address) == stun_servers.end()) {
1397 stun_servers.insert(stun_address);
1398 }
deadbeefc5d0d952015-07-16 10:22:21 -07001399 // Every UDP TURN server should also be used as a STUN server.
1400 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1401 for (const rtc::SocketAddress& turn_server : turn_servers) {
1402 if (stun_servers.find(turn_server) == stun_servers.end()) {
1403 stun_servers.insert(turn_server);
1404 }
1405 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001406 return stun_servers;
1407}
1408
1409void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1410 relays.push_back(config);
1411}
1412
1413bool PortConfiguration::SupportsProtocol(
1414 const RelayServerConfig& relay, ProtocolType type) const {
1415 PortList::const_iterator relay_port;
1416 for (relay_port = relay.ports.begin();
1417 relay_port != relay.ports.end();
1418 ++relay_port) {
1419 if (relay_port->proto == type)
1420 return true;
1421 }
1422 return false;
1423}
1424
1425bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1426 ProtocolType type) const {
1427 for (size_t i = 0; i < relays.size(); ++i) {
1428 if (relays[i].type == turn_type &&
1429 SupportsProtocol(relays[i], type))
1430 return true;
1431 }
1432 return false;
1433}
1434
1435ServerAddresses PortConfiguration::GetRelayServerAddresses(
1436 RelayType turn_type, ProtocolType type) const {
1437 ServerAddresses servers;
1438 for (size_t i = 0; i < relays.size(); ++i) {
1439 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1440 servers.insert(relays[i].ports.front().address);
1441 }
1442 }
1443 return servers;
1444}
1445
1446} // namespace cricket