blob: f343b352ee49fd6a97c403a08363ea22efe2a956 [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
13#include <string>
14#include <vector>
15
16#include "webrtc/p2p/base/basicpacketsocketfactory.h"
17#include "webrtc/p2p/base/common.h"
18#include "webrtc/p2p/base/port.h"
19#include "webrtc/p2p/base/relayport.h"
20#include "webrtc/p2p/base/stunport.h"
21#include "webrtc/p2p/base/tcpport.h"
22#include "webrtc/p2p/base/turnport.h"
23#include "webrtc/p2p/base/udpport.h"
Guo-wei Shieh38f88932015-08-13 22:24:02 -070024#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000025#include "webrtc/base/common.h"
26#include "webrtc/base/helpers.h"
27#include "webrtc/base/logging.h"
28
29using rtc::CreateRandomId;
30using rtc::CreateRandomString;
31
32namespace {
33
34enum {
35 MSG_CONFIG_START,
36 MSG_CONFIG_READY,
37 MSG_ALLOCATE,
38 MSG_ALLOCATION_PHASE,
39 MSG_SHAKE,
40 MSG_SEQUENCEOBJECTS_CREATED,
41 MSG_CONFIG_STOP,
42};
43
44const int PHASE_UDP = 0;
45const int PHASE_RELAY = 1;
46const int PHASE_TCP = 2;
47const int PHASE_SSLTCP = 3;
48
49const int kNumPhases = 4;
50
51const int SHAKE_MIN_DELAY = 45 * 1000; // 45 seconds
52const int SHAKE_MAX_DELAY = 90 * 1000; // 90 seconds
53
54int ShakeDelay() {
55 int range = SHAKE_MAX_DELAY - SHAKE_MIN_DELAY + 1;
56 return SHAKE_MIN_DELAY + CreateRandomId() % range;
57}
58
59} // namespace
60
61namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000062const uint32 DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070063 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
64 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000065
66// BasicPortAllocator
67BasicPortAllocator::BasicPortAllocator(
68 rtc::NetworkManager* network_manager,
69 rtc::PacketSocketFactory* socket_factory)
70 : network_manager_(network_manager),
eblima894ad942015-07-03 08:34:33 -070071 socket_factory_(socket_factory),
72 stun_servers_() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073 ASSERT(socket_factory_ != NULL);
74 Construct();
75}
76
77BasicPortAllocator::BasicPortAllocator(
78 rtc::NetworkManager* network_manager)
79 : network_manager_(network_manager),
eblima894ad942015-07-03 08:34:33 -070080 socket_factory_(NULL),
81 stun_servers_() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000082 Construct();
83}
84
85BasicPortAllocator::BasicPortAllocator(
86 rtc::NetworkManager* network_manager,
87 rtc::PacketSocketFactory* socket_factory,
88 const ServerAddresses& stun_servers)
89 : network_manager_(network_manager),
90 socket_factory_(socket_factory),
91 stun_servers_(stun_servers) {
92 ASSERT(socket_factory_ != NULL);
93 Construct();
94}
95
96BasicPortAllocator::BasicPortAllocator(
97 rtc::NetworkManager* network_manager,
98 const ServerAddresses& stun_servers,
99 const rtc::SocketAddress& relay_address_udp,
100 const rtc::SocketAddress& relay_address_tcp,
101 const rtc::SocketAddress& relay_address_ssl)
102 : network_manager_(network_manager),
103 socket_factory_(NULL),
104 stun_servers_(stun_servers) {
105
106 RelayServerConfig config(RELAY_GTURN);
107 if (!relay_address_udp.IsNil())
108 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
109 if (!relay_address_tcp.IsNil())
110 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
111 if (!relay_address_ssl.IsNil())
112 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
113
114 if (!config.ports.empty())
115 AddRelay(config);
116
117 Construct();
118}
119
120void BasicPortAllocator::Construct() {
121 allow_tcp_listen_ = true;
122}
123
124BasicPortAllocator::~BasicPortAllocator() {
125}
126
deadbeefc5d0d952015-07-16 10:22:21 -0700127PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000128 const std::string& content_name, int component,
129 const std::string& ice_ufrag, const std::string& ice_pwd) {
130 return new BasicPortAllocatorSession(
131 this, content_name, component, ice_ufrag, ice_pwd);
132}
133
134
135// BasicPortAllocatorSession
136BasicPortAllocatorSession::BasicPortAllocatorSession(
137 BasicPortAllocator *allocator,
138 const std::string& content_name,
139 int component,
140 const std::string& ice_ufrag,
141 const std::string& ice_pwd)
142 : PortAllocatorSession(content_name, component,
143 ice_ufrag, ice_pwd, allocator->flags()),
144 allocator_(allocator), network_thread_(NULL),
145 socket_factory_(allocator->socket_factory()),
146 allocation_started_(false),
147 network_manager_started_(false),
148 running_(false),
149 allocation_sequences_created_(false) {
150 allocator_->network_manager()->SignalNetworksChanged.connect(
151 this, &BasicPortAllocatorSession::OnNetworksChanged);
152 allocator_->network_manager()->StartUpdating();
153}
154
155BasicPortAllocatorSession::~BasicPortAllocatorSession() {
156 allocator_->network_manager()->StopUpdating();
157 if (network_thread_ != NULL)
158 network_thread_->Clear(this);
159
160 for (uint32 i = 0; i < sequences_.size(); ++i) {
161 // AllocationSequence should clear it's map entry for turn ports before
162 // ports are destroyed.
163 sequences_[i]->Clear();
164 }
165
166 std::vector<PortData>::iterator it;
167 for (it = ports_.begin(); it != ports_.end(); it++)
168 delete it->port();
169
170 for (uint32 i = 0; i < configs_.size(); ++i)
171 delete configs_[i];
172
173 for (uint32 i = 0; i < sequences_.size(); ++i)
174 delete sequences_[i];
175}
176
177void BasicPortAllocatorSession::StartGettingPorts() {
178 network_thread_ = rtc::Thread::Current();
179 if (!socket_factory_) {
180 owned_socket_factory_.reset(
181 new rtc::BasicPacketSocketFactory(network_thread_));
182 socket_factory_ = owned_socket_factory_.get();
183 }
184
185 running_ = true;
186 network_thread_->Post(this, MSG_CONFIG_START);
187
188 if (flags() & PORTALLOCATOR_ENABLE_SHAKER)
189 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
190}
191
192void BasicPortAllocatorSession::StopGettingPorts() {
193 ASSERT(rtc::Thread::Current() == network_thread_);
194 running_ = false;
honghaiz98db68f2015-09-29 07:58:17 -0700195 network_thread_->Post(this, MSG_CONFIG_STOP);
196 ClearGettingPorts();
197}
198
199void BasicPortAllocatorSession::ClearGettingPorts() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 network_thread_->Clear(this, MSG_ALLOCATE);
201 for (uint32 i = 0; i < sequences_.size(); ++i)
202 sequences_[i]->Stop();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203}
204
205void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
206 switch (message->message_id) {
207 case MSG_CONFIG_START:
208 ASSERT(rtc::Thread::Current() == network_thread_);
209 GetPortConfigurations();
210 break;
211
212 case MSG_CONFIG_READY:
213 ASSERT(rtc::Thread::Current() == network_thread_);
214 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
215 break;
216
217 case MSG_ALLOCATE:
218 ASSERT(rtc::Thread::Current() == network_thread_);
219 OnAllocate();
220 break;
221
222 case MSG_SHAKE:
223 ASSERT(rtc::Thread::Current() == network_thread_);
224 OnShake();
225 break;
226 case MSG_SEQUENCEOBJECTS_CREATED:
227 ASSERT(rtc::Thread::Current() == network_thread_);
228 OnAllocationSequenceObjectsCreated();
229 break;
230 case MSG_CONFIG_STOP:
231 ASSERT(rtc::Thread::Current() == network_thread_);
232 OnConfigStop();
233 break;
234 default:
235 ASSERT(false);
236 }
237}
238
239void BasicPortAllocatorSession::GetPortConfigurations() {
240 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
241 username(),
242 password());
243
244 for (size_t i = 0; i < allocator_->relays().size(); ++i) {
245 config->AddRelay(allocator_->relays()[i]);
246 }
247 ConfigReady(config);
248}
249
250void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
251 network_thread_->Post(this, MSG_CONFIG_READY, config);
252}
253
254// Adds a configuration to the list.
255void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
256 if (config)
257 configs_.push_back(config);
258
259 AllocatePorts();
260}
261
262void BasicPortAllocatorSession::OnConfigStop() {
263 ASSERT(rtc::Thread::Current() == network_thread_);
264
265 // If any of the allocated ports have not completed the candidates allocation,
266 // mark those as error. Since session doesn't need any new candidates
267 // at this stage of the allocation, it's safe to discard any new candidates.
268 bool send_signal = false;
269 for (std::vector<PortData>::iterator it = ports_.begin();
270 it != ports_.end(); ++it) {
271 if (!it->complete()) {
272 // Updating port state to error, which didn't finish allocating candidates
273 // yet.
274 it->set_error();
275 send_signal = true;
276 }
277 }
278
279 // Did we stop any running sequences?
280 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
281 it != sequences_.end() && !send_signal; ++it) {
282 if ((*it)->state() == AllocationSequence::kStopped) {
283 send_signal = true;
284 }
285 }
286
287 // If we stopped anything that was running, send a done signal now.
288 if (send_signal) {
289 MaybeSignalCandidatesAllocationDone();
290 }
291}
292
293void BasicPortAllocatorSession::AllocatePorts() {
294 ASSERT(rtc::Thread::Current() == network_thread_);
295 network_thread_->Post(this, MSG_ALLOCATE);
296}
297
298void BasicPortAllocatorSession::OnAllocate() {
299 if (network_manager_started_)
300 DoAllocate();
301
302 allocation_started_ = true;
303}
304
honghaiz8c404fa2015-09-28 07:59:43 -0700305void BasicPortAllocatorSession::GetNetworks(
306 std::vector<rtc::Network*>* networks) {
307 networks->clear();
308 rtc::NetworkManager* network_manager = allocator_->network_manager();
309 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700310 // If the network permission state is BLOCKED, we just act as if the flag has
311 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700312 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700313 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700314 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
315 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000316 // If the adapter enumeration is disabled, we'll just bind to any address
317 // instead of specific NIC. This is to ensure the same routing for http
318 // traffic by OS is also used here to avoid any local or public IP leakage
319 // during stun process.
320 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
honghaiz8c404fa2015-09-28 07:59:43 -0700321 network_manager->GetAnyAddressNetworks(networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000322 } else {
honghaiz8c404fa2015-09-28 07:59:43 -0700323 network_manager->GetNetworks(networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000324 }
honghaiz8c404fa2015-09-28 07:59:43 -0700325}
326
327// For each network, see if we have a sequence that covers it already. If not,
328// create a new sequence to create the appropriate ports.
329void BasicPortAllocatorSession::DoAllocate() {
330 bool done_signal_needed = false;
331 std::vector<rtc::Network*> networks;
332 GetNetworks(&networks);
333
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000334 if (networks.empty()) {
335 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
336 done_signal_needed = true;
337 } else {
338 for (uint32 i = 0; i < networks.size(); ++i) {
339 PortConfiguration* config = NULL;
340 if (configs_.size() > 0)
341 config = configs_.back();
342
343 uint32 sequence_flags = flags();
344 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
345 // If all the ports are disabled we should just fire the allocation
346 // done event and return.
347 done_signal_needed = true;
348 break;
349 }
350
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351 if (!config || config->relays.empty()) {
352 // No relay ports specified in this config.
353 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
354 }
355
356 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000357 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000358 // Skip IPv6 networks unless the flag's been set.
359 continue;
360 }
361
362 // Disable phases that would only create ports equivalent to
363 // ones that we have already made.
364 DisableEquivalentPhases(networks[i], config, &sequence_flags);
365
366 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
367 // New AllocationSequence would have nothing to do, so don't make it.
368 continue;
369 }
370
371 AllocationSequence* sequence =
372 new AllocationSequence(this, networks[i], config, sequence_flags);
373 if (!sequence->Init()) {
374 delete sequence;
375 continue;
376 }
377 done_signal_needed = true;
378 sequence->SignalPortAllocationComplete.connect(
379 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
380 if (running_)
381 sequence->Start();
382 sequences_.push_back(sequence);
383 }
384 }
385 if (done_signal_needed) {
386 network_thread_->Post(this, MSG_SEQUENCEOBJECTS_CREATED);
387 }
388}
389
390void BasicPortAllocatorSession::OnNetworksChanged() {
honghaiz8c404fa2015-09-28 07:59:43 -0700391 std::vector<rtc::Network*> networks;
392 GetNetworks(&networks);
393 for (AllocationSequence* sequence : sequences_) {
394 // Remove the network from the allocation sequence if it is not in
395 // |networks|.
396 if (!sequence->network_removed() &&
397 std::find(networks.begin(), networks.end(), sequence->network()) ==
398 networks.end()) {
399 sequence->OnNetworkRemoved();
400 }
401 }
402
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 network_manager_started_ = true;
404 if (allocation_started_)
405 DoAllocate();
406}
407
408void BasicPortAllocatorSession::DisableEquivalentPhases(
409 rtc::Network* network, PortConfiguration* config, uint32* flags) {
410 for (uint32 i = 0; i < sequences_.size() &&
411 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES; ++i) {
412 sequences_[i]->DisableEquivalentPhases(network, config, flags);
413 }
414}
415
416void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
417 AllocationSequence * seq,
418 bool prepare_address) {
419 if (!port)
420 return;
421
422 LOG(LS_INFO) << "Adding allocated port for " << content_name();
423 port->set_content_name(content_name());
424 port->set_component(component_);
425 port->set_generation(generation());
426 if (allocator_->proxy().type != rtc::PROXY_NONE)
427 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
428 port->set_send_retransmit_count_attribute((allocator_->flags() &
429 PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
430
431 // Push down the candidate_filter to individual port.
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000432 uint32 candidate_filter = allocator_->candidate_filter();
433
434 // When adapter enumeration is disabled, disable CF_HOST at port level so
435 // local address is not leaked by stunport in the candidate's related address.
436 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
437 candidate_filter &= ~CF_HOST;
438 }
439 port->set_candidate_filter(candidate_filter);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440
441 PortData data(port, seq);
442 ports_.push_back(data);
443
444 port->SignalCandidateReady.connect(
445 this, &BasicPortAllocatorSession::OnCandidateReady);
446 port->SignalPortComplete.connect(this,
447 &BasicPortAllocatorSession::OnPortComplete);
448 port->SignalDestroyed.connect(this,
449 &BasicPortAllocatorSession::OnPortDestroyed);
450 port->SignalPortError.connect(
451 this, &BasicPortAllocatorSession::OnPortError);
452 LOG_J(LS_INFO, port) << "Added port to allocator";
453
454 if (prepare_address)
455 port->PrepareAddress();
456}
457
458void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
459 allocation_sequences_created_ = true;
460 // Send candidate allocation complete signal if we have no sequences.
461 MaybeSignalCandidatesAllocationDone();
462}
463
464void BasicPortAllocatorSession::OnCandidateReady(
465 Port* port, const Candidate& c) {
466 ASSERT(rtc::Thread::Current() == network_thread_);
467 PortData* data = FindPort(port);
468 ASSERT(data != NULL);
469 // Discarding any candidate signal if port allocation status is
470 // already in completed state.
471 if (data->complete())
472 return;
473
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700475 bool candidate_signalable = CheckCandidateFilter(c);
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700476
477 // When device enumeration is disabled (to prevent non-default IP addresses
478 // from leaking), we ping from some local candidates even though we don't
479 // signal them. However, if host candidates are also disabled (for example, to
480 // prevent even default IP addresses from leaking), we still don't want to
481 // ping from them, even if device enumeration is disabled. Thus, we check for
482 // both device enumeration and host candidates being disabled.
483 bool network_enumeration_disabled = c.address().IsAnyIP();
484 bool can_ping_from_candidate =
485 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
486 bool host_canidates_disabled = !(allocator_->candidate_filter() & CF_HOST);
487
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700488 bool candidate_pairable =
489 candidate_signalable ||
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700490 (network_enumeration_disabled && can_ping_from_candidate &&
491 !host_canidates_disabled);
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700492 bool candidate_protocol_enabled =
493 StringToProto(c.protocol().c_str(), &pvalue) &&
494 data->sequence()->ProtocolEnabled(pvalue);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000495
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700496 if (candidate_signalable && candidate_protocol_enabled) {
497 std::vector<Candidate> candidates;
498 candidates.push_back(c);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000499 SignalCandidatesReady(this, candidates);
500 }
501
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700502 // Port has been made ready. Nothing to do here.
503 if (data->ready()) {
504 return;
505 }
506
507 // Move the port to the READY state, either because we have a usable candidate
508 // from the port, or simply because the port is bound to the any address and
509 // therefore has no host candidate. This will trigger the port to start
510 // creating candidate pairs (connections) and issue connectivity checks.
511 if (candidate_pairable) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000512 data->set_ready();
513 SignalPortReady(this, port);
514 }
515}
516
517void BasicPortAllocatorSession::OnPortComplete(Port* port) {
518 ASSERT(rtc::Thread::Current() == network_thread_);
519 PortData* data = FindPort(port);
520 ASSERT(data != NULL);
521
522 // Ignore any late signals.
523 if (data->complete())
524 return;
525
526 // Moving to COMPLETE state.
527 data->set_complete();
528 // Send candidate allocation complete signal if this was the last port.
529 MaybeSignalCandidatesAllocationDone();
530}
531
532void BasicPortAllocatorSession::OnPortError(Port* port) {
533 ASSERT(rtc::Thread::Current() == network_thread_);
534 PortData* data = FindPort(port);
535 ASSERT(data != NULL);
536 // We might have already given up on this port and stopped it.
537 if (data->complete())
538 return;
539
540 // SignalAddressError is currently sent from StunPort/TurnPort.
541 // But this signal itself is generic.
542 data->set_error();
543 // Send candidate allocation complete signal if this was the last port.
544 MaybeSignalCandidatesAllocationDone();
545}
546
547void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
548 ProtocolType proto) {
549 std::vector<Candidate> candidates;
550 for (std::vector<PortData>::iterator it = ports_.begin();
551 it != ports_.end(); ++it) {
552 if (it->sequence() != seq)
553 continue;
554
555 const std::vector<Candidate>& potentials = it->port()->Candidates();
556 for (size_t i = 0; i < potentials.size(); ++i) {
557 if (!CheckCandidateFilter(potentials[i]))
558 continue;
559 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700560 bool candidate_protocol_enabled =
561 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
562 pvalue == proto;
563 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000564 candidates.push_back(potentials[i]);
565 }
566 }
567 }
568
569 if (!candidates.empty()) {
570 SignalCandidatesReady(this, candidates);
571 }
572}
573
574bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) {
575 uint32 filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000576
577 // When binding to any address, before sending packets out, the getsockname
578 // returns all 0s, but after sending packets, it'll be the NIC used to
579 // send. All 0s is not a valid ICE candidate address and should be filtered
580 // out.
581 if (c.address().IsAnyIP()) {
582 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583 }
584
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000585 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000586 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000587 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000588 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000589 } else if (c.type() == LOCAL_PORT_TYPE) {
590 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
591 // We allow host candidates if the filter allows server-reflexive
592 // candidates and the candidate is a public IP. Because we don't generate
593 // server-reflexive candidates if they have the same IP as the host
594 // candidate (i.e. when the host candidate is a public IP), filtering to
595 // only server-reflexive candidates won't work right when the host
596 // candidates have public IPs.
597 return true;
598 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000599
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700600 // If PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE is specified and it's
601 // loopback address, we should allow it as it's for demo page connectivity
602 // when no TURN/STUN specified.
603 if (c.address().IsLoopbackIP() &&
604 (flags() & PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE) != 0) {
605 return true;
606 }
607
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000608 // This is just to prevent the case when binding to any address (all 0s), if
609 // somehow the host candidate address is not all 0s. Either because local
610 // installed proxy changes the address or a packet has been sent for any
611 // reason before getsockname is called.
612 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
613 LOG(LS_WARNING) << "Received non-0 host address: "
614 << c.address().ToString()
615 << " when adapter enumeration is disabled";
616 return false;
617 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000618
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000619 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000620 }
621 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000622}
623
624void BasicPortAllocatorSession::OnPortAllocationComplete(
625 AllocationSequence* seq) {
626 // Send candidate allocation complete signal if all ports are done.
627 MaybeSignalCandidatesAllocationDone();
628}
629
630void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
631 // Send signal only if all required AllocationSequence objects
632 // are created.
633 if (!allocation_sequences_created_)
634 return;
635
636 // Check that all port allocation sequences are complete.
637 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
638 it != sequences_.end(); ++it) {
639 if ((*it)->state() == AllocationSequence::kRunning)
640 return;
641 }
642
643 // If all allocated ports are in complete state, session must have got all
644 // expected candidates. Session will trigger candidates allocation complete
645 // signal.
646 for (std::vector<PortData>::iterator it = ports_.begin();
647 it != ports_.end(); ++it) {
648 if (!it->complete())
649 return;
650 }
651 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
652 << component_ << ":" << generation();
653 SignalCandidatesAllocationDone(this);
654}
655
656void BasicPortAllocatorSession::OnPortDestroyed(
657 PortInterface* port) {
658 ASSERT(rtc::Thread::Current() == network_thread_);
659 for (std::vector<PortData>::iterator iter = ports_.begin();
660 iter != ports_.end(); ++iter) {
661 if (port == iter->port()) {
662 ports_.erase(iter);
663 LOG_J(LS_INFO, port) << "Removed port from allocator ("
664 << static_cast<int>(ports_.size()) << " remaining)";
665 return;
666 }
667 }
668 ASSERT(false);
669}
670
671void BasicPortAllocatorSession::OnShake() {
672 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
673
674 std::vector<Port*> ports;
675 std::vector<Connection*> connections;
676
677 for (size_t i = 0; i < ports_.size(); ++i) {
678 if (ports_[i].ready())
679 ports.push_back(ports_[i].port());
680 }
681
682 for (size_t i = 0; i < ports.size(); ++i) {
683 Port::AddressMap::const_iterator iter;
684 for (iter = ports[i]->connections().begin();
685 iter != ports[i]->connections().end();
686 ++iter) {
687 connections.push_back(iter->second);
688 }
689 }
690
691 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
692 << connections.size() << " connections";
693
694 for (size_t i = 0; i < connections.size(); ++i)
695 connections[i]->Destroy();
696
697 if (running_ || (ports.size() > 0) || (connections.size() > 0))
698 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
699}
700
701BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
702 Port* port) {
703 for (std::vector<PortData>::iterator it = ports_.begin();
704 it != ports_.end(); ++it) {
705 if (it->port() == port) {
706 return &*it;
707 }
708 }
709 return NULL;
710}
711
712// AllocationSequence
713
714AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
715 rtc::Network* network,
716 PortConfiguration* config,
717 uint32 flags)
718 : session_(session),
719 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000720 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721 config_(config),
722 state_(kInit),
723 flags_(flags),
724 udp_socket_(),
725 udp_port_(NULL),
726 phase_(0) {
727}
728
729bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000730 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
731 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
732 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
733 session_->allocator()->max_port()));
734 if (udp_socket_) {
735 udp_socket_->SignalReadPacket.connect(
736 this, &AllocationSequence::OnReadPacket);
737 }
738 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
739 // are next available options to setup a communication channel.
740 }
741 return true;
742}
743
744void AllocationSequence::Clear() {
745 udp_port_ = NULL;
746 turn_ports_.clear();
747}
748
honghaiz8c404fa2015-09-28 07:59:43 -0700749void AllocationSequence::OnNetworkRemoved() {
750 // Stop the allocation sequence if its network is gone.
751 Stop();
752 network_removed_ = true;
753}
754
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755AllocationSequence::~AllocationSequence() {
756 session_->network_thread()->Clear(this);
757}
758
759void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
760 PortConfiguration* config, uint32* flags) {
honghaiz8c404fa2015-09-28 07:59:43 -0700761 if (network_removed_) {
762 // If the network of this allocation sequence has ever gone away,
763 // it won't be equivalent to the new network.
764 return;
765 }
766
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000767 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000768 // Different network setup; nothing is equivalent.
769 return;
770 }
771
772 // Else turn off the stuff that we've already got covered.
773
774 // Every config implicitly specifies local, so turn that off right away.
775 *flags |= PORTALLOCATOR_DISABLE_UDP;
776 *flags |= PORTALLOCATOR_DISABLE_TCP;
777
778 if (config_ && config) {
779 if (config_->StunServers() == config->StunServers()) {
780 // Already got this STUN servers covered.
781 *flags |= PORTALLOCATOR_DISABLE_STUN;
782 }
783 if (!config_->relays.empty()) {
784 // Already got relays covered.
785 // NOTE: This will even skip a _different_ set of relay servers if we
786 // were to be given one, but that never happens in our codebase. Should
787 // probably get rid of the list in PortConfiguration and just keep a
788 // single relay server in each one.
789 *flags |= PORTALLOCATOR_DISABLE_RELAY;
790 }
791 }
792}
793
794void AllocationSequence::Start() {
795 state_ = kRunning;
796 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
797}
798
799void AllocationSequence::Stop() {
800 // If the port is completed, don't set it to stopped.
801 if (state_ == kRunning) {
802 state_ = kStopped;
803 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
804 }
805}
806
807void AllocationSequence::OnMessage(rtc::Message* msg) {
808 ASSERT(rtc::Thread::Current() == session_->network_thread());
809 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
810
811 const char* const PHASE_NAMES[kNumPhases] = {
812 "Udp", "Relay", "Tcp", "SslTcp"
813 };
814
815 // Perform all of the phases in the current step.
816 LOG_J(LS_INFO, network_) << "Allocation Phase="
817 << PHASE_NAMES[phase_];
818
819 switch (phase_) {
820 case PHASE_UDP:
821 CreateUDPPorts();
822 CreateStunPorts();
823 EnableProtocol(PROTO_UDP);
824 break;
825
826 case PHASE_RELAY:
827 CreateRelayPorts();
828 break;
829
830 case PHASE_TCP:
831 CreateTCPPorts();
832 EnableProtocol(PROTO_TCP);
833 break;
834
835 case PHASE_SSLTCP:
836 state_ = kCompleted;
837 EnableProtocol(PROTO_SSLTCP);
838 break;
839
840 default:
841 ASSERT(false);
842 }
843
844 if (state() == kRunning) {
845 ++phase_;
846 session_->network_thread()->PostDelayed(
847 session_->allocator()->step_delay(),
848 this, MSG_ALLOCATION_PHASE);
849 } else {
850 // If all phases in AllocationSequence are completed, no allocation
851 // steps needed further. Canceling pending signal.
852 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
853 SignalPortAllocationComplete(this);
854 }
855}
856
857void AllocationSequence::EnableProtocol(ProtocolType proto) {
858 if (!ProtocolEnabled(proto)) {
859 protocols_.push_back(proto);
860 session_->OnProtocolEnabled(this, proto);
861 }
862}
863
864bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
865 for (ProtocolList::const_iterator it = protocols_.begin();
866 it != protocols_.end(); ++it) {
867 if (*it == proto)
868 return true;
869 }
870 return false;
871}
872
873void AllocationSequence::CreateUDPPorts() {
874 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
875 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
876 return;
877 }
878
879 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
880 // is enabled completely.
881 UDPPort* port = NULL;
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700882 bool emit_localhost_for_anyaddress =
883 IsFlagSet(PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700885 port = UDPPort::Create(
886 session_->network_thread(), session_->socket_factory(), network_,
887 udp_socket_.get(), session_->username(), session_->password(),
888 session_->allocator()->origin(), emit_localhost_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700890 port = UDPPort::Create(
891 session_->network_thread(), session_->socket_factory(), network_, ip_,
892 session_->allocator()->min_port(), session_->allocator()->max_port(),
893 session_->username(), session_->password(),
894 session_->allocator()->origin(), emit_localhost_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 }
896
897 if (port) {
898 // If shared socket is enabled, STUN candidate will be allocated by the
899 // UDPPort.
900 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
901 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000902 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903
904 // If STUN is not disabled, setting stun server address to port.
905 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 if (config_ && !config_->StunServers().empty()) {
907 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
908 << "STUN candidate generation.";
909 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910 }
911 }
912 }
913
914 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 }
916}
917
918void AllocationSequence::CreateTCPPorts() {
919 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
920 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
921 return;
922 }
923
924 Port* port = TCPPort::Create(session_->network_thread(),
925 session_->socket_factory(),
926 network_, ip_,
927 session_->allocator()->min_port(),
928 session_->allocator()->max_port(),
929 session_->username(), session_->password(),
930 session_->allocator()->allow_tcp_listen());
931 if (port) {
932 session_->AddAllocatedPort(port, this, true);
933 // Since TCPPort is not created using shared socket, |port| will not be
934 // added to the dequeue.
935 }
936}
937
938void AllocationSequence::CreateStunPorts() {
939 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
940 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
941 return;
942 }
943
944 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
945 return;
946 }
947
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000948 if (!(config_ && !config_->StunServers().empty())) {
949 LOG(LS_WARNING)
950 << "AllocationSequence: No STUN server configured, skipping.";
951 return;
952 }
953
954 StunPort* port = StunPort::Create(session_->network_thread(),
955 session_->socket_factory(),
956 network_, ip_,
957 session_->allocator()->min_port(),
958 session_->allocator()->max_port(),
959 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000960 config_->StunServers(),
961 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000962 if (port) {
963 session_->AddAllocatedPort(port, this, true);
964 // Since StunPort is not created using shared socket, |port| will not be
965 // added to the dequeue.
966 }
967}
968
969void AllocationSequence::CreateRelayPorts() {
970 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
971 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
972 return;
973 }
974
975 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
976 // ought to have a relay list for them here.
977 ASSERT(config_ && !config_->relays.empty());
978 if (!(config_ && !config_->relays.empty())) {
979 LOG(LS_WARNING)
980 << "AllocationSequence: No relay server configured, skipping.";
981 return;
982 }
983
984 PortConfiguration::RelayList::const_iterator relay;
985 for (relay = config_->relays.begin();
986 relay != config_->relays.end(); ++relay) {
987 if (relay->type == RELAY_GTURN) {
988 CreateGturnPort(*relay);
989 } else if (relay->type == RELAY_TURN) {
990 CreateTurnPort(*relay);
991 } else {
992 ASSERT(false);
993 }
994 }
995}
996
997void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
998 // TODO(mallinath) - Rename RelayPort to GTurnPort.
999 RelayPort* port = RelayPort::Create(session_->network_thread(),
1000 session_->socket_factory(),
1001 network_, ip_,
1002 session_->allocator()->min_port(),
1003 session_->allocator()->max_port(),
1004 config_->username, config_->password);
1005 if (port) {
1006 // Since RelayPort is not created using shared socket, |port| will not be
1007 // added to the dequeue.
1008 // Note: We must add the allocated port before we add addresses because
1009 // the latter will create candidates that need name and preference
1010 // settings. However, we also can't prepare the address (normally
1011 // done by AddAllocatedPort) until we have these addresses. So we
1012 // wait to do that until below.
1013 session_->AddAllocatedPort(port, this, false);
1014
1015 // Add the addresses of this protocol.
1016 PortList::const_iterator relay_port;
1017 for (relay_port = config.ports.begin();
1018 relay_port != config.ports.end();
1019 ++relay_port) {
1020 port->AddServerAddress(*relay_port);
1021 port->AddExternalAddress(*relay_port);
1022 }
1023 // Start fetching an address for this port.
1024 port->PrepareAddress();
1025 }
1026}
1027
1028void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1029 PortList::const_iterator relay_port;
1030 for (relay_port = config.ports.begin();
1031 relay_port != config.ports.end(); ++relay_port) {
1032 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001033
1034 // Skip UDP connections to relay servers if it's disallowed.
1035 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1036 relay_port->proto == PROTO_UDP) {
1037 continue;
1038 }
1039
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040 // Shared socket mode must be enabled only for UDP based ports. Hence
1041 // don't pass shared socket for ports which will create TCP sockets.
1042 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1043 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1044 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001045 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 port = TurnPort::Create(session_->network_thread(),
1047 session_->socket_factory(),
1048 network_, udp_socket_.get(),
1049 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001050 *relay_port, config.credentials, config.priority,
1051 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001052 turn_ports_.push_back(port);
1053 // Listen to the port destroyed signal, to allow AllocationSequence to
1054 // remove entrt from it's map.
1055 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1056 } else {
1057 port = TurnPort::Create(session_->network_thread(),
1058 session_->socket_factory(),
1059 network_, ip_,
1060 session_->allocator()->min_port(),
1061 session_->allocator()->max_port(),
1062 session_->username(),
1063 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001064 *relay_port, config.credentials, config.priority,
1065 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001066 }
1067 ASSERT(port != NULL);
1068 session_->AddAllocatedPort(port, this, true);
1069 }
1070}
1071
1072void AllocationSequence::OnReadPacket(
1073 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1074 const rtc::SocketAddress& remote_addr,
1075 const rtc::PacketTime& packet_time) {
1076 ASSERT(socket == udp_socket_.get());
1077
1078 bool turn_port_found = false;
1079
1080 // Try to find the TurnPort that matches the remote address. Note that the
1081 // message could be a STUN binding response if the TURN server is also used as
1082 // a STUN server. We don't want to parse every message here to check if it is
1083 // a STUN binding response, so we pass the message to TurnPort regardless of
1084 // the message type. The TurnPort will just ignore the message since it will
1085 // not find any request by transaction ID.
1086 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1087 it != turn_ports_.end(); ++it) {
1088 TurnPort* port = *it;
1089 if (port->server_address().address == remote_addr) {
1090 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1091 turn_port_found = true;
1092 break;
1093 }
1094 }
1095
1096 if (udp_port_) {
1097 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1098
1099 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1100 // the TURN server is also a STUN server.
1101 if (!turn_port_found ||
1102 stun_servers.find(remote_addr) != stun_servers.end()) {
1103 udp_port_->HandleIncomingPacket(
1104 socket, data, size, remote_addr, packet_time);
1105 }
1106 }
1107}
1108
1109void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1110 if (udp_port_ == port) {
1111 udp_port_ = NULL;
1112 return;
1113 }
1114
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001115 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1116 if (it != turn_ports_.end()) {
1117 turn_ports_.erase(it);
1118 } else {
1119 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1120 ASSERT(false);
1121 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001122}
1123
1124// PortConfiguration
1125PortConfiguration::PortConfiguration(
1126 const rtc::SocketAddress& stun_address,
1127 const std::string& username,
1128 const std::string& password)
1129 : stun_address(stun_address), username(username), password(password) {
1130 if (!stun_address.IsNil())
1131 stun_servers.insert(stun_address);
1132}
1133
1134PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1135 const std::string& username,
1136 const std::string& password)
1137 : stun_servers(stun_servers),
1138 username(username),
1139 password(password) {
1140 if (!stun_servers.empty())
1141 stun_address = *(stun_servers.begin());
1142}
1143
1144ServerAddresses PortConfiguration::StunServers() {
1145 if (!stun_address.IsNil() &&
1146 stun_servers.find(stun_address) == stun_servers.end()) {
1147 stun_servers.insert(stun_address);
1148 }
deadbeefc5d0d952015-07-16 10:22:21 -07001149 // Every UDP TURN server should also be used as a STUN server.
1150 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1151 for (const rtc::SocketAddress& turn_server : turn_servers) {
1152 if (stun_servers.find(turn_server) == stun_servers.end()) {
1153 stun_servers.insert(turn_server);
1154 }
1155 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001156 return stun_servers;
1157}
1158
1159void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1160 relays.push_back(config);
1161}
1162
1163bool PortConfiguration::SupportsProtocol(
1164 const RelayServerConfig& relay, ProtocolType type) const {
1165 PortList::const_iterator relay_port;
1166 for (relay_port = relay.ports.begin();
1167 relay_port != relay.ports.end();
1168 ++relay_port) {
1169 if (relay_port->proto == type)
1170 return true;
1171 }
1172 return false;
1173}
1174
1175bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1176 ProtocolType type) const {
1177 for (size_t i = 0; i < relays.size(); ++i) {
1178 if (relays[i].type == turn_type &&
1179 SupportsProtocol(relays[i], type))
1180 return true;
1181 }
1182 return false;
1183}
1184
1185ServerAddresses PortConfiguration::GetRelayServerAddresses(
1186 RelayType turn_type, ProtocolType type) const {
1187 ServerAddresses servers;
1188 for (size_t i = 0; i < relays.size(); ++i) {
1189 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1190 servers.insert(relays[i].ports.front().address);
1191 }
1192 }
1193 return servers;
1194}
1195
1196} // namespace cricket