blob: a14f85b6f289c0516ef732540b9081b5e6146d05 [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);
deadbeef653b8e02015-11-11 12:55:10 -0800107 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000108 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800109 }
110 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000111 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800112 }
113 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800115 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000116
deadbeef653b8e02015-11-11 12:55:10 -0800117 if (!config.ports.empty()) {
118 AddTurnServer(config);
119 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120
121 Construct();
122}
123
124void BasicPortAllocator::Construct() {
125 allow_tcp_listen_ = true;
126}
127
128BasicPortAllocator::~BasicPortAllocator() {
129}
130
deadbeefc5d0d952015-07-16 10:22:21 -0700131PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 const std::string& content_name, int component,
133 const std::string& ice_ufrag, const std::string& ice_pwd) {
134 return new BasicPortAllocatorSession(
135 this, content_name, component, ice_ufrag, ice_pwd);
136}
137
138
139// BasicPortAllocatorSession
140BasicPortAllocatorSession::BasicPortAllocatorSession(
141 BasicPortAllocator *allocator,
142 const std::string& content_name,
143 int component,
144 const std::string& ice_ufrag,
145 const std::string& ice_pwd)
146 : PortAllocatorSession(content_name, component,
147 ice_ufrag, ice_pwd, allocator->flags()),
148 allocator_(allocator), network_thread_(NULL),
149 socket_factory_(allocator->socket_factory()),
150 allocation_started_(false),
151 network_manager_started_(false),
152 running_(false),
153 allocation_sequences_created_(false) {
154 allocator_->network_manager()->SignalNetworksChanged.connect(
155 this, &BasicPortAllocatorSession::OnNetworksChanged);
156 allocator_->network_manager()->StartUpdating();
157}
158
159BasicPortAllocatorSession::~BasicPortAllocatorSession() {
160 allocator_->network_manager()->StopUpdating();
161 if (network_thread_ != NULL)
162 network_thread_->Clear(this);
163
Peter Boström0c4e06b2015-10-07 12:23:21 +0200164 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000165 // AllocationSequence should clear it's map entry for turn ports before
166 // ports are destroyed.
167 sequences_[i]->Clear();
168 }
169
170 std::vector<PortData>::iterator it;
171 for (it = ports_.begin(); it != ports_.end(); it++)
172 delete it->port();
173
Peter Boström0c4e06b2015-10-07 12:23:21 +0200174 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 delete configs_[i];
176
Peter Boström0c4e06b2015-10-07 12:23:21 +0200177 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 delete sequences_[i];
179}
180
181void BasicPortAllocatorSession::StartGettingPorts() {
182 network_thread_ = rtc::Thread::Current();
183 if (!socket_factory_) {
184 owned_socket_factory_.reset(
185 new rtc::BasicPacketSocketFactory(network_thread_));
186 socket_factory_ = owned_socket_factory_.get();
187 }
188
189 running_ = true;
190 network_thread_->Post(this, MSG_CONFIG_START);
191
192 if (flags() & PORTALLOCATOR_ENABLE_SHAKER)
193 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
194}
195
196void BasicPortAllocatorSession::StopGettingPorts() {
197 ASSERT(rtc::Thread::Current() == network_thread_);
198 running_ = false;
honghaiz98db68f2015-09-29 07:58:17 -0700199 network_thread_->Post(this, MSG_CONFIG_STOP);
200 ClearGettingPorts();
201}
202
203void BasicPortAllocatorSession::ClearGettingPorts() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204 network_thread_->Clear(this, MSG_ALLOCATE);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200205 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 sequences_[i]->Stop();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207}
208
209void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
210 switch (message->message_id) {
211 case MSG_CONFIG_START:
212 ASSERT(rtc::Thread::Current() == network_thread_);
213 GetPortConfigurations();
214 break;
215
216 case MSG_CONFIG_READY:
217 ASSERT(rtc::Thread::Current() == network_thread_);
218 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
219 break;
220
221 case MSG_ALLOCATE:
222 ASSERT(rtc::Thread::Current() == network_thread_);
223 OnAllocate();
224 break;
225
226 case MSG_SHAKE:
227 ASSERT(rtc::Thread::Current() == network_thread_);
228 OnShake();
229 break;
230 case MSG_SEQUENCEOBJECTS_CREATED:
231 ASSERT(rtc::Thread::Current() == network_thread_);
232 OnAllocationSequenceObjectsCreated();
233 break;
234 case MSG_CONFIG_STOP:
235 ASSERT(rtc::Thread::Current() == network_thread_);
236 OnConfigStop();
237 break;
238 default:
239 ASSERT(false);
240 }
241}
242
243void BasicPortAllocatorSession::GetPortConfigurations() {
244 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
245 username(),
246 password());
247
deadbeef653b8e02015-11-11 12:55:10 -0800248 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
249 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 }
251 ConfigReady(config);
252}
253
254void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
255 network_thread_->Post(this, MSG_CONFIG_READY, config);
256}
257
258// Adds a configuration to the list.
259void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800260 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800262 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263
264 AllocatePorts();
265}
266
267void BasicPortAllocatorSession::OnConfigStop() {
268 ASSERT(rtc::Thread::Current() == network_thread_);
269
270 // If any of the allocated ports have not completed the candidates allocation,
271 // mark those as error. Since session doesn't need any new candidates
272 // at this stage of the allocation, it's safe to discard any new candidates.
273 bool send_signal = false;
274 for (std::vector<PortData>::iterator it = ports_.begin();
275 it != ports_.end(); ++it) {
276 if (!it->complete()) {
277 // Updating port state to error, which didn't finish allocating candidates
278 // yet.
279 it->set_error();
280 send_signal = true;
281 }
282 }
283
284 // Did we stop any running sequences?
285 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
286 it != sequences_.end() && !send_signal; ++it) {
287 if ((*it)->state() == AllocationSequence::kStopped) {
288 send_signal = true;
289 }
290 }
291
292 // If we stopped anything that was running, send a done signal now.
293 if (send_signal) {
294 MaybeSignalCandidatesAllocationDone();
295 }
296}
297
298void BasicPortAllocatorSession::AllocatePorts() {
299 ASSERT(rtc::Thread::Current() == network_thread_);
300 network_thread_->Post(this, MSG_ALLOCATE);
301}
302
303void BasicPortAllocatorSession::OnAllocate() {
304 if (network_manager_started_)
305 DoAllocate();
306
307 allocation_started_ = true;
308}
309
honghaiz8c404fa2015-09-28 07:59:43 -0700310void BasicPortAllocatorSession::GetNetworks(
311 std::vector<rtc::Network*>* networks) {
312 networks->clear();
313 rtc::NetworkManager* network_manager = allocator_->network_manager();
314 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700315 // If the network permission state is BLOCKED, we just act as if the flag has
316 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700317 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700318 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700319 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
320 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000321 // If the adapter enumeration is disabled, we'll just bind to any address
322 // instead of specific NIC. This is to ensure the same routing for http
323 // traffic by OS is also used here to avoid any local or public IP leakage
324 // during stun process.
325 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
honghaiz8c404fa2015-09-28 07:59:43 -0700326 network_manager->GetAnyAddressNetworks(networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000327 } else {
honghaiz8c404fa2015-09-28 07:59:43 -0700328 network_manager->GetNetworks(networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000329 }
honghaiz8c404fa2015-09-28 07:59:43 -0700330}
331
332// For each network, see if we have a sequence that covers it already. If not,
333// create a new sequence to create the appropriate ports.
334void BasicPortAllocatorSession::DoAllocate() {
335 bool done_signal_needed = false;
336 std::vector<rtc::Network*> networks;
337 GetNetworks(&networks);
338
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 if (networks.empty()) {
340 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
341 done_signal_needed = true;
342 } else {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200343 for (uint32_t i = 0; i < networks.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000344 PortConfiguration* config = NULL;
345 if (configs_.size() > 0)
346 config = configs_.back();
347
Peter Boström0c4e06b2015-10-07 12:23:21 +0200348 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000349 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
350 // If all the ports are disabled we should just fire the allocation
351 // done event and return.
352 done_signal_needed = true;
353 break;
354 }
355
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356 if (!config || config->relays.empty()) {
357 // No relay ports specified in this config.
358 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
359 }
360
361 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000362 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000363 // Skip IPv6 networks unless the flag's been set.
364 continue;
365 }
366
367 // Disable phases that would only create ports equivalent to
368 // ones that we have already made.
369 DisableEquivalentPhases(networks[i], config, &sequence_flags);
370
371 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
372 // New AllocationSequence would have nothing to do, so don't make it.
373 continue;
374 }
375
376 AllocationSequence* sequence =
377 new AllocationSequence(this, networks[i], config, sequence_flags);
378 if (!sequence->Init()) {
379 delete sequence;
380 continue;
381 }
382 done_signal_needed = true;
383 sequence->SignalPortAllocationComplete.connect(
384 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
385 if (running_)
386 sequence->Start();
387 sequences_.push_back(sequence);
388 }
389 }
390 if (done_signal_needed) {
391 network_thread_->Post(this, MSG_SEQUENCEOBJECTS_CREATED);
392 }
393}
394
395void BasicPortAllocatorSession::OnNetworksChanged() {
honghaiz8c404fa2015-09-28 07:59:43 -0700396 std::vector<rtc::Network*> networks;
397 GetNetworks(&networks);
398 for (AllocationSequence* sequence : sequences_) {
399 // Remove the network from the allocation sequence if it is not in
400 // |networks|.
401 if (!sequence->network_removed() &&
402 std::find(networks.begin(), networks.end(), sequence->network()) ==
403 networks.end()) {
404 sequence->OnNetworkRemoved();
405 }
406 }
407
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000408 network_manager_started_ = true;
409 if (allocation_started_)
410 DoAllocate();
411}
412
413void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200414 rtc::Network* network,
415 PortConfiguration* config,
416 uint32_t* flags) {
417 for (uint32_t i = 0; i < sequences_.size() &&
418 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
419 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 sequences_[i]->DisableEquivalentPhases(network, config, flags);
421 }
422}
423
424void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
425 AllocationSequence * seq,
426 bool prepare_address) {
427 if (!port)
428 return;
429
430 LOG(LS_INFO) << "Adding allocated port for " << content_name();
431 port->set_content_name(content_name());
432 port->set_component(component_);
433 port->set_generation(generation());
434 if (allocator_->proxy().type != rtc::PROXY_NONE)
435 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
436 port->set_send_retransmit_count_attribute((allocator_->flags() &
437 PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
438
439 // Push down the candidate_filter to individual port.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200440 uint32_t candidate_filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000441
442 // When adapter enumeration is disabled, disable CF_HOST at port level so
443 // local address is not leaked by stunport in the candidate's related address.
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800444 if ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
445 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) {
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000446 candidate_filter &= ~CF_HOST;
447 }
448 port->set_candidate_filter(candidate_filter);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449
450 PortData data(port, seq);
451 ports_.push_back(data);
452
453 port->SignalCandidateReady.connect(
454 this, &BasicPortAllocatorSession::OnCandidateReady);
455 port->SignalPortComplete.connect(this,
456 &BasicPortAllocatorSession::OnPortComplete);
457 port->SignalDestroyed.connect(this,
458 &BasicPortAllocatorSession::OnPortDestroyed);
459 port->SignalPortError.connect(
460 this, &BasicPortAllocatorSession::OnPortError);
461 LOG_J(LS_INFO, port) << "Added port to allocator";
462
463 if (prepare_address)
464 port->PrepareAddress();
465}
466
467void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
468 allocation_sequences_created_ = true;
469 // Send candidate allocation complete signal if we have no sequences.
470 MaybeSignalCandidatesAllocationDone();
471}
472
473void BasicPortAllocatorSession::OnCandidateReady(
474 Port* port, const Candidate& c) {
475 ASSERT(rtc::Thread::Current() == network_thread_);
476 PortData* data = FindPort(port);
477 ASSERT(data != NULL);
478 // Discarding any candidate signal if port allocation status is
479 // already in completed state.
480 if (data->complete())
481 return;
482
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000483 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700484 bool candidate_signalable = CheckCandidateFilter(c);
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700485
486 // When device enumeration is disabled (to prevent non-default IP addresses
487 // from leaking), we ping from some local candidates even though we don't
488 // signal them. However, if host candidates are also disabled (for example, to
489 // prevent even default IP addresses from leaking), we still don't want to
490 // ping from them, even if device enumeration is disabled. Thus, we check for
491 // both device enumeration and host candidates being disabled.
492 bool network_enumeration_disabled = c.address().IsAnyIP();
493 bool can_ping_from_candidate =
494 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
495 bool host_canidates_disabled = !(allocator_->candidate_filter() & CF_HOST);
496
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700497 bool candidate_pairable =
498 candidate_signalable ||
Guo-wei Shieh898d21c2015-09-30 10:54:55 -0700499 (network_enumeration_disabled && can_ping_from_candidate &&
500 !host_canidates_disabled);
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700501 bool candidate_protocol_enabled =
502 StringToProto(c.protocol().c_str(), &pvalue) &&
503 data->sequence()->ProtocolEnabled(pvalue);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700505 if (candidate_signalable && candidate_protocol_enabled) {
506 std::vector<Candidate> candidates;
507 candidates.push_back(c);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508 SignalCandidatesReady(this, candidates);
509 }
510
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700511 // Port has been made ready. Nothing to do here.
512 if (data->ready()) {
513 return;
514 }
515
516 // Move the port to the READY state, either because we have a usable candidate
517 // from the port, or simply because the port is bound to the any address and
518 // therefore has no host candidate. This will trigger the port to start
519 // creating candidate pairs (connections) and issue connectivity checks.
520 if (candidate_pairable) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000521 data->set_ready();
522 SignalPortReady(this, port);
523 }
524}
525
526void BasicPortAllocatorSession::OnPortComplete(Port* port) {
527 ASSERT(rtc::Thread::Current() == network_thread_);
528 PortData* data = FindPort(port);
529 ASSERT(data != NULL);
530
531 // Ignore any late signals.
532 if (data->complete())
533 return;
534
535 // Moving to COMPLETE state.
536 data->set_complete();
537 // Send candidate allocation complete signal if this was the last port.
538 MaybeSignalCandidatesAllocationDone();
539}
540
541void BasicPortAllocatorSession::OnPortError(Port* port) {
542 ASSERT(rtc::Thread::Current() == network_thread_);
543 PortData* data = FindPort(port);
544 ASSERT(data != NULL);
545 // We might have already given up on this port and stopped it.
546 if (data->complete())
547 return;
548
549 // SignalAddressError is currently sent from StunPort/TurnPort.
550 // But this signal itself is generic.
551 data->set_error();
552 // Send candidate allocation complete signal if this was the last port.
553 MaybeSignalCandidatesAllocationDone();
554}
555
556void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
557 ProtocolType proto) {
558 std::vector<Candidate> candidates;
559 for (std::vector<PortData>::iterator it = ports_.begin();
560 it != ports_.end(); ++it) {
561 if (it->sequence() != seq)
562 continue;
563
564 const std::vector<Candidate>& potentials = it->port()->Candidates();
565 for (size_t i = 0; i < potentials.size(); ++i) {
566 if (!CheckCandidateFilter(potentials[i]))
567 continue;
568 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700569 bool candidate_protocol_enabled =
570 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
571 pvalue == proto;
572 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000573 candidates.push_back(potentials[i]);
574 }
575 }
576 }
577
578 if (!candidates.empty()) {
579 SignalCandidatesReady(this, candidates);
580 }
581}
582
583bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200584 uint32_t filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000585
586 // When binding to any address, before sending packets out, the getsockname
587 // returns all 0s, but after sending packets, it'll be the NIC used to
588 // send. All 0s is not a valid ICE candidate address and should be filtered
589 // out.
590 if (c.address().IsAnyIP()) {
591 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 }
593
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000594 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000595 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000596 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000597 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000598 } else if (c.type() == LOCAL_PORT_TYPE) {
599 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
600 // We allow host candidates if the filter allows server-reflexive
601 // candidates and the candidate is a public IP. Because we don't generate
602 // server-reflexive candidates if they have the same IP as the host
603 // candidate (i.e. when the host candidate is a public IP), filtering to
604 // only server-reflexive candidates won't work right when the host
605 // candidates have public IPs.
606 return true;
607 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000609 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000610 }
611 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612}
613
614void BasicPortAllocatorSession::OnPortAllocationComplete(
615 AllocationSequence* seq) {
616 // Send candidate allocation complete signal if all ports are done.
617 MaybeSignalCandidatesAllocationDone();
618}
619
620void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
621 // Send signal only if all required AllocationSequence objects
622 // are created.
623 if (!allocation_sequences_created_)
624 return;
625
626 // Check that all port allocation sequences are complete.
627 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
628 it != sequences_.end(); ++it) {
629 if ((*it)->state() == AllocationSequence::kRunning)
630 return;
631 }
632
633 // If all allocated ports are in complete state, session must have got all
634 // expected candidates. Session will trigger candidates allocation complete
635 // signal.
636 for (std::vector<PortData>::iterator it = ports_.begin();
637 it != ports_.end(); ++it) {
638 if (!it->complete())
639 return;
640 }
641 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
642 << component_ << ":" << generation();
643 SignalCandidatesAllocationDone(this);
644}
645
646void BasicPortAllocatorSession::OnPortDestroyed(
647 PortInterface* port) {
648 ASSERT(rtc::Thread::Current() == network_thread_);
649 for (std::vector<PortData>::iterator iter = ports_.begin();
650 iter != ports_.end(); ++iter) {
651 if (port == iter->port()) {
652 ports_.erase(iter);
653 LOG_J(LS_INFO, port) << "Removed port from allocator ("
654 << static_cast<int>(ports_.size()) << " remaining)";
655 return;
656 }
657 }
658 ASSERT(false);
659}
660
661void BasicPortAllocatorSession::OnShake() {
662 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
663
664 std::vector<Port*> ports;
665 std::vector<Connection*> connections;
666
667 for (size_t i = 0; i < ports_.size(); ++i) {
668 if (ports_[i].ready())
669 ports.push_back(ports_[i].port());
670 }
671
672 for (size_t i = 0; i < ports.size(); ++i) {
673 Port::AddressMap::const_iterator iter;
674 for (iter = ports[i]->connections().begin();
675 iter != ports[i]->connections().end();
676 ++iter) {
677 connections.push_back(iter->second);
678 }
679 }
680
681 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
682 << connections.size() << " connections";
683
684 for (size_t i = 0; i < connections.size(); ++i)
685 connections[i]->Destroy();
686
687 if (running_ || (ports.size() > 0) || (connections.size() > 0))
688 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
689}
690
691BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
692 Port* port) {
693 for (std::vector<PortData>::iterator it = ports_.begin();
694 it != ports_.end(); ++it) {
695 if (it->port() == port) {
696 return &*it;
697 }
698 }
699 return NULL;
700}
701
702// AllocationSequence
703
704AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
705 rtc::Network* network,
706 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200707 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708 : session_(session),
709 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000710 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000711 config_(config),
712 state_(kInit),
713 flags_(flags),
714 udp_socket_(),
715 udp_port_(NULL),
716 phase_(0) {
717}
718
719bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000720 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
721 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
722 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
723 session_->allocator()->max_port()));
724 if (udp_socket_) {
725 udp_socket_->SignalReadPacket.connect(
726 this, &AllocationSequence::OnReadPacket);
727 }
728 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
729 // are next available options to setup a communication channel.
730 }
731 return true;
732}
733
734void AllocationSequence::Clear() {
735 udp_port_ = NULL;
736 turn_ports_.clear();
737}
738
honghaiz8c404fa2015-09-28 07:59:43 -0700739void AllocationSequence::OnNetworkRemoved() {
740 // Stop the allocation sequence if its network is gone.
741 Stop();
742 network_removed_ = true;
743}
744
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000745AllocationSequence::~AllocationSequence() {
746 session_->network_thread()->Clear(this);
747}
748
749void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200750 PortConfiguration* config, uint32_t* flags) {
honghaiz8c404fa2015-09-28 07:59:43 -0700751 if (network_removed_) {
752 // If the network of this allocation sequence has ever gone away,
753 // it won't be equivalent to the new network.
754 return;
755 }
756
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000758 // Different network setup; nothing is equivalent.
759 return;
760 }
761
762 // Else turn off the stuff that we've already got covered.
763
764 // Every config implicitly specifies local, so turn that off right away.
765 *flags |= PORTALLOCATOR_DISABLE_UDP;
766 *flags |= PORTALLOCATOR_DISABLE_TCP;
767
768 if (config_ && config) {
769 if (config_->StunServers() == config->StunServers()) {
770 // Already got this STUN servers covered.
771 *flags |= PORTALLOCATOR_DISABLE_STUN;
772 }
773 if (!config_->relays.empty()) {
774 // Already got relays covered.
775 // NOTE: This will even skip a _different_ set of relay servers if we
776 // were to be given one, but that never happens in our codebase. Should
777 // probably get rid of the list in PortConfiguration and just keep a
778 // single relay server in each one.
779 *flags |= PORTALLOCATOR_DISABLE_RELAY;
780 }
781 }
782}
783
784void AllocationSequence::Start() {
785 state_ = kRunning;
786 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
787}
788
789void AllocationSequence::Stop() {
790 // If the port is completed, don't set it to stopped.
791 if (state_ == kRunning) {
792 state_ = kStopped;
793 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
794 }
795}
796
797void AllocationSequence::OnMessage(rtc::Message* msg) {
798 ASSERT(rtc::Thread::Current() == session_->network_thread());
799 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
800
801 const char* const PHASE_NAMES[kNumPhases] = {
802 "Udp", "Relay", "Tcp", "SslTcp"
803 };
804
805 // Perform all of the phases in the current step.
806 LOG_J(LS_INFO, network_) << "Allocation Phase="
807 << PHASE_NAMES[phase_];
808
809 switch (phase_) {
810 case PHASE_UDP:
811 CreateUDPPorts();
812 CreateStunPorts();
813 EnableProtocol(PROTO_UDP);
814 break;
815
816 case PHASE_RELAY:
817 CreateRelayPorts();
818 break;
819
820 case PHASE_TCP:
821 CreateTCPPorts();
822 EnableProtocol(PROTO_TCP);
823 break;
824
825 case PHASE_SSLTCP:
826 state_ = kCompleted;
827 EnableProtocol(PROTO_SSLTCP);
828 break;
829
830 default:
831 ASSERT(false);
832 }
833
834 if (state() == kRunning) {
835 ++phase_;
836 session_->network_thread()->PostDelayed(
837 session_->allocator()->step_delay(),
838 this, MSG_ALLOCATION_PHASE);
839 } else {
840 // If all phases in AllocationSequence are completed, no allocation
841 // steps needed further. Canceling pending signal.
842 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
843 SignalPortAllocationComplete(this);
844 }
845}
846
847void AllocationSequence::EnableProtocol(ProtocolType proto) {
848 if (!ProtocolEnabled(proto)) {
849 protocols_.push_back(proto);
850 session_->OnProtocolEnabled(this, proto);
851 }
852}
853
854bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
855 for (ProtocolList::const_iterator it = protocols_.begin();
856 it != protocols_.end(); ++it) {
857 if (*it == proto)
858 return true;
859 }
860 return false;
861}
862
863void AllocationSequence::CreateUDPPorts() {
864 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
865 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
866 return;
867 }
868
869 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
870 // is enabled completely.
871 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800872 bool emit_local_candidate_for_anyaddress =
873 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700875 port = UDPPort::Create(
876 session_->network_thread(), session_->socket_factory(), network_,
877 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800878 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700880 port = UDPPort::Create(
881 session_->network_thread(), session_->socket_factory(), network_, ip_,
882 session_->allocator()->min_port(), session_->allocator()->max_port(),
883 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800884 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 }
886
887 if (port) {
888 // If shared socket is enabled, STUN candidate will be allocated by the
889 // UDPPort.
890 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
891 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000892 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893
894 // If STUN is not disabled, setting stun server address to port.
895 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000896 if (config_ && !config_->StunServers().empty()) {
897 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
898 << "STUN candidate generation.";
899 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 }
901 }
902 }
903
904 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905 }
906}
907
908void AllocationSequence::CreateTCPPorts() {
909 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
910 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
911 return;
912 }
913
914 Port* port = TCPPort::Create(session_->network_thread(),
915 session_->socket_factory(),
916 network_, ip_,
917 session_->allocator()->min_port(),
918 session_->allocator()->max_port(),
919 session_->username(), session_->password(),
920 session_->allocator()->allow_tcp_listen());
921 if (port) {
922 session_->AddAllocatedPort(port, this, true);
923 // Since TCPPort is not created using shared socket, |port| will not be
924 // added to the dequeue.
925 }
926}
927
928void AllocationSequence::CreateStunPorts() {
929 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
930 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
931 return;
932 }
933
934 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
935 return;
936 }
937
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000938 if (!(config_ && !config_->StunServers().empty())) {
939 LOG(LS_WARNING)
940 << "AllocationSequence: No STUN server configured, skipping.";
941 return;
942 }
943
944 StunPort* port = StunPort::Create(session_->network_thread(),
945 session_->socket_factory(),
946 network_, ip_,
947 session_->allocator()->min_port(),
948 session_->allocator()->max_port(),
949 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000950 config_->StunServers(),
951 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952 if (port) {
953 session_->AddAllocatedPort(port, this, true);
954 // Since StunPort is not created using shared socket, |port| will not be
955 // added to the dequeue.
956 }
957}
958
959void AllocationSequence::CreateRelayPorts() {
960 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
961 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
962 return;
963 }
964
965 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
966 // ought to have a relay list for them here.
967 ASSERT(config_ && !config_->relays.empty());
968 if (!(config_ && !config_->relays.empty())) {
969 LOG(LS_WARNING)
970 << "AllocationSequence: No relay server configured, skipping.";
971 return;
972 }
973
974 PortConfiguration::RelayList::const_iterator relay;
975 for (relay = config_->relays.begin();
976 relay != config_->relays.end(); ++relay) {
977 if (relay->type == RELAY_GTURN) {
978 CreateGturnPort(*relay);
979 } else if (relay->type == RELAY_TURN) {
980 CreateTurnPort(*relay);
981 } else {
982 ASSERT(false);
983 }
984 }
985}
986
987void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
988 // TODO(mallinath) - Rename RelayPort to GTurnPort.
989 RelayPort* port = RelayPort::Create(session_->network_thread(),
990 session_->socket_factory(),
991 network_, ip_,
992 session_->allocator()->min_port(),
993 session_->allocator()->max_port(),
994 config_->username, config_->password);
995 if (port) {
996 // Since RelayPort is not created using shared socket, |port| will not be
997 // added to the dequeue.
998 // Note: We must add the allocated port before we add addresses because
999 // the latter will create candidates that need name and preference
1000 // settings. However, we also can't prepare the address (normally
1001 // done by AddAllocatedPort) until we have these addresses. So we
1002 // wait to do that until below.
1003 session_->AddAllocatedPort(port, this, false);
1004
1005 // Add the addresses of this protocol.
1006 PortList::const_iterator relay_port;
1007 for (relay_port = config.ports.begin();
1008 relay_port != config.ports.end();
1009 ++relay_port) {
1010 port->AddServerAddress(*relay_port);
1011 port->AddExternalAddress(*relay_port);
1012 }
1013 // Start fetching an address for this port.
1014 port->PrepareAddress();
1015 }
1016}
1017
1018void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1019 PortList::const_iterator relay_port;
1020 for (relay_port = config.ports.begin();
1021 relay_port != config.ports.end(); ++relay_port) {
1022 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001023
1024 // Skip UDP connections to relay servers if it's disallowed.
1025 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1026 relay_port->proto == PROTO_UDP) {
1027 continue;
1028 }
1029
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030 // Shared socket mode must be enabled only for UDP based ports. Hence
1031 // don't pass shared socket for ports which will create TCP sockets.
1032 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1033 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1034 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001035 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001036 port = TurnPort::Create(session_->network_thread(),
1037 session_->socket_factory(),
1038 network_, udp_socket_.get(),
1039 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001040 *relay_port, config.credentials, config.priority,
1041 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001042 turn_ports_.push_back(port);
1043 // Listen to the port destroyed signal, to allow AllocationSequence to
1044 // remove entrt from it's map.
1045 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1046 } else {
1047 port = TurnPort::Create(session_->network_thread(),
1048 session_->socket_factory(),
1049 network_, ip_,
1050 session_->allocator()->min_port(),
1051 session_->allocator()->max_port(),
1052 session_->username(),
1053 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001054 *relay_port, config.credentials, config.priority,
1055 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001056 }
1057 ASSERT(port != NULL);
1058 session_->AddAllocatedPort(port, this, true);
1059 }
1060}
1061
1062void AllocationSequence::OnReadPacket(
1063 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1064 const rtc::SocketAddress& remote_addr,
1065 const rtc::PacketTime& packet_time) {
1066 ASSERT(socket == udp_socket_.get());
1067
1068 bool turn_port_found = false;
1069
1070 // Try to find the TurnPort that matches the remote address. Note that the
1071 // message could be a STUN binding response if the TURN server is also used as
1072 // a STUN server. We don't want to parse every message here to check if it is
1073 // a STUN binding response, so we pass the message to TurnPort regardless of
1074 // the message type. The TurnPort will just ignore the message since it will
1075 // not find any request by transaction ID.
1076 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1077 it != turn_ports_.end(); ++it) {
1078 TurnPort* port = *it;
1079 if (port->server_address().address == remote_addr) {
1080 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1081 turn_port_found = true;
1082 break;
1083 }
1084 }
1085
1086 if (udp_port_) {
1087 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1088
1089 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1090 // the TURN server is also a STUN server.
1091 if (!turn_port_found ||
1092 stun_servers.find(remote_addr) != stun_servers.end()) {
1093 udp_port_->HandleIncomingPacket(
1094 socket, data, size, remote_addr, packet_time);
1095 }
1096 }
1097}
1098
1099void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1100 if (udp_port_ == port) {
1101 udp_port_ = NULL;
1102 return;
1103 }
1104
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001105 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1106 if (it != turn_ports_.end()) {
1107 turn_ports_.erase(it);
1108 } else {
1109 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1110 ASSERT(false);
1111 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001112}
1113
1114// PortConfiguration
1115PortConfiguration::PortConfiguration(
1116 const rtc::SocketAddress& stun_address,
1117 const std::string& username,
1118 const std::string& password)
1119 : stun_address(stun_address), username(username), password(password) {
1120 if (!stun_address.IsNil())
1121 stun_servers.insert(stun_address);
1122}
1123
1124PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1125 const std::string& username,
1126 const std::string& password)
1127 : stun_servers(stun_servers),
1128 username(username),
1129 password(password) {
1130 if (!stun_servers.empty())
1131 stun_address = *(stun_servers.begin());
1132}
1133
1134ServerAddresses PortConfiguration::StunServers() {
1135 if (!stun_address.IsNil() &&
1136 stun_servers.find(stun_address) == stun_servers.end()) {
1137 stun_servers.insert(stun_address);
1138 }
deadbeefc5d0d952015-07-16 10:22:21 -07001139 // Every UDP TURN server should also be used as a STUN server.
1140 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1141 for (const rtc::SocketAddress& turn_server : turn_servers) {
1142 if (stun_servers.find(turn_server) == stun_servers.end()) {
1143 stun_servers.insert(turn_server);
1144 }
1145 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001146 return stun_servers;
1147}
1148
1149void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1150 relays.push_back(config);
1151}
1152
1153bool PortConfiguration::SupportsProtocol(
1154 const RelayServerConfig& relay, ProtocolType type) const {
1155 PortList::const_iterator relay_port;
1156 for (relay_port = relay.ports.begin();
1157 relay_port != relay.ports.end();
1158 ++relay_port) {
1159 if (relay_port->proto == type)
1160 return true;
1161 }
1162 return false;
1163}
1164
1165bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1166 ProtocolType type) const {
1167 for (size_t i = 0; i < relays.size(); ++i) {
1168 if (relays[i].type == turn_type &&
1169 SupportsProtocol(relays[i], type))
1170 return true;
1171 }
1172 return false;
1173}
1174
1175ServerAddresses PortConfiguration::GetRelayServerAddresses(
1176 RelayType turn_type, ProtocolType type) const {
1177 ServerAddresses servers;
1178 for (size_t i = 0; i < relays.size(); ++i) {
1179 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1180 servers.insert(relays[i].ports.front().address);
1181 }
1182 }
1183 return servers;
1184}
1185
1186} // namespace cricket