blob: 05a90e185c1cc6b895984777d9a16492cd9dee74 [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() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000672 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
673 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
674 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
675 session_->allocator()->max_port()));
676 if (udp_socket_) {
677 udp_socket_->SignalReadPacket.connect(
678 this, &AllocationSequence::OnReadPacket);
679 }
680 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
681 // are next available options to setup a communication channel.
682 }
683 return true;
684}
685
686void AllocationSequence::Clear() {
687 udp_port_ = NULL;
688 turn_ports_.clear();
689}
690
691AllocationSequence::~AllocationSequence() {
692 session_->network_thread()->Clear(this);
693}
694
695void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
696 PortConfiguration* config, uint32* flags) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000697 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000698 // Different network setup; nothing is equivalent.
699 return;
700 }
701
702 // Else turn off the stuff that we've already got covered.
703
704 // Every config implicitly specifies local, so turn that off right away.
705 *flags |= PORTALLOCATOR_DISABLE_UDP;
706 *flags |= PORTALLOCATOR_DISABLE_TCP;
707
708 if (config_ && config) {
709 if (config_->StunServers() == config->StunServers()) {
710 // Already got this STUN servers covered.
711 *flags |= PORTALLOCATOR_DISABLE_STUN;
712 }
713 if (!config_->relays.empty()) {
714 // Already got relays covered.
715 // NOTE: This will even skip a _different_ set of relay servers if we
716 // were to be given one, but that never happens in our codebase. Should
717 // probably get rid of the list in PortConfiguration and just keep a
718 // single relay server in each one.
719 *flags |= PORTALLOCATOR_DISABLE_RELAY;
720 }
721 }
722}
723
724void AllocationSequence::Start() {
725 state_ = kRunning;
726 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
727}
728
729void AllocationSequence::Stop() {
730 // If the port is completed, don't set it to stopped.
731 if (state_ == kRunning) {
732 state_ = kStopped;
733 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
734 }
735}
736
737void AllocationSequence::OnMessage(rtc::Message* msg) {
738 ASSERT(rtc::Thread::Current() == session_->network_thread());
739 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
740
741 const char* const PHASE_NAMES[kNumPhases] = {
742 "Udp", "Relay", "Tcp", "SslTcp"
743 };
744
745 // Perform all of the phases in the current step.
746 LOG_J(LS_INFO, network_) << "Allocation Phase="
747 << PHASE_NAMES[phase_];
748
749 switch (phase_) {
750 case PHASE_UDP:
751 CreateUDPPorts();
752 CreateStunPorts();
753 EnableProtocol(PROTO_UDP);
754 break;
755
756 case PHASE_RELAY:
757 CreateRelayPorts();
758 break;
759
760 case PHASE_TCP:
761 CreateTCPPorts();
762 EnableProtocol(PROTO_TCP);
763 break;
764
765 case PHASE_SSLTCP:
766 state_ = kCompleted;
767 EnableProtocol(PROTO_SSLTCP);
768 break;
769
770 default:
771 ASSERT(false);
772 }
773
774 if (state() == kRunning) {
775 ++phase_;
776 session_->network_thread()->PostDelayed(
777 session_->allocator()->step_delay(),
778 this, MSG_ALLOCATION_PHASE);
779 } else {
780 // If all phases in AllocationSequence are completed, no allocation
781 // steps needed further. Canceling pending signal.
782 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
783 SignalPortAllocationComplete(this);
784 }
785}
786
787void AllocationSequence::EnableProtocol(ProtocolType proto) {
788 if (!ProtocolEnabled(proto)) {
789 protocols_.push_back(proto);
790 session_->OnProtocolEnabled(this, proto);
791 }
792}
793
794bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
795 for (ProtocolList::const_iterator it = protocols_.begin();
796 it != protocols_.end(); ++it) {
797 if (*it == proto)
798 return true;
799 }
800 return false;
801}
802
803void AllocationSequence::CreateUDPPorts() {
804 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
805 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
806 return;
807 }
808
809 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
810 // is enabled completely.
811 UDPPort* port = NULL;
812 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
813 port = UDPPort::Create(session_->network_thread(),
814 session_->socket_factory(), network_,
815 udp_socket_.get(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000816 session_->username(), session_->password(),
817 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 } else {
819 port = UDPPort::Create(session_->network_thread(),
820 session_->socket_factory(),
821 network_, ip_,
822 session_->allocator()->min_port(),
823 session_->allocator()->max_port(),
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 }
827
828 if (port) {
829 // If shared socket is enabled, STUN candidate will be allocated by the
830 // UDPPort.
831 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
832 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000833 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834
835 // If STUN is not disabled, setting stun server address to port.
836 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837 if (config_ && !config_->StunServers().empty()) {
838 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
839 << "STUN candidate generation.";
840 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 }
842 }
843 }
844
845 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 }
847}
848
849void AllocationSequence::CreateTCPPorts() {
850 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
851 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
852 return;
853 }
854
855 Port* port = TCPPort::Create(session_->network_thread(),
856 session_->socket_factory(),
857 network_, ip_,
858 session_->allocator()->min_port(),
859 session_->allocator()->max_port(),
860 session_->username(), session_->password(),
861 session_->allocator()->allow_tcp_listen());
862 if (port) {
863 session_->AddAllocatedPort(port, this, true);
864 // Since TCPPort is not created using shared socket, |port| will not be
865 // added to the dequeue.
866 }
867}
868
869void AllocationSequence::CreateStunPorts() {
870 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
871 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
872 return;
873 }
874
875 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
876 return;
877 }
878
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000879 if (!(config_ && !config_->StunServers().empty())) {
880 LOG(LS_WARNING)
881 << "AllocationSequence: No STUN server configured, skipping.";
882 return;
883 }
884
885 StunPort* port = StunPort::Create(session_->network_thread(),
886 session_->socket_factory(),
887 network_, ip_,
888 session_->allocator()->min_port(),
889 session_->allocator()->max_port(),
890 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000891 config_->StunServers(),
892 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000893 if (port) {
894 session_->AddAllocatedPort(port, this, true);
895 // Since StunPort is not created using shared socket, |port| will not be
896 // added to the dequeue.
897 }
898}
899
900void AllocationSequence::CreateRelayPorts() {
901 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
902 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
903 return;
904 }
905
906 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
907 // ought to have a relay list for them here.
908 ASSERT(config_ && !config_->relays.empty());
909 if (!(config_ && !config_->relays.empty())) {
910 LOG(LS_WARNING)
911 << "AllocationSequence: No relay server configured, skipping.";
912 return;
913 }
914
915 PortConfiguration::RelayList::const_iterator relay;
916 for (relay = config_->relays.begin();
917 relay != config_->relays.end(); ++relay) {
918 if (relay->type == RELAY_GTURN) {
919 CreateGturnPort(*relay);
920 } else if (relay->type == RELAY_TURN) {
921 CreateTurnPort(*relay);
922 } else {
923 ASSERT(false);
924 }
925 }
926}
927
928void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
929 // TODO(mallinath) - Rename RelayPort to GTurnPort.
930 RelayPort* port = RelayPort::Create(session_->network_thread(),
931 session_->socket_factory(),
932 network_, ip_,
933 session_->allocator()->min_port(),
934 session_->allocator()->max_port(),
935 config_->username, config_->password);
936 if (port) {
937 // Since RelayPort is not created using shared socket, |port| will not be
938 // added to the dequeue.
939 // Note: We must add the allocated port before we add addresses because
940 // the latter will create candidates that need name and preference
941 // settings. However, we also can't prepare the address (normally
942 // done by AddAllocatedPort) until we have these addresses. So we
943 // wait to do that until below.
944 session_->AddAllocatedPort(port, this, false);
945
946 // Add the addresses of this protocol.
947 PortList::const_iterator relay_port;
948 for (relay_port = config.ports.begin();
949 relay_port != config.ports.end();
950 ++relay_port) {
951 port->AddServerAddress(*relay_port);
952 port->AddExternalAddress(*relay_port);
953 }
954 // Start fetching an address for this port.
955 port->PrepareAddress();
956 }
957}
958
959void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
960 PortList::const_iterator relay_port;
961 for (relay_port = config.ports.begin();
962 relay_port != config.ports.end(); ++relay_port) {
963 TurnPort* port = NULL;
964 // Shared socket mode must be enabled only for UDP based ports. Hence
965 // don't pass shared socket for ports which will create TCP sockets.
966 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
967 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
968 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -0700969 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 port = TurnPort::Create(session_->network_thread(),
971 session_->socket_factory(),
972 network_, udp_socket_.get(),
973 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000974 *relay_port, config.credentials, config.priority,
975 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000976 turn_ports_.push_back(port);
977 // Listen to the port destroyed signal, to allow AllocationSequence to
978 // remove entrt from it's map.
979 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
980 } else {
981 port = TurnPort::Create(session_->network_thread(),
982 session_->socket_factory(),
983 network_, ip_,
984 session_->allocator()->min_port(),
985 session_->allocator()->max_port(),
986 session_->username(),
987 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000988 *relay_port, config.credentials, config.priority,
989 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000990 }
991 ASSERT(port != NULL);
992 session_->AddAllocatedPort(port, this, true);
993 }
994}
995
996void AllocationSequence::OnReadPacket(
997 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
998 const rtc::SocketAddress& remote_addr,
999 const rtc::PacketTime& packet_time) {
1000 ASSERT(socket == udp_socket_.get());
1001
1002 bool turn_port_found = false;
1003
1004 // Try to find the TurnPort that matches the remote address. Note that the
1005 // message could be a STUN binding response if the TURN server is also used as
1006 // a STUN server. We don't want to parse every message here to check if it is
1007 // a STUN binding response, so we pass the message to TurnPort regardless of
1008 // the message type. The TurnPort will just ignore the message since it will
1009 // not find any request by transaction ID.
1010 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1011 it != turn_ports_.end(); ++it) {
1012 TurnPort* port = *it;
1013 if (port->server_address().address == remote_addr) {
1014 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1015 turn_port_found = true;
1016 break;
1017 }
1018 }
1019
1020 if (udp_port_) {
1021 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1022
1023 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1024 // the TURN server is also a STUN server.
1025 if (!turn_port_found ||
1026 stun_servers.find(remote_addr) != stun_servers.end()) {
1027 udp_port_->HandleIncomingPacket(
1028 socket, data, size, remote_addr, packet_time);
1029 }
1030 }
1031}
1032
1033void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1034 if (udp_port_ == port) {
1035 udp_port_ = NULL;
1036 return;
1037 }
1038
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001039 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1040 if (it != turn_ports_.end()) {
1041 turn_ports_.erase(it);
1042 } else {
1043 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1044 ASSERT(false);
1045 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046}
1047
1048// PortConfiguration
1049PortConfiguration::PortConfiguration(
1050 const rtc::SocketAddress& stun_address,
1051 const std::string& username,
1052 const std::string& password)
1053 : stun_address(stun_address), username(username), password(password) {
1054 if (!stun_address.IsNil())
1055 stun_servers.insert(stun_address);
1056}
1057
1058PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1059 const std::string& username,
1060 const std::string& password)
1061 : stun_servers(stun_servers),
1062 username(username),
1063 password(password) {
1064 if (!stun_servers.empty())
1065 stun_address = *(stun_servers.begin());
1066}
1067
1068ServerAddresses PortConfiguration::StunServers() {
1069 if (!stun_address.IsNil() &&
1070 stun_servers.find(stun_address) == stun_servers.end()) {
1071 stun_servers.insert(stun_address);
1072 }
deadbeefc5d0d952015-07-16 10:22:21 -07001073 // Every UDP TURN server should also be used as a STUN server.
1074 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1075 for (const rtc::SocketAddress& turn_server : turn_servers) {
1076 if (stun_servers.find(turn_server) == stun_servers.end()) {
1077 stun_servers.insert(turn_server);
1078 }
1079 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080 return stun_servers;
1081}
1082
1083void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1084 relays.push_back(config);
1085}
1086
1087bool PortConfiguration::SupportsProtocol(
1088 const RelayServerConfig& relay, ProtocolType type) const {
1089 PortList::const_iterator relay_port;
1090 for (relay_port = relay.ports.begin();
1091 relay_port != relay.ports.end();
1092 ++relay_port) {
1093 if (relay_port->proto == type)
1094 return true;
1095 }
1096 return false;
1097}
1098
1099bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1100 ProtocolType type) const {
1101 for (size_t i = 0; i < relays.size(); ++i) {
1102 if (relays[i].type == turn_type &&
1103 SupportsProtocol(relays[i], type))
1104 return true;
1105 }
1106 return false;
1107}
1108
1109ServerAddresses PortConfiguration::GetRelayServerAddresses(
1110 RelayType turn_type, ProtocolType type) const {
1111 ServerAddresses servers;
1112 for (size_t i = 0; i < relays.size(); ++i) {
1113 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1114 servers.insert(relays[i].ports.front().address);
1115 }
1116 }
1117 return servers;
1118}
1119
1120} // namespace cricket