blob: 3f5aa0a1ff396cbb512d65166d46c54c598b70b9 [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"
24#include "webrtc/base/common.h"
25#include "webrtc/base/helpers.h"
26#include "webrtc/base/logging.h"
27
28using rtc::CreateRandomId;
29using rtc::CreateRandomString;
30
31namespace {
32
33enum {
34 MSG_CONFIG_START,
35 MSG_CONFIG_READY,
36 MSG_ALLOCATE,
37 MSG_ALLOCATION_PHASE,
38 MSG_SHAKE,
39 MSG_SEQUENCEOBJECTS_CREATED,
40 MSG_CONFIG_STOP,
41};
42
43const int PHASE_UDP = 0;
44const int PHASE_RELAY = 1;
45const int PHASE_TCP = 2;
46const int PHASE_SSLTCP = 3;
47
48const int kNumPhases = 4;
49
50const int SHAKE_MIN_DELAY = 45 * 1000; // 45 seconds
51const int SHAKE_MAX_DELAY = 90 * 1000; // 90 seconds
52
53int ShakeDelay() {
54 int range = SHAKE_MAX_DELAY - SHAKE_MIN_DELAY + 1;
55 return SHAKE_MIN_DELAY + CreateRandomId() % range;
56}
57
58} // namespace
59
60namespace cricket {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000061const uint32 DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070062 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
63 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064
65// BasicPortAllocator
66BasicPortAllocator::BasicPortAllocator(
67 rtc::NetworkManager* network_manager,
68 rtc::PacketSocketFactory* socket_factory)
69 : network_manager_(network_manager),
eblima894ad942015-07-03 08:34:33 -070070 socket_factory_(socket_factory),
71 stun_servers_() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072 ASSERT(socket_factory_ != NULL);
73 Construct();
74}
75
76BasicPortAllocator::BasicPortAllocator(
77 rtc::NetworkManager* network_manager)
78 : network_manager_(network_manager),
eblima894ad942015-07-03 08:34:33 -070079 socket_factory_(NULL),
80 stun_servers_() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000081 Construct();
82}
83
84BasicPortAllocator::BasicPortAllocator(
85 rtc::NetworkManager* network_manager,
86 rtc::PacketSocketFactory* socket_factory,
87 const ServerAddresses& stun_servers)
88 : network_manager_(network_manager),
89 socket_factory_(socket_factory),
90 stun_servers_(stun_servers) {
91 ASSERT(socket_factory_ != NULL);
92 Construct();
93}
94
95BasicPortAllocator::BasicPortAllocator(
96 rtc::NetworkManager* network_manager,
97 const ServerAddresses& stun_servers,
98 const rtc::SocketAddress& relay_address_udp,
99 const rtc::SocketAddress& relay_address_tcp,
100 const rtc::SocketAddress& relay_address_ssl)
101 : network_manager_(network_manager),
102 socket_factory_(NULL),
103 stun_servers_(stun_servers) {
104
105 RelayServerConfig config(RELAY_GTURN);
106 if (!relay_address_udp.IsNil())
107 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
108 if (!relay_address_tcp.IsNil())
109 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
110 if (!relay_address_ssl.IsNil())
111 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
112
113 if (!config.ports.empty())
114 AddRelay(config);
115
116 Construct();
117}
118
119void BasicPortAllocator::Construct() {
120 allow_tcp_listen_ = true;
121}
122
123BasicPortAllocator::~BasicPortAllocator() {
124}
125
deadbeefc5d0d952015-07-16 10:22:21 -0700126PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127 const std::string& content_name, int component,
128 const std::string& ice_ufrag, const std::string& ice_pwd) {
129 return new BasicPortAllocatorSession(
130 this, content_name, component, ice_ufrag, ice_pwd);
131}
132
133
134// BasicPortAllocatorSession
135BasicPortAllocatorSession::BasicPortAllocatorSession(
136 BasicPortAllocator *allocator,
137 const std::string& content_name,
138 int component,
139 const std::string& ice_ufrag,
140 const std::string& ice_pwd)
141 : PortAllocatorSession(content_name, component,
142 ice_ufrag, ice_pwd, allocator->flags()),
143 allocator_(allocator), network_thread_(NULL),
144 socket_factory_(allocator->socket_factory()),
145 allocation_started_(false),
146 network_manager_started_(false),
147 running_(false),
148 allocation_sequences_created_(false) {
149 allocator_->network_manager()->SignalNetworksChanged.connect(
150 this, &BasicPortAllocatorSession::OnNetworksChanged);
151 allocator_->network_manager()->StartUpdating();
152}
153
154BasicPortAllocatorSession::~BasicPortAllocatorSession() {
155 allocator_->network_manager()->StopUpdating();
156 if (network_thread_ != NULL)
157 network_thread_->Clear(this);
158
159 for (uint32 i = 0; i < sequences_.size(); ++i) {
160 // AllocationSequence should clear it's map entry for turn ports before
161 // ports are destroyed.
162 sequences_[i]->Clear();
163 }
164
165 std::vector<PortData>::iterator it;
166 for (it = ports_.begin(); it != ports_.end(); it++)
167 delete it->port();
168
169 for (uint32 i = 0; i < configs_.size(); ++i)
170 delete configs_[i];
171
172 for (uint32 i = 0; i < sequences_.size(); ++i)
173 delete sequences_[i];
174}
175
176void BasicPortAllocatorSession::StartGettingPorts() {
177 network_thread_ = rtc::Thread::Current();
178 if (!socket_factory_) {
179 owned_socket_factory_.reset(
180 new rtc::BasicPacketSocketFactory(network_thread_));
181 socket_factory_ = owned_socket_factory_.get();
182 }
183
184 running_ = true;
185 network_thread_->Post(this, MSG_CONFIG_START);
186
187 if (flags() & PORTALLOCATOR_ENABLE_SHAKER)
188 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
189}
190
191void BasicPortAllocatorSession::StopGettingPorts() {
192 ASSERT(rtc::Thread::Current() == network_thread_);
193 running_ = false;
194 network_thread_->Clear(this, MSG_ALLOCATE);
195 for (uint32 i = 0; i < sequences_.size(); ++i)
196 sequences_[i]->Stop();
197 network_thread_->Post(this, MSG_CONFIG_STOP);
198}
199
200void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
201 switch (message->message_id) {
202 case MSG_CONFIG_START:
203 ASSERT(rtc::Thread::Current() == network_thread_);
204 GetPortConfigurations();
205 break;
206
207 case MSG_CONFIG_READY:
208 ASSERT(rtc::Thread::Current() == network_thread_);
209 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
210 break;
211
212 case MSG_ALLOCATE:
213 ASSERT(rtc::Thread::Current() == network_thread_);
214 OnAllocate();
215 break;
216
217 case MSG_SHAKE:
218 ASSERT(rtc::Thread::Current() == network_thread_);
219 OnShake();
220 break;
221 case MSG_SEQUENCEOBJECTS_CREATED:
222 ASSERT(rtc::Thread::Current() == network_thread_);
223 OnAllocationSequenceObjectsCreated();
224 break;
225 case MSG_CONFIG_STOP:
226 ASSERT(rtc::Thread::Current() == network_thread_);
227 OnConfigStop();
228 break;
229 default:
230 ASSERT(false);
231 }
232}
233
234void BasicPortAllocatorSession::GetPortConfigurations() {
235 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
236 username(),
237 password());
238
239 for (size_t i = 0; i < allocator_->relays().size(); ++i) {
240 config->AddRelay(allocator_->relays()[i]);
241 }
242 ConfigReady(config);
243}
244
245void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
246 network_thread_->Post(this, MSG_CONFIG_READY, config);
247}
248
249// Adds a configuration to the list.
250void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
251 if (config)
252 configs_.push_back(config);
253
254 AllocatePorts();
255}
256
257void BasicPortAllocatorSession::OnConfigStop() {
258 ASSERT(rtc::Thread::Current() == network_thread_);
259
260 // If any of the allocated ports have not completed the candidates allocation,
261 // mark those as error. Since session doesn't need any new candidates
262 // at this stage of the allocation, it's safe to discard any new candidates.
263 bool send_signal = false;
264 for (std::vector<PortData>::iterator it = ports_.begin();
265 it != ports_.end(); ++it) {
266 if (!it->complete()) {
267 // Updating port state to error, which didn't finish allocating candidates
268 // yet.
269 it->set_error();
270 send_signal = true;
271 }
272 }
273
274 // Did we stop any running sequences?
275 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
276 it != sequences_.end() && !send_signal; ++it) {
277 if ((*it)->state() == AllocationSequence::kStopped) {
278 send_signal = true;
279 }
280 }
281
282 // If we stopped anything that was running, send a done signal now.
283 if (send_signal) {
284 MaybeSignalCandidatesAllocationDone();
285 }
286}
287
288void BasicPortAllocatorSession::AllocatePorts() {
289 ASSERT(rtc::Thread::Current() == network_thread_);
290 network_thread_->Post(this, MSG_ALLOCATE);
291}
292
293void BasicPortAllocatorSession::OnAllocate() {
294 if (network_manager_started_)
295 DoAllocate();
296
297 allocation_started_ = true;
298}
299
300// For each network, see if we have a sequence that covers it already. If not,
301// create a new sequence to create the appropriate ports.
302void BasicPortAllocatorSession::DoAllocate() {
303 bool done_signal_needed = false;
304 std::vector<rtc::Network*> networks;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000305
306 // If the adapter enumeration is disabled, we'll just bind to any address
307 // instead of specific NIC. This is to ensure the same routing for http
308 // traffic by OS is also used here to avoid any local or public IP leakage
309 // during stun process.
310 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
311 allocator_->network_manager()->GetAnyAddressNetworks(&networks);
312 } else {
313 allocator_->network_manager()->GetNetworks(&networks);
314 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000315 if (networks.empty()) {
316 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
317 done_signal_needed = true;
318 } else {
319 for (uint32 i = 0; i < networks.size(); ++i) {
320 PortConfiguration* config = NULL;
321 if (configs_.size() > 0)
322 config = configs_.back();
323
324 uint32 sequence_flags = flags();
325 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
326 // If all the ports are disabled we should just fire the allocation
327 // done event and return.
328 done_signal_needed = true;
329 break;
330 }
331
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000332 if (!config || config->relays.empty()) {
333 // No relay ports specified in this config.
334 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
335 }
336
337 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000338 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 // Skip IPv6 networks unless the flag's been set.
340 continue;
341 }
342
343 // Disable phases that would only create ports equivalent to
344 // ones that we have already made.
345 DisableEquivalentPhases(networks[i], config, &sequence_flags);
346
347 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
348 // New AllocationSequence would have nothing to do, so don't make it.
349 continue;
350 }
351
352 AllocationSequence* sequence =
353 new AllocationSequence(this, networks[i], config, sequence_flags);
354 if (!sequence->Init()) {
355 delete sequence;
356 continue;
357 }
358 done_signal_needed = true;
359 sequence->SignalPortAllocationComplete.connect(
360 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
361 if (running_)
362 sequence->Start();
363 sequences_.push_back(sequence);
364 }
365 }
366 if (done_signal_needed) {
367 network_thread_->Post(this, MSG_SEQUENCEOBJECTS_CREATED);
368 }
369}
370
371void BasicPortAllocatorSession::OnNetworksChanged() {
372 network_manager_started_ = true;
373 if (allocation_started_)
374 DoAllocate();
375}
376
377void BasicPortAllocatorSession::DisableEquivalentPhases(
378 rtc::Network* network, PortConfiguration* config, uint32* flags) {
379 for (uint32 i = 0; i < sequences_.size() &&
380 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES; ++i) {
381 sequences_[i]->DisableEquivalentPhases(network, config, flags);
382 }
383}
384
385void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
386 AllocationSequence * seq,
387 bool prepare_address) {
388 if (!port)
389 return;
390
391 LOG(LS_INFO) << "Adding allocated port for " << content_name();
392 port->set_content_name(content_name());
393 port->set_component(component_);
394 port->set_generation(generation());
395 if (allocator_->proxy().type != rtc::PROXY_NONE)
396 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
397 port->set_send_retransmit_count_attribute((allocator_->flags() &
398 PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
399
400 // Push down the candidate_filter to individual port.
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000401 uint32 candidate_filter = allocator_->candidate_filter();
402
403 // When adapter enumeration is disabled, disable CF_HOST at port level so
404 // local address is not leaked by stunport in the candidate's related address.
405 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
406 candidate_filter &= ~CF_HOST;
407 }
408 port->set_candidate_filter(candidate_filter);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409
410 PortData data(port, seq);
411 ports_.push_back(data);
412
413 port->SignalCandidateReady.connect(
414 this, &BasicPortAllocatorSession::OnCandidateReady);
415 port->SignalPortComplete.connect(this,
416 &BasicPortAllocatorSession::OnPortComplete);
417 port->SignalDestroyed.connect(this,
418 &BasicPortAllocatorSession::OnPortDestroyed);
419 port->SignalPortError.connect(
420 this, &BasicPortAllocatorSession::OnPortError);
421 LOG_J(LS_INFO, port) << "Added port to allocator";
422
423 if (prepare_address)
424 port->PrepareAddress();
425}
426
427void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
428 allocation_sequences_created_ = true;
429 // Send candidate allocation complete signal if we have no sequences.
430 MaybeSignalCandidatesAllocationDone();
431}
432
433void BasicPortAllocatorSession::OnCandidateReady(
434 Port* port, const Candidate& c) {
435 ASSERT(rtc::Thread::Current() == network_thread_);
436 PortData* data = FindPort(port);
437 ASSERT(data != NULL);
438 // Discarding any candidate signal if port allocation status is
439 // already in completed state.
440 if (data->complete())
441 return;
442
443 // Send candidates whose protocol is enabled.
444 std::vector<Candidate> candidates;
445 ProtocolType pvalue;
446 bool candidate_allowed_to_send = CheckCandidateFilter(c);
447 if (StringToProto(c.protocol().c_str(), &pvalue) &&
448 data->sequence()->ProtocolEnabled(pvalue) &&
449 candidate_allowed_to_send) {
450 candidates.push_back(c);
451 }
452
453 if (!candidates.empty()) {
454 SignalCandidatesReady(this, candidates);
455 }
456
457 // Moving to READY state as we have atleast one candidate from the port.
458 // Since this port has atleast one candidate we should forward this port
459 // to listners, to allow connections from this port.
460 // Also we should make sure that candidate gathered from this port is allowed
461 // to send outside.
462 if (!data->ready() && candidate_allowed_to_send) {
463 data->set_ready();
464 SignalPortReady(this, port);
465 }
466}
467
468void BasicPortAllocatorSession::OnPortComplete(Port* port) {
469 ASSERT(rtc::Thread::Current() == network_thread_);
470 PortData* data = FindPort(port);
471 ASSERT(data != NULL);
472
473 // Ignore any late signals.
474 if (data->complete())
475 return;
476
477 // Moving to COMPLETE state.
478 data->set_complete();
479 // Send candidate allocation complete signal if this was the last port.
480 MaybeSignalCandidatesAllocationDone();
481}
482
483void BasicPortAllocatorSession::OnPortError(Port* port) {
484 ASSERT(rtc::Thread::Current() == network_thread_);
485 PortData* data = FindPort(port);
486 ASSERT(data != NULL);
487 // We might have already given up on this port and stopped it.
488 if (data->complete())
489 return;
490
491 // SignalAddressError is currently sent from StunPort/TurnPort.
492 // But this signal itself is generic.
493 data->set_error();
494 // Send candidate allocation complete signal if this was the last port.
495 MaybeSignalCandidatesAllocationDone();
496}
497
498void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
499 ProtocolType proto) {
500 std::vector<Candidate> candidates;
501 for (std::vector<PortData>::iterator it = ports_.begin();
502 it != ports_.end(); ++it) {
503 if (it->sequence() != seq)
504 continue;
505
506 const std::vector<Candidate>& potentials = it->port()->Candidates();
507 for (size_t i = 0; i < potentials.size(); ++i) {
508 if (!CheckCandidateFilter(potentials[i]))
509 continue;
510 ProtocolType pvalue;
511 if (!StringToProto(potentials[i].protocol().c_str(), &pvalue))
512 continue;
513 if (pvalue == proto) {
514 candidates.push_back(potentials[i]);
515 }
516 }
517 }
518
519 if (!candidates.empty()) {
520 SignalCandidatesReady(this, candidates);
521 }
522}
523
524bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) {
525 uint32 filter = allocator_->candidate_filter();
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000526
527 // When binding to any address, before sending packets out, the getsockname
528 // returns all 0s, but after sending packets, it'll be the NIC used to
529 // send. All 0s is not a valid ICE candidate address and should be filtered
530 // out.
531 if (c.address().IsAnyIP()) {
532 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000533 }
534
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000535 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000536 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000537 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000538 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000539 } else if (c.type() == LOCAL_PORT_TYPE) {
540 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
541 // We allow host candidates if the filter allows server-reflexive
542 // candidates and the candidate is a public IP. Because we don't generate
543 // server-reflexive candidates if they have the same IP as the host
544 // candidate (i.e. when the host candidate is a public IP), filtering to
545 // only server-reflexive candidates won't work right when the host
546 // candidates have public IPs.
547 return true;
548 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000550 // This is just to prevent the case when binding to any address (all 0s), if
551 // somehow the host candidate address is not all 0s. Either because local
552 // installed proxy changes the address or a packet has been sent for any
553 // reason before getsockname is called.
554 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
555 LOG(LS_WARNING) << "Received non-0 host address: "
556 << c.address().ToString()
557 << " when adapter enumeration is disabled";
558 return false;
559 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000561 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000562 }
563 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000564}
565
566void BasicPortAllocatorSession::OnPortAllocationComplete(
567 AllocationSequence* seq) {
568 // Send candidate allocation complete signal if all ports are done.
569 MaybeSignalCandidatesAllocationDone();
570}
571
572void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
573 // Send signal only if all required AllocationSequence objects
574 // are created.
575 if (!allocation_sequences_created_)
576 return;
577
578 // Check that all port allocation sequences are complete.
579 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
580 it != sequences_.end(); ++it) {
581 if ((*it)->state() == AllocationSequence::kRunning)
582 return;
583 }
584
585 // If all allocated ports are in complete state, session must have got all
586 // expected candidates. Session will trigger candidates allocation complete
587 // signal.
588 for (std::vector<PortData>::iterator it = ports_.begin();
589 it != ports_.end(); ++it) {
590 if (!it->complete())
591 return;
592 }
593 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
594 << component_ << ":" << generation();
595 SignalCandidatesAllocationDone(this);
596}
597
598void BasicPortAllocatorSession::OnPortDestroyed(
599 PortInterface* port) {
600 ASSERT(rtc::Thread::Current() == network_thread_);
601 for (std::vector<PortData>::iterator iter = ports_.begin();
602 iter != ports_.end(); ++iter) {
603 if (port == iter->port()) {
604 ports_.erase(iter);
605 LOG_J(LS_INFO, port) << "Removed port from allocator ("
606 << static_cast<int>(ports_.size()) << " remaining)";
607 return;
608 }
609 }
610 ASSERT(false);
611}
612
613void BasicPortAllocatorSession::OnShake() {
614 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
615
616 std::vector<Port*> ports;
617 std::vector<Connection*> connections;
618
619 for (size_t i = 0; i < ports_.size(); ++i) {
620 if (ports_[i].ready())
621 ports.push_back(ports_[i].port());
622 }
623
624 for (size_t i = 0; i < ports.size(); ++i) {
625 Port::AddressMap::const_iterator iter;
626 for (iter = ports[i]->connections().begin();
627 iter != ports[i]->connections().end();
628 ++iter) {
629 connections.push_back(iter->second);
630 }
631 }
632
633 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
634 << connections.size() << " connections";
635
636 for (size_t i = 0; i < connections.size(); ++i)
637 connections[i]->Destroy();
638
639 if (running_ || (ports.size() > 0) || (connections.size() > 0))
640 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
641}
642
643BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
644 Port* port) {
645 for (std::vector<PortData>::iterator it = ports_.begin();
646 it != ports_.end(); ++it) {
647 if (it->port() == port) {
648 return &*it;
649 }
650 }
651 return NULL;
652}
653
654// AllocationSequence
655
656AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
657 rtc::Network* network,
658 PortConfiguration* config,
659 uint32 flags)
660 : session_(session),
661 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663 config_(config),
664 state_(kInit),
665 flags_(flags),
666 udp_socket_(),
667 udp_port_(NULL),
668 phase_(0) {
669}
670
671bool AllocationSequence::Init() {
pthatcherfa301802015-08-11 04:12:56 -0700672 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
673 !IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_UFRAG)) {
674 LOG(LS_ERROR) << "Shared socket option can't be set without "
675 << "shared ufrag.";
676 ASSERT(false);
677 return false;
678 }
679
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
681 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
682 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
683 session_->allocator()->max_port()));
684 if (udp_socket_) {
685 udp_socket_->SignalReadPacket.connect(
686 this, &AllocationSequence::OnReadPacket);
687 }
688 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
689 // are next available options to setup a communication channel.
690 }
691 return true;
692}
693
694void AllocationSequence::Clear() {
695 udp_port_ = NULL;
696 turn_ports_.clear();
697}
698
699AllocationSequence::~AllocationSequence() {
700 session_->network_thread()->Clear(this);
701}
702
703void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
704 PortConfiguration* config, uint32* flags) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000706 // Different network setup; nothing is equivalent.
707 return;
708 }
709
710 // Else turn off the stuff that we've already got covered.
711
712 // Every config implicitly specifies local, so turn that off right away.
713 *flags |= PORTALLOCATOR_DISABLE_UDP;
714 *flags |= PORTALLOCATOR_DISABLE_TCP;
715
716 if (config_ && config) {
717 if (config_->StunServers() == config->StunServers()) {
718 // Already got this STUN servers covered.
719 *flags |= PORTALLOCATOR_DISABLE_STUN;
720 }
721 if (!config_->relays.empty()) {
722 // Already got relays covered.
723 // NOTE: This will even skip a _different_ set of relay servers if we
724 // were to be given one, but that never happens in our codebase. Should
725 // probably get rid of the list in PortConfiguration and just keep a
726 // single relay server in each one.
727 *flags |= PORTALLOCATOR_DISABLE_RELAY;
728 }
729 }
730}
731
732void AllocationSequence::Start() {
733 state_ = kRunning;
734 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
735}
736
737void AllocationSequence::Stop() {
738 // If the port is completed, don't set it to stopped.
739 if (state_ == kRunning) {
740 state_ = kStopped;
741 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
742 }
743}
744
745void AllocationSequence::OnMessage(rtc::Message* msg) {
746 ASSERT(rtc::Thread::Current() == session_->network_thread());
747 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
748
749 const char* const PHASE_NAMES[kNumPhases] = {
750 "Udp", "Relay", "Tcp", "SslTcp"
751 };
752
753 // Perform all of the phases in the current step.
754 LOG_J(LS_INFO, network_) << "Allocation Phase="
755 << PHASE_NAMES[phase_];
756
757 switch (phase_) {
758 case PHASE_UDP:
759 CreateUDPPorts();
760 CreateStunPorts();
761 EnableProtocol(PROTO_UDP);
762 break;
763
764 case PHASE_RELAY:
765 CreateRelayPorts();
766 break;
767
768 case PHASE_TCP:
769 CreateTCPPorts();
770 EnableProtocol(PROTO_TCP);
771 break;
772
773 case PHASE_SSLTCP:
774 state_ = kCompleted;
775 EnableProtocol(PROTO_SSLTCP);
776 break;
777
778 default:
779 ASSERT(false);
780 }
781
782 if (state() == kRunning) {
783 ++phase_;
784 session_->network_thread()->PostDelayed(
785 session_->allocator()->step_delay(),
786 this, MSG_ALLOCATION_PHASE);
787 } else {
788 // If all phases in AllocationSequence are completed, no allocation
789 // steps needed further. Canceling pending signal.
790 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
791 SignalPortAllocationComplete(this);
792 }
793}
794
795void AllocationSequence::EnableProtocol(ProtocolType proto) {
796 if (!ProtocolEnabled(proto)) {
797 protocols_.push_back(proto);
798 session_->OnProtocolEnabled(this, proto);
799 }
800}
801
802bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
803 for (ProtocolList::const_iterator it = protocols_.begin();
804 it != protocols_.end(); ++it) {
805 if (*it == proto)
806 return true;
807 }
808 return false;
809}
810
811void AllocationSequence::CreateUDPPorts() {
812 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
813 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
814 return;
815 }
816
817 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
818 // is enabled completely.
819 UDPPort* port = NULL;
820 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
821 port = UDPPort::Create(session_->network_thread(),
822 session_->socket_factory(), network_,
823 udp_socket_.get(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000824 session_->username(), session_->password(),
825 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000826 } else {
827 port = UDPPort::Create(session_->network_thread(),
828 session_->socket_factory(),
829 network_, ip_,
830 session_->allocator()->min_port(),
831 session_->allocator()->max_port(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000832 session_->username(), session_->password(),
833 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834 }
835
836 if (port) {
837 // If shared socket is enabled, STUN candidate will be allocated by the
838 // UDPPort.
839 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
840 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000841 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842
843 // If STUN is not disabled, setting stun server address to port.
844 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 if (config_ && !config_->StunServers().empty()) {
846 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
847 << "STUN candidate generation.";
848 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000849 }
850 }
851 }
852
853 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854 }
855}
856
857void AllocationSequence::CreateTCPPorts() {
858 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
859 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
860 return;
861 }
862
863 Port* port = TCPPort::Create(session_->network_thread(),
864 session_->socket_factory(),
865 network_, ip_,
866 session_->allocator()->min_port(),
867 session_->allocator()->max_port(),
868 session_->username(), session_->password(),
869 session_->allocator()->allow_tcp_listen());
870 if (port) {
871 session_->AddAllocatedPort(port, this, true);
872 // Since TCPPort is not created using shared socket, |port| will not be
873 // added to the dequeue.
874 }
875}
876
877void AllocationSequence::CreateStunPorts() {
878 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
879 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
880 return;
881 }
882
883 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
884 return;
885 }
886
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 if (!(config_ && !config_->StunServers().empty())) {
888 LOG(LS_WARNING)
889 << "AllocationSequence: No STUN server configured, skipping.";
890 return;
891 }
892
893 StunPort* port = StunPort::Create(session_->network_thread(),
894 session_->socket_factory(),
895 network_, ip_,
896 session_->allocator()->min_port(),
897 session_->allocator()->max_port(),
898 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000899 config_->StunServers(),
900 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000901 if (port) {
902 session_->AddAllocatedPort(port, this, true);
903 // Since StunPort is not created using shared socket, |port| will not be
904 // added to the dequeue.
905 }
906}
907
908void AllocationSequence::CreateRelayPorts() {
909 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
910 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
911 return;
912 }
913
914 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
915 // ought to have a relay list for them here.
916 ASSERT(config_ && !config_->relays.empty());
917 if (!(config_ && !config_->relays.empty())) {
918 LOG(LS_WARNING)
919 << "AllocationSequence: No relay server configured, skipping.";
920 return;
921 }
922
923 PortConfiguration::RelayList::const_iterator relay;
924 for (relay = config_->relays.begin();
925 relay != config_->relays.end(); ++relay) {
926 if (relay->type == RELAY_GTURN) {
927 CreateGturnPort(*relay);
928 } else if (relay->type == RELAY_TURN) {
929 CreateTurnPort(*relay);
930 } else {
931 ASSERT(false);
932 }
933 }
934}
935
936void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
937 // TODO(mallinath) - Rename RelayPort to GTurnPort.
938 RelayPort* port = RelayPort::Create(session_->network_thread(),
939 session_->socket_factory(),
940 network_, ip_,
941 session_->allocator()->min_port(),
942 session_->allocator()->max_port(),
943 config_->username, config_->password);
944 if (port) {
945 // Since RelayPort is not created using shared socket, |port| will not be
946 // added to the dequeue.
947 // Note: We must add the allocated port before we add addresses because
948 // the latter will create candidates that need name and preference
949 // settings. However, we also can't prepare the address (normally
950 // done by AddAllocatedPort) until we have these addresses. So we
951 // wait to do that until below.
952 session_->AddAllocatedPort(port, this, false);
953
954 // Add the addresses of this protocol.
955 PortList::const_iterator relay_port;
956 for (relay_port = config.ports.begin();
957 relay_port != config.ports.end();
958 ++relay_port) {
959 port->AddServerAddress(*relay_port);
960 port->AddExternalAddress(*relay_port);
961 }
962 // Start fetching an address for this port.
963 port->PrepareAddress();
964 }
965}
966
967void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
968 PortList::const_iterator relay_port;
969 for (relay_port = config.ports.begin();
970 relay_port != config.ports.end(); ++relay_port) {
971 TurnPort* port = NULL;
972 // Shared socket mode must be enabled only for UDP based ports. Hence
973 // don't pass shared socket for ports which will create TCP sockets.
974 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
975 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
976 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -0700977 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000978 port = TurnPort::Create(session_->network_thread(),
979 session_->socket_factory(),
980 network_, udp_socket_.get(),
981 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000982 *relay_port, config.credentials, config.priority,
983 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000984 turn_ports_.push_back(port);
985 // Listen to the port destroyed signal, to allow AllocationSequence to
986 // remove entrt from it's map.
987 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
988 } else {
989 port = TurnPort::Create(session_->network_thread(),
990 session_->socket_factory(),
991 network_, ip_,
992 session_->allocator()->min_port(),
993 session_->allocator()->max_port(),
994 session_->username(),
995 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000996 *relay_port, config.credentials, config.priority,
997 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000998 }
999 ASSERT(port != NULL);
1000 session_->AddAllocatedPort(port, this, true);
1001 }
1002}
1003
1004void AllocationSequence::OnReadPacket(
1005 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1006 const rtc::SocketAddress& remote_addr,
1007 const rtc::PacketTime& packet_time) {
1008 ASSERT(socket == udp_socket_.get());
1009
1010 bool turn_port_found = false;
1011
1012 // Try to find the TurnPort that matches the remote address. Note that the
1013 // message could be a STUN binding response if the TURN server is also used as
1014 // a STUN server. We don't want to parse every message here to check if it is
1015 // a STUN binding response, so we pass the message to TurnPort regardless of
1016 // the message type. The TurnPort will just ignore the message since it will
1017 // not find any request by transaction ID.
1018 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1019 it != turn_ports_.end(); ++it) {
1020 TurnPort* port = *it;
1021 if (port->server_address().address == remote_addr) {
1022 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1023 turn_port_found = true;
1024 break;
1025 }
1026 }
1027
1028 if (udp_port_) {
1029 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1030
1031 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1032 // the TURN server is also a STUN server.
1033 if (!turn_port_found ||
1034 stun_servers.find(remote_addr) != stun_servers.end()) {
1035 udp_port_->HandleIncomingPacket(
1036 socket, data, size, remote_addr, packet_time);
1037 }
1038 }
1039}
1040
1041void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1042 if (udp_port_ == port) {
1043 udp_port_ = NULL;
1044 return;
1045 }
1046
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001047 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1048 if (it != turn_ports_.end()) {
1049 turn_ports_.erase(it);
1050 } else {
1051 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1052 ASSERT(false);
1053 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001054}
1055
1056// PortConfiguration
1057PortConfiguration::PortConfiguration(
1058 const rtc::SocketAddress& stun_address,
1059 const std::string& username,
1060 const std::string& password)
1061 : stun_address(stun_address), username(username), password(password) {
1062 if (!stun_address.IsNil())
1063 stun_servers.insert(stun_address);
1064}
1065
1066PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1067 const std::string& username,
1068 const std::string& password)
1069 : stun_servers(stun_servers),
1070 username(username),
1071 password(password) {
1072 if (!stun_servers.empty())
1073 stun_address = *(stun_servers.begin());
1074}
1075
1076ServerAddresses PortConfiguration::StunServers() {
1077 if (!stun_address.IsNil() &&
1078 stun_servers.find(stun_address) == stun_servers.end()) {
1079 stun_servers.insert(stun_address);
1080 }
deadbeefc5d0d952015-07-16 10:22:21 -07001081 // Every UDP TURN server should also be used as a STUN server.
1082 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1083 for (const rtc::SocketAddress& turn_server : turn_servers) {
1084 if (stun_servers.find(turn_server) == stun_servers.end()) {
1085 stun_servers.insert(turn_server);
1086 }
1087 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001088 return stun_servers;
1089}
1090
1091void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1092 relays.push_back(config);
1093}
1094
1095bool PortConfiguration::SupportsProtocol(
1096 const RelayServerConfig& relay, ProtocolType type) const {
1097 PortList::const_iterator relay_port;
1098 for (relay_port = relay.ports.begin();
1099 relay_port != relay.ports.end();
1100 ++relay_port) {
1101 if (relay_port->proto == type)
1102 return true;
1103 }
1104 return false;
1105}
1106
1107bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1108 ProtocolType type) const {
1109 for (size_t i = 0; i < relays.size(); ++i) {
1110 if (relays[i].type == turn_type &&
1111 SupportsProtocol(relays[i], type))
1112 return true;
1113 }
1114 return false;
1115}
1116
1117ServerAddresses PortConfiguration::GetRelayServerAddresses(
1118 RelayType turn_type, ProtocolType type) const {
1119 ServerAddresses servers;
1120 for (size_t i = 0; i < relays.size(); ++i) {
1121 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1122 servers.insert(relays[i].ports.front().address);
1123 }
1124 }
1125 return servers;
1126}
1127
1128} // namespace cricket