blob: 21c8921f4024c51b3679471595a97dae199c1625 [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.
439 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
440 candidate_filter &= ~CF_HOST;
441 }
442 port->set_candidate_filter(candidate_filter);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443
444 PortData data(port, seq);
445 ports_.push_back(data);
446
447 port->SignalCandidateReady.connect(
448 this, &BasicPortAllocatorSession::OnCandidateReady);
449 port->SignalPortComplete.connect(this,
450 &BasicPortAllocatorSession::OnPortComplete);
451 port->SignalDestroyed.connect(this,
452 &BasicPortAllocatorSession::OnPortDestroyed);
453 port->SignalPortError.connect(
454 this, &BasicPortAllocatorSession::OnPortError);
455 LOG_J(LS_INFO, port) << "Added port to allocator";
456
457 if (prepare_address)
458 port->PrepareAddress();
459}
460
461void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
462 allocation_sequences_created_ = true;
463 // Send candidate allocation complete signal if we have no sequences.
464 MaybeSignalCandidatesAllocationDone();
465}
466
467void BasicPortAllocatorSession::OnCandidateReady(
468 Port* port, const Candidate& c) {
469 ASSERT(rtc::Thread::Current() == network_thread_);
470 PortData* data = FindPort(port);
471 ASSERT(data != NULL);
472 // Discarding any candidate signal if port allocation status is
473 // already in completed state.
474 if (data->complete())
475 return;
476
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700478 bool candidate_signalable = CheckCandidateFilter(c);
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700479
480 // When device enumeration is disabled (to prevent non-default IP addresses
481 // from leaking), we ping from some local candidates even though we don't
482 // signal them. However, if host candidates are also disabled (for example, to
483 // prevent even default IP addresses from leaking), we still don't want to
484 // ping from them, even if device enumeration is disabled. Thus, we check for
485 // both device enumeration and host candidates being disabled.
486 bool network_enumeration_disabled = c.address().IsAnyIP();
487 bool can_ping_from_candidate =
488 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
489 bool host_canidates_disabled = !(allocator_->candidate_filter() & CF_HOST);
490
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700491 bool candidate_pairable =
492 candidate_signalable ||
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700493 (network_enumeration_disabled && can_ping_from_candidate &&
494 !host_canidates_disabled);
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700495 bool candidate_protocol_enabled =
496 StringToProto(c.protocol().c_str(), &pvalue) &&
497 data->sequence()->ProtocolEnabled(pvalue);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000498
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700499 if (candidate_signalable && candidate_protocol_enabled) {
500 std::vector<Candidate> candidates;
501 candidates.push_back(c);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000502 SignalCandidatesReady(this, candidates);
503 }
504
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700505 // Port has been made ready. Nothing to do here.
506 if (data->ready()) {
507 return;
508 }
509
510 // Move the port to the READY state, either because we have a usable candidate
511 // from the port, or simply because the port is bound to the any address and
512 // therefore has no host candidate. This will trigger the port to start
513 // creating candidate pairs (connections) and issue connectivity checks.
514 if (candidate_pairable) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000515 data->set_ready();
516 SignalPortReady(this, port);
517 }
518}
519
520void BasicPortAllocatorSession::OnPortComplete(Port* port) {
521 ASSERT(rtc::Thread::Current() == network_thread_);
522 PortData* data = FindPort(port);
523 ASSERT(data != NULL);
524
525 // Ignore any late signals.
526 if (data->complete())
527 return;
528
529 // Moving to COMPLETE state.
530 data->set_complete();
531 // Send candidate allocation complete signal if this was the last port.
532 MaybeSignalCandidatesAllocationDone();
533}
534
535void BasicPortAllocatorSession::OnPortError(Port* port) {
536 ASSERT(rtc::Thread::Current() == network_thread_);
537 PortData* data = FindPort(port);
538 ASSERT(data != NULL);
539 // We might have already given up on this port and stopped it.
540 if (data->complete())
541 return;
542
543 // SignalAddressError is currently sent from StunPort/TurnPort.
544 // But this signal itself is generic.
545 data->set_error();
546 // Send candidate allocation complete signal if this was the last port.
547 MaybeSignalCandidatesAllocationDone();
548}
549
550void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
551 ProtocolType proto) {
552 std::vector<Candidate> candidates;
553 for (std::vector<PortData>::iterator it = ports_.begin();
554 it != ports_.end(); ++it) {
555 if (it->sequence() != seq)
556 continue;
557
558 const std::vector<Candidate>& potentials = it->port()->Candidates();
559 for (size_t i = 0; i < potentials.size(); ++i) {
560 if (!CheckCandidateFilter(potentials[i]))
561 continue;
562 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700563 bool candidate_protocol_enabled =
564 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
565 pvalue == proto;
566 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567 candidates.push_back(potentials[i]);
568 }
569 }
570 }
571
572 if (!candidates.empty()) {
573 SignalCandidatesReady(this, candidates);
574 }
575}
576
577bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200578 uint32_t filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000579
580 // When binding to any address, before sending packets out, the getsockname
581 // returns all 0s, but after sending packets, it'll be the NIC used to
582 // send. All 0s is not a valid ICE candidate address and should be filtered
583 // out.
584 if (c.address().IsAnyIP()) {
585 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000586 }
587
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000588 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000589 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000590 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000591 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000592 } else if (c.type() == LOCAL_PORT_TYPE) {
593 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
594 // We allow host candidates if the filter allows server-reflexive
595 // candidates and the candidate is a public IP. Because we don't generate
596 // server-reflexive candidates if they have the same IP as the host
597 // candidate (i.e. when the host candidate is a public IP), filtering to
598 // only server-reflexive candidates won't work right when the host
599 // candidates have public IPs.
600 return true;
601 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700603 // If PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE is specified and it's
604 // loopback address, we should allow it as it's for demo page connectivity
605 // when no TURN/STUN specified.
606 if (c.address().IsLoopbackIP() &&
607 (flags() & PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE) != 0) {
608 return true;
609 }
610
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000611 // This is just to prevent the case when binding to any address (all 0s), if
612 // somehow the host candidate address is not all 0s. Either because local
613 // installed proxy changes the address or a packet has been sent for any
614 // reason before getsockname is called.
615 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
616 LOG(LS_WARNING) << "Received non-0 host address: "
617 << c.address().ToString()
618 << " when adapter enumeration is disabled";
619 return false;
620 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000622 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000623 }
624 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000625}
626
627void BasicPortAllocatorSession::OnPortAllocationComplete(
628 AllocationSequence* seq) {
629 // Send candidate allocation complete signal if all ports are done.
630 MaybeSignalCandidatesAllocationDone();
631}
632
633void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
634 // Send signal only if all required AllocationSequence objects
635 // are created.
636 if (!allocation_sequences_created_)
637 return;
638
639 // Check that all port allocation sequences are complete.
640 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
641 it != sequences_.end(); ++it) {
642 if ((*it)->state() == AllocationSequence::kRunning)
643 return;
644 }
645
646 // If all allocated ports are in complete state, session must have got all
647 // expected candidates. Session will trigger candidates allocation complete
648 // signal.
649 for (std::vector<PortData>::iterator it = ports_.begin();
650 it != ports_.end(); ++it) {
651 if (!it->complete())
652 return;
653 }
654 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
655 << component_ << ":" << generation();
656 SignalCandidatesAllocationDone(this);
657}
658
659void BasicPortAllocatorSession::OnPortDestroyed(
660 PortInterface* port) {
661 ASSERT(rtc::Thread::Current() == network_thread_);
662 for (std::vector<PortData>::iterator iter = ports_.begin();
663 iter != ports_.end(); ++iter) {
664 if (port == iter->port()) {
665 ports_.erase(iter);
666 LOG_J(LS_INFO, port) << "Removed port from allocator ("
667 << static_cast<int>(ports_.size()) << " remaining)";
668 return;
669 }
670 }
671 ASSERT(false);
672}
673
674void BasicPortAllocatorSession::OnShake() {
675 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
676
677 std::vector<Port*> ports;
678 std::vector<Connection*> connections;
679
680 for (size_t i = 0; i < ports_.size(); ++i) {
681 if (ports_[i].ready())
682 ports.push_back(ports_[i].port());
683 }
684
685 for (size_t i = 0; i < ports.size(); ++i) {
686 Port::AddressMap::const_iterator iter;
687 for (iter = ports[i]->connections().begin();
688 iter != ports[i]->connections().end();
689 ++iter) {
690 connections.push_back(iter->second);
691 }
692 }
693
694 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
695 << connections.size() << " connections";
696
697 for (size_t i = 0; i < connections.size(); ++i)
698 connections[i]->Destroy();
699
700 if (running_ || (ports.size() > 0) || (connections.size() > 0))
701 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
702}
703
704BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
705 Port* port) {
706 for (std::vector<PortData>::iterator it = ports_.begin();
707 it != ports_.end(); ++it) {
708 if (it->port() == port) {
709 return &*it;
710 }
711 }
712 return NULL;
713}
714
715// AllocationSequence
716
717AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
718 rtc::Network* network,
719 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200720 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721 : session_(session),
722 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000724 config_(config),
725 state_(kInit),
726 flags_(flags),
727 udp_socket_(),
728 udp_port_(NULL),
729 phase_(0) {
730}
731
732bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000733 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
734 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
735 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
736 session_->allocator()->max_port()));
737 if (udp_socket_) {
738 udp_socket_->SignalReadPacket.connect(
739 this, &AllocationSequence::OnReadPacket);
740 }
741 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
742 // are next available options to setup a communication channel.
743 }
744 return true;
745}
746
747void AllocationSequence::Clear() {
748 udp_port_ = NULL;
749 turn_ports_.clear();
750}
751
honghaiz8c404fa2015-09-28 07:59:43 -0700752void AllocationSequence::OnNetworkRemoved() {
753 // Stop the allocation sequence if its network is gone.
754 Stop();
755 network_removed_ = true;
756}
757
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758AllocationSequence::~AllocationSequence() {
759 session_->network_thread()->Clear(this);
760}
761
762void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200763 PortConfiguration* config, uint32_t* flags) {
honghaiz8c404fa2015-09-28 07:59:43 -0700764 if (network_removed_) {
765 // If the network of this allocation sequence has ever gone away,
766 // it won't be equivalent to the new network.
767 return;
768 }
769
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000770 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771 // Different network setup; nothing is equivalent.
772 return;
773 }
774
775 // Else turn off the stuff that we've already got covered.
776
777 // Every config implicitly specifies local, so turn that off right away.
778 *flags |= PORTALLOCATOR_DISABLE_UDP;
779 *flags |= PORTALLOCATOR_DISABLE_TCP;
780
781 if (config_ && config) {
782 if (config_->StunServers() == config->StunServers()) {
783 // Already got this STUN servers covered.
784 *flags |= PORTALLOCATOR_DISABLE_STUN;
785 }
786 if (!config_->relays.empty()) {
787 // Already got relays covered.
788 // NOTE: This will even skip a _different_ set of relay servers if we
789 // were to be given one, but that never happens in our codebase. Should
790 // probably get rid of the list in PortConfiguration and just keep a
791 // single relay server in each one.
792 *flags |= PORTALLOCATOR_DISABLE_RELAY;
793 }
794 }
795}
796
797void AllocationSequence::Start() {
798 state_ = kRunning;
799 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
800}
801
802void AllocationSequence::Stop() {
803 // If the port is completed, don't set it to stopped.
804 if (state_ == kRunning) {
805 state_ = kStopped;
806 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
807 }
808}
809
810void AllocationSequence::OnMessage(rtc::Message* msg) {
811 ASSERT(rtc::Thread::Current() == session_->network_thread());
812 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
813
814 const char* const PHASE_NAMES[kNumPhases] = {
815 "Udp", "Relay", "Tcp", "SslTcp"
816 };
817
818 // Perform all of the phases in the current step.
819 LOG_J(LS_INFO, network_) << "Allocation Phase="
820 << PHASE_NAMES[phase_];
821
822 switch (phase_) {
823 case PHASE_UDP:
824 CreateUDPPorts();
825 CreateStunPorts();
826 EnableProtocol(PROTO_UDP);
827 break;
828
829 case PHASE_RELAY:
830 CreateRelayPorts();
831 break;
832
833 case PHASE_TCP:
834 CreateTCPPorts();
835 EnableProtocol(PROTO_TCP);
836 break;
837
838 case PHASE_SSLTCP:
839 state_ = kCompleted;
840 EnableProtocol(PROTO_SSLTCP);
841 break;
842
843 default:
844 ASSERT(false);
845 }
846
847 if (state() == kRunning) {
848 ++phase_;
849 session_->network_thread()->PostDelayed(
850 session_->allocator()->step_delay(),
851 this, MSG_ALLOCATION_PHASE);
852 } else {
853 // If all phases in AllocationSequence are completed, no allocation
854 // steps needed further. Canceling pending signal.
855 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
856 SignalPortAllocationComplete(this);
857 }
858}
859
860void AllocationSequence::EnableProtocol(ProtocolType proto) {
861 if (!ProtocolEnabled(proto)) {
862 protocols_.push_back(proto);
863 session_->OnProtocolEnabled(this, proto);
864 }
865}
866
867bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
868 for (ProtocolList::const_iterator it = protocols_.begin();
869 it != protocols_.end(); ++it) {
870 if (*it == proto)
871 return true;
872 }
873 return false;
874}
875
876void AllocationSequence::CreateUDPPorts() {
877 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
878 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
879 return;
880 }
881
882 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
883 // is enabled completely.
884 UDPPort* port = NULL;
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700885 bool emit_localhost_for_anyaddress =
886 IsFlagSet(PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700888 port = UDPPort::Create(
889 session_->network_thread(), session_->socket_factory(), network_,
890 udp_socket_.get(), session_->username(), session_->password(),
891 session_->allocator()->origin(), emit_localhost_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700893 port = UDPPort::Create(
894 session_->network_thread(), session_->socket_factory(), network_, ip_,
895 session_->allocator()->min_port(), session_->allocator()->max_port(),
896 session_->username(), session_->password(),
897 session_->allocator()->origin(), emit_localhost_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000898 }
899
900 if (port) {
901 // If shared socket is enabled, STUN candidate will be allocated by the
902 // UDPPort.
903 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
904 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000905 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906
907 // If STUN is not disabled, setting stun server address to port.
908 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909 if (config_ && !config_->StunServers().empty()) {
910 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
911 << "STUN candidate generation.";
912 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 }
914 }
915 }
916
917 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 }
919}
920
921void AllocationSequence::CreateTCPPorts() {
922 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
923 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
924 return;
925 }
926
927 Port* port = TCPPort::Create(session_->network_thread(),
928 session_->socket_factory(),
929 network_, ip_,
930 session_->allocator()->min_port(),
931 session_->allocator()->max_port(),
932 session_->username(), session_->password(),
933 session_->allocator()->allow_tcp_listen());
934 if (port) {
935 session_->AddAllocatedPort(port, this, true);
936 // Since TCPPort is not created using shared socket, |port| will not be
937 // added to the dequeue.
938 }
939}
940
941void AllocationSequence::CreateStunPorts() {
942 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
943 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
944 return;
945 }
946
947 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
948 return;
949 }
950
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000951 if (!(config_ && !config_->StunServers().empty())) {
952 LOG(LS_WARNING)
953 << "AllocationSequence: No STUN server configured, skipping.";
954 return;
955 }
956
957 StunPort* port = StunPort::Create(session_->network_thread(),
958 session_->socket_factory(),
959 network_, ip_,
960 session_->allocator()->min_port(),
961 session_->allocator()->max_port(),
962 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000963 config_->StunServers(),
964 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000965 if (port) {
966 session_->AddAllocatedPort(port, this, true);
967 // Since StunPort is not created using shared socket, |port| will not be
968 // added to the dequeue.
969 }
970}
971
972void AllocationSequence::CreateRelayPorts() {
973 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
974 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
975 return;
976 }
977
978 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
979 // ought to have a relay list for them here.
980 ASSERT(config_ && !config_->relays.empty());
981 if (!(config_ && !config_->relays.empty())) {
982 LOG(LS_WARNING)
983 << "AllocationSequence: No relay server configured, skipping.";
984 return;
985 }
986
987 PortConfiguration::RelayList::const_iterator relay;
988 for (relay = config_->relays.begin();
989 relay != config_->relays.end(); ++relay) {
990 if (relay->type == RELAY_GTURN) {
991 CreateGturnPort(*relay);
992 } else if (relay->type == RELAY_TURN) {
993 CreateTurnPort(*relay);
994 } else {
995 ASSERT(false);
996 }
997 }
998}
999
1000void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1001 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1002 RelayPort* port = RelayPort::Create(session_->network_thread(),
1003 session_->socket_factory(),
1004 network_, ip_,
1005 session_->allocator()->min_port(),
1006 session_->allocator()->max_port(),
1007 config_->username, config_->password);
1008 if (port) {
1009 // Since RelayPort is not created using shared socket, |port| will not be
1010 // added to the dequeue.
1011 // Note: We must add the allocated port before we add addresses because
1012 // the latter will create candidates that need name and preference
1013 // settings. However, we also can't prepare the address (normally
1014 // done by AddAllocatedPort) until we have these addresses. So we
1015 // wait to do that until below.
1016 session_->AddAllocatedPort(port, this, false);
1017
1018 // Add the addresses of this protocol.
1019 PortList::const_iterator relay_port;
1020 for (relay_port = config.ports.begin();
1021 relay_port != config.ports.end();
1022 ++relay_port) {
1023 port->AddServerAddress(*relay_port);
1024 port->AddExternalAddress(*relay_port);
1025 }
1026 // Start fetching an address for this port.
1027 port->PrepareAddress();
1028 }
1029}
1030
1031void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1032 PortList::const_iterator relay_port;
1033 for (relay_port = config.ports.begin();
1034 relay_port != config.ports.end(); ++relay_port) {
1035 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001036
1037 // Skip UDP connections to relay servers if it's disallowed.
1038 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1039 relay_port->proto == PROTO_UDP) {
1040 continue;
1041 }
1042
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001043 // Shared socket mode must be enabled only for UDP based ports. Hence
1044 // don't pass shared socket for ports which will create TCP sockets.
1045 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1046 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1047 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001048 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001049 port = TurnPort::Create(session_->network_thread(),
1050 session_->socket_factory(),
1051 network_, udp_socket_.get(),
1052 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001053 *relay_port, config.credentials, config.priority,
1054 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001055 turn_ports_.push_back(port);
1056 // Listen to the port destroyed signal, to allow AllocationSequence to
1057 // remove entrt from it's map.
1058 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1059 } else {
1060 port = TurnPort::Create(session_->network_thread(),
1061 session_->socket_factory(),
1062 network_, ip_,
1063 session_->allocator()->min_port(),
1064 session_->allocator()->max_port(),
1065 session_->username(),
1066 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001067 *relay_port, config.credentials, config.priority,
1068 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001069 }
1070 ASSERT(port != NULL);
1071 session_->AddAllocatedPort(port, this, true);
1072 }
1073}
1074
1075void AllocationSequence::OnReadPacket(
1076 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1077 const rtc::SocketAddress& remote_addr,
1078 const rtc::PacketTime& packet_time) {
1079 ASSERT(socket == udp_socket_.get());
1080
1081 bool turn_port_found = false;
1082
1083 // Try to find the TurnPort that matches the remote address. Note that the
1084 // message could be a STUN binding response if the TURN server is also used as
1085 // a STUN server. We don't want to parse every message here to check if it is
1086 // a STUN binding response, so we pass the message to TurnPort regardless of
1087 // the message type. The TurnPort will just ignore the message since it will
1088 // not find any request by transaction ID.
1089 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1090 it != turn_ports_.end(); ++it) {
1091 TurnPort* port = *it;
1092 if (port->server_address().address == remote_addr) {
1093 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1094 turn_port_found = true;
1095 break;
1096 }
1097 }
1098
1099 if (udp_port_) {
1100 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1101
1102 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1103 // the TURN server is also a STUN server.
1104 if (!turn_port_found ||
1105 stun_servers.find(remote_addr) != stun_servers.end()) {
1106 udp_port_->HandleIncomingPacket(
1107 socket, data, size, remote_addr, packet_time);
1108 }
1109 }
1110}
1111
1112void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1113 if (udp_port_ == port) {
1114 udp_port_ = NULL;
1115 return;
1116 }
1117
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001118 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1119 if (it != turn_ports_.end()) {
1120 turn_ports_.erase(it);
1121 } else {
1122 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1123 ASSERT(false);
1124 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125}
1126
1127// PortConfiguration
1128PortConfiguration::PortConfiguration(
1129 const rtc::SocketAddress& stun_address,
1130 const std::string& username,
1131 const std::string& password)
1132 : stun_address(stun_address), username(username), password(password) {
1133 if (!stun_address.IsNil())
1134 stun_servers.insert(stun_address);
1135}
1136
1137PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1138 const std::string& username,
1139 const std::string& password)
1140 : stun_servers(stun_servers),
1141 username(username),
1142 password(password) {
1143 if (!stun_servers.empty())
1144 stun_address = *(stun_servers.begin());
1145}
1146
1147ServerAddresses PortConfiguration::StunServers() {
1148 if (!stun_address.IsNil() &&
1149 stun_servers.find(stun_address) == stun_servers.end()) {
1150 stun_servers.insert(stun_address);
1151 }
deadbeefc5d0d952015-07-16 10:22:21 -07001152 // Every UDP TURN server should also be used as a STUN server.
1153 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1154 for (const rtc::SocketAddress& turn_server : turn_servers) {
1155 if (stun_servers.find(turn_server) == stun_servers.end()) {
1156 stun_servers.insert(turn_server);
1157 }
1158 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001159 return stun_servers;
1160}
1161
1162void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1163 relays.push_back(config);
1164}
1165
1166bool PortConfiguration::SupportsProtocol(
1167 const RelayServerConfig& relay, ProtocolType type) const {
1168 PortList::const_iterator relay_port;
1169 for (relay_port = relay.ports.begin();
1170 relay_port != relay.ports.end();
1171 ++relay_port) {
1172 if (relay_port->proto == type)
1173 return true;
1174 }
1175 return false;
1176}
1177
1178bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1179 ProtocolType type) const {
1180 for (size_t i = 0; i < relays.size(); ++i) {
1181 if (relays[i].type == turn_type &&
1182 SupportsProtocol(relays[i], type))
1183 return true;
1184 }
1185 return false;
1186}
1187
1188ServerAddresses PortConfiguration::GetRelayServerAddresses(
1189 RelayType turn_type, ProtocolType type) const {
1190 ServerAddresses servers;
1191 for (size_t i = 0; i < relays.size(); ++i) {
1192 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1193 servers.insert(relays[i].ports.front().address);
1194 }
1195 }
1196 return servers;
1197}
1198
1199} // namespace cricket