blob: 865fbbb4c0f33efa736ba5d6cdfef6dc816c4f90 [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 {
Peter Boström0c4e06b2015-10-07 12:23:21 +020062const uint32_t 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);
deadbeef18a944b2015-10-26 19:21:40 -0700107 if (!relay_address_udp.IsNil())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000108 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef18a944b2015-10-26 19:21:40 -0700109 if (!relay_address_tcp.IsNil())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef18a944b2015-10-26 19:21:40 -0700111 if (!relay_address_ssl.IsNil())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000112 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
113
deadbeef18a944b2015-10-26 19:21:40 -0700114 if (!config.ports.empty())
115 AddRelay(config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000116
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
Peter Boström0c4e06b2015-10-07 12:23:21 +0200160 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 // 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
Peter Boström0c4e06b2015-10-07 12:23:21 +0200170 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171 delete configs_[i];
172
Peter Boström0c4e06b2015-10-07 12:23:21 +0200173 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000174 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);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200201 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000202 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
deadbeef18a944b2015-10-26 19:21:40 -0700244 for (size_t i = 0; i < allocator_->relays().size(); ++i) {
245 config->AddRelay(allocator_->relays()[i]);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000246 }
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) {
deadbeef18a944b2015-10-26 19:21:40 -0700256 if (config)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257 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 {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200338 for (uint32_t i = 0; i < networks.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 PortConfiguration* config = NULL;
340 if (configs_.size() > 0)
341 config = configs_.back();
342
Peter Boström0c4e06b2015-10-07 12:23:21 +0200343 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344 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(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200409 rtc::Network* network,
410 PortConfiguration* config,
411 uint32_t* flags) {
412 for (uint32_t i = 0; i < sequences_.size() &&
413 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
414 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000415 sequences_[i]->DisableEquivalentPhases(network, config, flags);
416 }
417}
418
419void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
420 AllocationSequence * seq,
421 bool prepare_address) {
422 if (!port)
423 return;
424
425 LOG(LS_INFO) << "Adding allocated port for " << content_name();
426 port->set_content_name(content_name());
427 port->set_component(component_);
428 port->set_generation(generation());
429 if (allocator_->proxy().type != rtc::PROXY_NONE)
430 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
431 port->set_send_retransmit_count_attribute((allocator_->flags() &
432 PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
433
434 // Push down the candidate_filter to individual port.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200435 uint32_t candidate_filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000436
437 // When adapter enumeration is disabled, disable CF_HOST at port level so
438 // local address is not leaked by stunport in the candidate's related address.
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800439 if ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
440 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) {
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000441 candidate_filter &= ~CF_HOST;
442 }
443 port->set_candidate_filter(candidate_filter);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444
445 PortData data(port, seq);
446 ports_.push_back(data);
447
448 port->SignalCandidateReady.connect(
449 this, &BasicPortAllocatorSession::OnCandidateReady);
450 port->SignalPortComplete.connect(this,
451 &BasicPortAllocatorSession::OnPortComplete);
452 port->SignalDestroyed.connect(this,
453 &BasicPortAllocatorSession::OnPortDestroyed);
454 port->SignalPortError.connect(
455 this, &BasicPortAllocatorSession::OnPortError);
456 LOG_J(LS_INFO, port) << "Added port to allocator";
457
458 if (prepare_address)
459 port->PrepareAddress();
460}
461
462void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
463 allocation_sequences_created_ = true;
464 // Send candidate allocation complete signal if we have no sequences.
465 MaybeSignalCandidatesAllocationDone();
466}
467
468void BasicPortAllocatorSession::OnCandidateReady(
469 Port* port, const Candidate& c) {
470 ASSERT(rtc::Thread::Current() == network_thread_);
471 PortData* data = FindPort(port);
472 ASSERT(data != NULL);
473 // Discarding any candidate signal if port allocation status is
474 // already in completed state.
475 if (data->complete())
476 return;
477
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700479 bool candidate_signalable = CheckCandidateFilter(c);
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700480
481 // When device enumeration is disabled (to prevent non-default IP addresses
482 // from leaking), we ping from some local candidates even though we don't
483 // signal them. However, if host candidates are also disabled (for example, to
484 // prevent even default IP addresses from leaking), we still don't want to
485 // ping from them, even if device enumeration is disabled. Thus, we check for
486 // both device enumeration and host candidates being disabled.
487 bool network_enumeration_disabled = c.address().IsAnyIP();
488 bool can_ping_from_candidate =
489 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
490 bool host_canidates_disabled = !(allocator_->candidate_filter() & CF_HOST);
491
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700492 bool candidate_pairable =
493 candidate_signalable ||
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700494 (network_enumeration_disabled && can_ping_from_candidate &&
495 !host_canidates_disabled);
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700496 bool candidate_protocol_enabled =
497 StringToProto(c.protocol().c_str(), &pvalue) &&
498 data->sequence()->ProtocolEnabled(pvalue);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000499
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700500 if (candidate_signalable && candidate_protocol_enabled) {
501 std::vector<Candidate> candidates;
502 candidates.push_back(c);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000503 SignalCandidatesReady(this, candidates);
504 }
505
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700506 // Port has been made ready. Nothing to do here.
507 if (data->ready()) {
508 return;
509 }
510
511 // Move the port to the READY state, either because we have a usable candidate
512 // from the port, or simply because the port is bound to the any address and
513 // therefore has no host candidate. This will trigger the port to start
514 // creating candidate pairs (connections) and issue connectivity checks.
515 if (candidate_pairable) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000516 data->set_ready();
517 SignalPortReady(this, port);
518 }
519}
520
521void BasicPortAllocatorSession::OnPortComplete(Port* port) {
522 ASSERT(rtc::Thread::Current() == network_thread_);
523 PortData* data = FindPort(port);
524 ASSERT(data != NULL);
525
526 // Ignore any late signals.
527 if (data->complete())
528 return;
529
530 // Moving to COMPLETE state.
531 data->set_complete();
532 // Send candidate allocation complete signal if this was the last port.
533 MaybeSignalCandidatesAllocationDone();
534}
535
536void BasicPortAllocatorSession::OnPortError(Port* port) {
537 ASSERT(rtc::Thread::Current() == network_thread_);
538 PortData* data = FindPort(port);
539 ASSERT(data != NULL);
540 // We might have already given up on this port and stopped it.
541 if (data->complete())
542 return;
543
544 // SignalAddressError is currently sent from StunPort/TurnPort.
545 // But this signal itself is generic.
546 data->set_error();
547 // Send candidate allocation complete signal if this was the last port.
548 MaybeSignalCandidatesAllocationDone();
549}
550
551void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
552 ProtocolType proto) {
553 std::vector<Candidate> candidates;
554 for (std::vector<PortData>::iterator it = ports_.begin();
555 it != ports_.end(); ++it) {
556 if (it->sequence() != seq)
557 continue;
558
559 const std::vector<Candidate>& potentials = it->port()->Candidates();
560 for (size_t i = 0; i < potentials.size(); ++i) {
561 if (!CheckCandidateFilter(potentials[i]))
562 continue;
563 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700564 bool candidate_protocol_enabled =
565 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
566 pvalue == proto;
567 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568 candidates.push_back(potentials[i]);
569 }
570 }
571 }
572
573 if (!candidates.empty()) {
574 SignalCandidatesReady(this, candidates);
575 }
576}
577
578bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200579 uint32_t filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000580
581 // When binding to any address, before sending packets out, the getsockname
582 // returns all 0s, but after sending packets, it'll be the NIC used to
583 // send. All 0s is not a valid ICE candidate address and should be filtered
584 // out.
585 if (c.address().IsAnyIP()) {
586 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 }
588
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000589 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000590 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000591 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000592 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000593 } else if (c.type() == LOCAL_PORT_TYPE) {
594 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
595 // We allow host candidates if the filter allows server-reflexive
596 // candidates and the candidate is a public IP. Because we don't generate
597 // server-reflexive candidates if they have the same IP as the host
598 // candidate (i.e. when the host candidate is a public IP), filtering to
599 // only server-reflexive candidates won't work right when the host
600 // candidates have public IPs.
601 return true;
602 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000603
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000604 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000605 }
606 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000607}
608
609void BasicPortAllocatorSession::OnPortAllocationComplete(
610 AllocationSequence* seq) {
611 // Send candidate allocation complete signal if all ports are done.
612 MaybeSignalCandidatesAllocationDone();
613}
614
615void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
616 // Send signal only if all required AllocationSequence objects
617 // are created.
618 if (!allocation_sequences_created_)
619 return;
620
621 // Check that all port allocation sequences are complete.
622 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
623 it != sequences_.end(); ++it) {
624 if ((*it)->state() == AllocationSequence::kRunning)
625 return;
626 }
627
628 // If all allocated ports are in complete state, session must have got all
629 // expected candidates. Session will trigger candidates allocation complete
630 // signal.
631 for (std::vector<PortData>::iterator it = ports_.begin();
632 it != ports_.end(); ++it) {
633 if (!it->complete())
634 return;
635 }
636 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
637 << component_ << ":" << generation();
638 SignalCandidatesAllocationDone(this);
639}
640
641void BasicPortAllocatorSession::OnPortDestroyed(
642 PortInterface* port) {
643 ASSERT(rtc::Thread::Current() == network_thread_);
644 for (std::vector<PortData>::iterator iter = ports_.begin();
645 iter != ports_.end(); ++iter) {
646 if (port == iter->port()) {
647 ports_.erase(iter);
648 LOG_J(LS_INFO, port) << "Removed port from allocator ("
649 << static_cast<int>(ports_.size()) << " remaining)";
650 return;
651 }
652 }
653 ASSERT(false);
654}
655
656void BasicPortAllocatorSession::OnShake() {
657 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
658
659 std::vector<Port*> ports;
660 std::vector<Connection*> connections;
661
662 for (size_t i = 0; i < ports_.size(); ++i) {
663 if (ports_[i].ready())
664 ports.push_back(ports_[i].port());
665 }
666
667 for (size_t i = 0; i < ports.size(); ++i) {
668 Port::AddressMap::const_iterator iter;
669 for (iter = ports[i]->connections().begin();
670 iter != ports[i]->connections().end();
671 ++iter) {
672 connections.push_back(iter->second);
673 }
674 }
675
676 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
677 << connections.size() << " connections";
678
679 for (size_t i = 0; i < connections.size(); ++i)
680 connections[i]->Destroy();
681
682 if (running_ || (ports.size() > 0) || (connections.size() > 0))
683 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
684}
685
686BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
687 Port* port) {
688 for (std::vector<PortData>::iterator it = ports_.begin();
689 it != ports_.end(); ++it) {
690 if (it->port() == port) {
691 return &*it;
692 }
693 }
694 return NULL;
695}
696
697// AllocationSequence
698
699AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
700 rtc::Network* network,
701 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200702 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000703 : session_(session),
704 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000706 config_(config),
707 state_(kInit),
708 flags_(flags),
709 udp_socket_(),
710 udp_port_(NULL),
711 phase_(0) {
712}
713
714bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000715 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
716 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
717 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
718 session_->allocator()->max_port()));
719 if (udp_socket_) {
720 udp_socket_->SignalReadPacket.connect(
721 this, &AllocationSequence::OnReadPacket);
722 }
723 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
724 // are next available options to setup a communication channel.
725 }
726 return true;
727}
728
729void AllocationSequence::Clear() {
730 udp_port_ = NULL;
731 turn_ports_.clear();
732}
733
honghaiz8c404fa2015-09-28 07:59:43 -0700734void AllocationSequence::OnNetworkRemoved() {
735 // Stop the allocation sequence if its network is gone.
736 Stop();
737 network_removed_ = true;
738}
739
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000740AllocationSequence::~AllocationSequence() {
741 session_->network_thread()->Clear(this);
742}
743
744void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200745 PortConfiguration* config, uint32_t* flags) {
honghaiz8c404fa2015-09-28 07:59:43 -0700746 if (network_removed_) {
747 // If the network of this allocation sequence has ever gone away,
748 // it won't be equivalent to the new network.
749 return;
750 }
751
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000753 // Different network setup; nothing is equivalent.
754 return;
755 }
756
757 // Else turn off the stuff that we've already got covered.
758
759 // Every config implicitly specifies local, so turn that off right away.
760 *flags |= PORTALLOCATOR_DISABLE_UDP;
761 *flags |= PORTALLOCATOR_DISABLE_TCP;
762
763 if (config_ && config) {
764 if (config_->StunServers() == config->StunServers()) {
765 // Already got this STUN servers covered.
766 *flags |= PORTALLOCATOR_DISABLE_STUN;
767 }
768 if (!config_->relays.empty()) {
769 // Already got relays covered.
770 // NOTE: This will even skip a _different_ set of relay servers if we
771 // were to be given one, but that never happens in our codebase. Should
772 // probably get rid of the list in PortConfiguration and just keep a
773 // single relay server in each one.
774 *flags |= PORTALLOCATOR_DISABLE_RELAY;
775 }
776 }
777}
778
779void AllocationSequence::Start() {
780 state_ = kRunning;
781 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
782}
783
784void AllocationSequence::Stop() {
785 // If the port is completed, don't set it to stopped.
786 if (state_ == kRunning) {
787 state_ = kStopped;
788 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
789 }
790}
791
792void AllocationSequence::OnMessage(rtc::Message* msg) {
793 ASSERT(rtc::Thread::Current() == session_->network_thread());
794 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
795
796 const char* const PHASE_NAMES[kNumPhases] = {
797 "Udp", "Relay", "Tcp", "SslTcp"
798 };
799
800 // Perform all of the phases in the current step.
801 LOG_J(LS_INFO, network_) << "Allocation Phase="
802 << PHASE_NAMES[phase_];
803
804 switch (phase_) {
805 case PHASE_UDP:
806 CreateUDPPorts();
807 CreateStunPorts();
808 EnableProtocol(PROTO_UDP);
809 break;
810
811 case PHASE_RELAY:
812 CreateRelayPorts();
813 break;
814
815 case PHASE_TCP:
816 CreateTCPPorts();
817 EnableProtocol(PROTO_TCP);
818 break;
819
820 case PHASE_SSLTCP:
821 state_ = kCompleted;
822 EnableProtocol(PROTO_SSLTCP);
823 break;
824
825 default:
826 ASSERT(false);
827 }
828
829 if (state() == kRunning) {
830 ++phase_;
831 session_->network_thread()->PostDelayed(
832 session_->allocator()->step_delay(),
833 this, MSG_ALLOCATION_PHASE);
834 } else {
835 // If all phases in AllocationSequence are completed, no allocation
836 // steps needed further. Canceling pending signal.
837 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
838 SignalPortAllocationComplete(this);
839 }
840}
841
842void AllocationSequence::EnableProtocol(ProtocolType proto) {
843 if (!ProtocolEnabled(proto)) {
844 protocols_.push_back(proto);
845 session_->OnProtocolEnabled(this, proto);
846 }
847}
848
849bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
850 for (ProtocolList::const_iterator it = protocols_.begin();
851 it != protocols_.end(); ++it) {
852 if (*it == proto)
853 return true;
854 }
855 return false;
856}
857
858void AllocationSequence::CreateUDPPorts() {
859 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
860 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
861 return;
862 }
863
864 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
865 // is enabled completely.
866 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800867 bool emit_local_candidate_for_anyaddress =
868 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000869 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700870 port = UDPPort::Create(
871 session_->network_thread(), session_->socket_factory(), network_,
872 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800873 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700875 port = UDPPort::Create(
876 session_->network_thread(), session_->socket_factory(), network_, ip_,
877 session_->allocator()->min_port(), session_->allocator()->max_port(),
878 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800879 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000880 }
881
882 if (port) {
883 // If shared socket is enabled, STUN candidate will be allocated by the
884 // UDPPort.
885 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
886 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000887 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888
889 // If STUN is not disabled, setting stun server address to port.
890 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 if (config_ && !config_->StunServers().empty()) {
892 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
893 << "STUN candidate generation.";
894 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895 }
896 }
897 }
898
899 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 }
901}
902
903void AllocationSequence::CreateTCPPorts() {
904 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
905 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
906 return;
907 }
908
909 Port* port = TCPPort::Create(session_->network_thread(),
910 session_->socket_factory(),
911 network_, ip_,
912 session_->allocator()->min_port(),
913 session_->allocator()->max_port(),
914 session_->username(), session_->password(),
915 session_->allocator()->allow_tcp_listen());
916 if (port) {
917 session_->AddAllocatedPort(port, this, true);
918 // Since TCPPort is not created using shared socket, |port| will not be
919 // added to the dequeue.
920 }
921}
922
923void AllocationSequence::CreateStunPorts() {
924 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
925 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
926 return;
927 }
928
929 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
930 return;
931 }
932
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933 if (!(config_ && !config_->StunServers().empty())) {
934 LOG(LS_WARNING)
935 << "AllocationSequence: No STUN server configured, skipping.";
936 return;
937 }
938
939 StunPort* port = StunPort::Create(session_->network_thread(),
940 session_->socket_factory(),
941 network_, ip_,
942 session_->allocator()->min_port(),
943 session_->allocator()->max_port(),
944 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000945 config_->StunServers(),
946 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947 if (port) {
948 session_->AddAllocatedPort(port, this, true);
949 // Since StunPort is not created using shared socket, |port| will not be
950 // added to the dequeue.
951 }
952}
953
954void AllocationSequence::CreateRelayPorts() {
955 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
956 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
957 return;
958 }
959
960 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
961 // ought to have a relay list for them here.
962 ASSERT(config_ && !config_->relays.empty());
963 if (!(config_ && !config_->relays.empty())) {
964 LOG(LS_WARNING)
965 << "AllocationSequence: No relay server configured, skipping.";
966 return;
967 }
968
969 PortConfiguration::RelayList::const_iterator relay;
970 for (relay = config_->relays.begin();
971 relay != config_->relays.end(); ++relay) {
972 if (relay->type == RELAY_GTURN) {
973 CreateGturnPort(*relay);
974 } else if (relay->type == RELAY_TURN) {
975 CreateTurnPort(*relay);
976 } else {
977 ASSERT(false);
978 }
979 }
980}
981
982void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
983 // TODO(mallinath) - Rename RelayPort to GTurnPort.
984 RelayPort* port = RelayPort::Create(session_->network_thread(),
985 session_->socket_factory(),
986 network_, ip_,
987 session_->allocator()->min_port(),
988 session_->allocator()->max_port(),
989 config_->username, config_->password);
990 if (port) {
991 // Since RelayPort is not created using shared socket, |port| will not be
992 // added to the dequeue.
993 // Note: We must add the allocated port before we add addresses because
994 // the latter will create candidates that need name and preference
995 // settings. However, we also can't prepare the address (normally
996 // done by AddAllocatedPort) until we have these addresses. So we
997 // wait to do that until below.
998 session_->AddAllocatedPort(port, this, false);
999
1000 // Add the addresses of this protocol.
1001 PortList::const_iterator relay_port;
1002 for (relay_port = config.ports.begin();
1003 relay_port != config.ports.end();
1004 ++relay_port) {
1005 port->AddServerAddress(*relay_port);
1006 port->AddExternalAddress(*relay_port);
1007 }
1008 // Start fetching an address for this port.
1009 port->PrepareAddress();
1010 }
1011}
1012
1013void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1014 PortList::const_iterator relay_port;
1015 for (relay_port = config.ports.begin();
1016 relay_port != config.ports.end(); ++relay_port) {
1017 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001018
1019 // Skip UDP connections to relay servers if it's disallowed.
1020 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1021 relay_port->proto == PROTO_UDP) {
1022 continue;
1023 }
1024
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001025 // Shared socket mode must be enabled only for UDP based ports. Hence
1026 // don't pass shared socket for ports which will create TCP sockets.
1027 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1028 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1029 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001030 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001031 port = TurnPort::Create(session_->network_thread(),
1032 session_->socket_factory(),
1033 network_, udp_socket_.get(),
1034 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001035 *relay_port, config.credentials, config.priority,
1036 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001037 turn_ports_.push_back(port);
1038 // Listen to the port destroyed signal, to allow AllocationSequence to
1039 // remove entrt from it's map.
1040 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1041 } else {
1042 port = TurnPort::Create(session_->network_thread(),
1043 session_->socket_factory(),
1044 network_, ip_,
1045 session_->allocator()->min_port(),
1046 session_->allocator()->max_port(),
1047 session_->username(),
1048 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001049 *relay_port, config.credentials, config.priority,
1050 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001051 }
1052 ASSERT(port != NULL);
1053 session_->AddAllocatedPort(port, this, true);
1054 }
1055}
1056
1057void AllocationSequence::OnReadPacket(
1058 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1059 const rtc::SocketAddress& remote_addr,
1060 const rtc::PacketTime& packet_time) {
1061 ASSERT(socket == udp_socket_.get());
1062
1063 bool turn_port_found = false;
1064
1065 // Try to find the TurnPort that matches the remote address. Note that the
1066 // message could be a STUN binding response if the TURN server is also used as
1067 // a STUN server. We don't want to parse every message here to check if it is
1068 // a STUN binding response, so we pass the message to TurnPort regardless of
1069 // the message type. The TurnPort will just ignore the message since it will
1070 // not find any request by transaction ID.
1071 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1072 it != turn_ports_.end(); ++it) {
1073 TurnPort* port = *it;
1074 if (port->server_address().address == remote_addr) {
1075 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1076 turn_port_found = true;
1077 break;
1078 }
1079 }
1080
1081 if (udp_port_) {
1082 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1083
1084 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1085 // the TURN server is also a STUN server.
1086 if (!turn_port_found ||
1087 stun_servers.find(remote_addr) != stun_servers.end()) {
1088 udp_port_->HandleIncomingPacket(
1089 socket, data, size, remote_addr, packet_time);
1090 }
1091 }
1092}
1093
1094void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1095 if (udp_port_ == port) {
1096 udp_port_ = NULL;
1097 return;
1098 }
1099
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001100 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1101 if (it != turn_ports_.end()) {
1102 turn_ports_.erase(it);
1103 } else {
1104 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1105 ASSERT(false);
1106 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001107}
1108
1109// PortConfiguration
1110PortConfiguration::PortConfiguration(
1111 const rtc::SocketAddress& stun_address,
1112 const std::string& username,
1113 const std::string& password)
1114 : stun_address(stun_address), username(username), password(password) {
1115 if (!stun_address.IsNil())
1116 stun_servers.insert(stun_address);
1117}
1118
1119PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1120 const std::string& username,
1121 const std::string& password)
1122 : stun_servers(stun_servers),
1123 username(username),
1124 password(password) {
1125 if (!stun_servers.empty())
1126 stun_address = *(stun_servers.begin());
1127}
1128
1129ServerAddresses PortConfiguration::StunServers() {
1130 if (!stun_address.IsNil() &&
1131 stun_servers.find(stun_address) == stun_servers.end()) {
1132 stun_servers.insert(stun_address);
1133 }
deadbeefc5d0d952015-07-16 10:22:21 -07001134 // Every UDP TURN server should also be used as a STUN server.
1135 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1136 for (const rtc::SocketAddress& turn_server : turn_servers) {
1137 if (stun_servers.find(turn_server) == stun_servers.end()) {
1138 stun_servers.insert(turn_server);
1139 }
1140 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001141 return stun_servers;
1142}
1143
1144void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1145 relays.push_back(config);
1146}
1147
1148bool PortConfiguration::SupportsProtocol(
1149 const RelayServerConfig& relay, ProtocolType type) const {
1150 PortList::const_iterator relay_port;
1151 for (relay_port = relay.ports.begin();
1152 relay_port != relay.ports.end();
1153 ++relay_port) {
1154 if (relay_port->proto == type)
1155 return true;
1156 }
1157 return false;
1158}
1159
1160bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1161 ProtocolType type) const {
1162 for (size_t i = 0; i < relays.size(); ++i) {
1163 if (relays[i].type == turn_type &&
1164 SupportsProtocol(relays[i], type))
1165 return true;
1166 }
1167 return false;
1168}
1169
1170ServerAddresses PortConfiguration::GetRelayServerAddresses(
1171 RelayType turn_type, ProtocolType type) const {
1172 ServerAddresses servers;
1173 for (size_t i = 0; i < relays.size(); ++i) {
1174 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1175 servers.insert(relays[i].ports.front().address);
1176 }
1177 }
1178 return servers;
1179}
1180
1181} // namespace cricket