blob: dbc2e3342eecb244081bd5020bbaefd1b03b3656 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004--2005, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "talk/p2p/client/basicportallocator.h"
29
30#include <string>
31#include <vector>
32
33#include "talk/base/common.h"
34#include "talk/base/helpers.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000035#include "talk/base/logging.h"
36#include "talk/p2p/base/basicpacketsocketfactory.h"
37#include "talk/p2p/base/common.h"
38#include "talk/p2p/base/port.h"
39#include "talk/p2p/base/relayport.h"
40#include "talk/p2p/base/stunport.h"
41#include "talk/p2p/base/tcpport.h"
42#include "talk/p2p/base/turnport.h"
43#include "talk/p2p/base/udpport.h"
44
45using talk_base::CreateRandomId;
46using talk_base::CreateRandomString;
47
48namespace {
49
50const uint32 MSG_CONFIG_START = 1;
51const uint32 MSG_CONFIG_READY = 2;
52const uint32 MSG_ALLOCATE = 3;
53const uint32 MSG_ALLOCATION_PHASE = 4;
54const uint32 MSG_SHAKE = 5;
55const uint32 MSG_SEQUENCEOBJECTS_CREATED = 6;
56const uint32 MSG_CONFIG_STOP = 7;
57
58const uint32 ALLOCATE_DELAY = 250;
59const uint32 ALLOCATION_STEP_DELAY = 1 * 1000;
60
61const int PHASE_UDP = 0;
62const int PHASE_RELAY = 1;
63const int PHASE_TCP = 2;
64const int PHASE_SSLTCP = 3;
65
66const int kNumPhases = 4;
67
68// Both these values are in bytes.
69const int kLargeSocketSendBufferSize = 128 * 1024;
70const int kNormalSocketSendBufferSize = 64 * 1024;
71
72const int SHAKE_MIN_DELAY = 45 * 1000; // 45 seconds
73const int SHAKE_MAX_DELAY = 90 * 1000; // 90 seconds
74
75int ShakeDelay() {
76 int range = SHAKE_MAX_DELAY - SHAKE_MIN_DELAY + 1;
77 return SHAKE_MIN_DELAY + CreateRandomId() % range;
78}
79
80} // namespace
81
82namespace cricket {
83
84const uint32 DISABLE_ALL_PHASES =
85 PORTALLOCATOR_DISABLE_UDP
86 | PORTALLOCATOR_DISABLE_TCP
87 | PORTALLOCATOR_DISABLE_STUN
88 | PORTALLOCATOR_DISABLE_RELAY;
89
90// Performs the allocation of ports, in a sequenced (timed) manner, for a given
91// network and IP address.
92class AllocationSequence : public talk_base::MessageHandler,
93 public sigslot::has_slots<> {
94 public:
95 enum State {
96 kInit, // Initial state.
97 kRunning, // Started allocating ports.
98 kStopped, // Stopped from running.
99 kCompleted, // All ports are allocated.
100
101 // kInit --> kRunning --> {kCompleted|kStopped}
102 };
103
104 AllocationSequence(BasicPortAllocatorSession* session,
105 talk_base::Network* network,
106 PortConfiguration* config,
107 uint32 flags);
108 ~AllocationSequence();
109 bool Init();
110
111 State state() const { return state_; }
112
113 // Disables the phases for a new sequence that this one already covers for an
114 // equivalent network setup.
115 void DisableEquivalentPhases(talk_base::Network* network,
116 PortConfiguration* config, uint32* flags);
117
118 // Starts and stops the sequence. When started, it will continue allocating
119 // new ports on its own timed schedule.
120 void Start();
121 void Stop();
122
123 // MessageHandler
124 void OnMessage(talk_base::Message* msg);
125
126 void EnableProtocol(ProtocolType proto);
127 bool ProtocolEnabled(ProtocolType proto) const;
128
129 // Signal from AllocationSequence, when it's done with allocating ports.
130 // This signal is useful, when port allocation fails which doesn't result
131 // in any candidates. Using this signal BasicPortAllocatorSession can send
132 // its candidate discovery conclusion signal. Without this signal,
133 // BasicPortAllocatorSession doesn't have any event to trigger signal. This
134 // can also be achieved by starting timer in BPAS.
135 sigslot::signal1<AllocationSequence*> SignalPortAllocationComplete;
136
137 private:
138 typedef std::vector<ProtocolType> ProtocolList;
139
140 bool IsFlagSet(uint32 flag) {
141 return ((flags_ & flag) != 0);
142 }
143 void CreateUDPPorts();
144 void CreateTCPPorts();
145 void CreateStunPorts();
146 void CreateRelayPorts();
147 void CreateGturnPort(const RelayServerConfig& config);
148 void CreateTurnPort(const RelayServerConfig& config);
149
150 void OnReadPacket(talk_base::AsyncPacketSocket* socket,
151 const char* data, size_t size,
wu@webrtc.orga9890802013-12-13 00:21:03 +0000152 const talk_base::SocketAddress& remote_addr,
153 const talk_base::PacketTime& packet_time);
154
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000155 void OnPortDestroyed(PortInterface* port);
156
157 BasicPortAllocatorSession* session_;
158 talk_base::Network* network_;
159 talk_base::IPAddress ip_;
160 PortConfiguration* config_;
161 State state_;
162 uint32 flags_;
163 ProtocolList protocols_;
164 talk_base::scoped_ptr<talk_base::AsyncPacketSocket> udp_socket_;
165 // Keeping a list of all UDP based ports.
166 std::deque<Port*> ports;
167 int phase_;
168};
169
170// BasicPortAllocator
171BasicPortAllocator::BasicPortAllocator(
172 talk_base::NetworkManager* network_manager,
173 talk_base::PacketSocketFactory* socket_factory)
174 : network_manager_(network_manager),
175 socket_factory_(socket_factory) {
176 ASSERT(socket_factory_ != NULL);
177 Construct();
178}
179
180BasicPortAllocator::BasicPortAllocator(
181 talk_base::NetworkManager* network_manager)
182 : network_manager_(network_manager),
183 socket_factory_(NULL) {
184 Construct();
185}
186
187BasicPortAllocator::BasicPortAllocator(
188 talk_base::NetworkManager* network_manager,
189 talk_base::PacketSocketFactory* socket_factory,
190 const talk_base::SocketAddress& stun_address)
191 : network_manager_(network_manager),
192 socket_factory_(socket_factory),
193 stun_address_(stun_address) {
194 ASSERT(socket_factory_ != NULL);
195 Construct();
196}
197
198BasicPortAllocator::BasicPortAllocator(
199 talk_base::NetworkManager* network_manager,
200 const talk_base::SocketAddress& stun_address,
201 const talk_base::SocketAddress& relay_address_udp,
202 const talk_base::SocketAddress& relay_address_tcp,
203 const talk_base::SocketAddress& relay_address_ssl)
204 : network_manager_(network_manager),
205 socket_factory_(NULL),
206 stun_address_(stun_address) {
207
208 RelayServerConfig config(RELAY_GTURN);
209 if (!relay_address_udp.IsAny())
210 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
211 if (!relay_address_tcp.IsAny())
212 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
213 if (!relay_address_ssl.IsAny())
214 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
215 AddRelay(config);
216
217 Construct();
218}
219
220void BasicPortAllocator::Construct() {
221 allow_tcp_listen_ = true;
222}
223
224BasicPortAllocator::~BasicPortAllocator() {
225}
226
227PortAllocatorSession *BasicPortAllocator::CreateSessionInternal(
228 const std::string& content_name, int component,
229 const std::string& ice_ufrag, const std::string& ice_pwd) {
230 return new BasicPortAllocatorSession(this, content_name, component,
231 ice_ufrag, ice_pwd);
232}
233
234// BasicPortAllocatorSession
235BasicPortAllocatorSession::BasicPortAllocatorSession(
236 BasicPortAllocator *allocator,
237 const std::string& content_name,
238 int component,
239 const std::string& ice_ufrag,
240 const std::string& ice_pwd)
241 : PortAllocatorSession(content_name, component,
242 ice_ufrag, ice_pwd, allocator->flags()),
243 allocator_(allocator), network_thread_(NULL),
244 socket_factory_(allocator->socket_factory()),
245 configuration_done_(false),
246 allocation_started_(false),
247 network_manager_started_(false),
248 running_(false),
249 allocation_sequences_created_(false) {
250 allocator_->network_manager()->SignalNetworksChanged.connect(
251 this, &BasicPortAllocatorSession::OnNetworksChanged);
252 allocator_->network_manager()->StartUpdating();
253}
254
255BasicPortAllocatorSession::~BasicPortAllocatorSession() {
256 allocator_->network_manager()->StopUpdating();
257 if (network_thread_ != NULL)
258 network_thread_->Clear(this);
259
260 std::vector<PortData>::iterator it;
261 for (it = ports_.begin(); it != ports_.end(); it++)
262 delete it->port();
263
264 for (uint32 i = 0; i < configs_.size(); ++i)
265 delete configs_[i];
266
267 for (uint32 i = 0; i < sequences_.size(); ++i)
268 delete sequences_[i];
269}
270
271void BasicPortAllocatorSession::StartGettingPorts() {
272 network_thread_ = talk_base::Thread::Current();
273 if (!socket_factory_) {
274 owned_socket_factory_.reset(
275 new talk_base::BasicPacketSocketFactory(network_thread_));
276 socket_factory_ = owned_socket_factory_.get();
277 }
278
279 running_ = true;
280 network_thread_->Post(this, MSG_CONFIG_START);
281
282 if (flags() & PORTALLOCATOR_ENABLE_SHAKER)
283 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
284}
285
286void BasicPortAllocatorSession::StopGettingPorts() {
287 ASSERT(talk_base::Thread::Current() == network_thread_);
288 running_ = false;
289 network_thread_->Clear(this, MSG_ALLOCATE);
290 for (uint32 i = 0; i < sequences_.size(); ++i)
291 sequences_[i]->Stop();
292 network_thread_->Post(this, MSG_CONFIG_STOP);
293}
294
295void BasicPortAllocatorSession::OnMessage(talk_base::Message *message) {
296 switch (message->message_id) {
297 case MSG_CONFIG_START:
298 ASSERT(talk_base::Thread::Current() == network_thread_);
299 GetPortConfigurations();
300 break;
301
302 case MSG_CONFIG_READY:
303 ASSERT(talk_base::Thread::Current() == network_thread_);
304 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
305 break;
306
307 case MSG_ALLOCATE:
308 ASSERT(talk_base::Thread::Current() == network_thread_);
309 OnAllocate();
310 break;
311
312 case MSG_SHAKE:
313 ASSERT(talk_base::Thread::Current() == network_thread_);
314 OnShake();
315 break;
316 case MSG_SEQUENCEOBJECTS_CREATED:
317 ASSERT(talk_base::Thread::Current() == network_thread_);
318 OnAllocationSequenceObjectsCreated();
319 break;
320 case MSG_CONFIG_STOP:
321 ASSERT(talk_base::Thread::Current() == network_thread_);
322 OnConfigStop();
323 break;
324 default:
325 ASSERT(false);
326 }
327}
328
329void BasicPortAllocatorSession::GetPortConfigurations() {
330 PortConfiguration* config = new PortConfiguration(allocator_->stun_address(),
331 username(),
332 password());
333
334 for (size_t i = 0; i < allocator_->relays().size(); ++i) {
335 config->AddRelay(allocator_->relays()[i]);
336 }
337 ConfigReady(config);
338}
339
340void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
341 network_thread_->Post(this, MSG_CONFIG_READY, config);
342}
343
344// Adds a configuration to the list.
345void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
346 if (config)
347 configs_.push_back(config);
348
349 AllocatePorts();
350}
351
352void BasicPortAllocatorSession::OnConfigStop() {
353 ASSERT(talk_base::Thread::Current() == network_thread_);
354
355 // If any of the allocated ports have not completed the candidates allocation,
356 // mark those as error. Since session doesn't need any new candidates
357 // at this stage of the allocation, it's safe to discard any new candidates.
358 bool send_signal = false;
359 for (std::vector<PortData>::iterator it = ports_.begin();
360 it != ports_.end(); ++it) {
361 if (!it->complete()) {
362 // Updating port state to error, which didn't finish allocating candidates
363 // yet.
364 it->set_error();
365 send_signal = true;
366 }
367 }
368
369 // Did we stop any running sequences?
370 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
371 it != sequences_.end() && !send_signal; ++it) {
372 if ((*it)->state() == AllocationSequence::kStopped) {
373 send_signal = true;
374 }
375 }
376
377 // If we stopped anything that was running, send a done signal now.
378 if (send_signal) {
379 MaybeSignalCandidatesAllocationDone();
380 }
381}
382
383void BasicPortAllocatorSession::AllocatePorts() {
384 ASSERT(talk_base::Thread::Current() == network_thread_);
385 network_thread_->Post(this, MSG_ALLOCATE);
386}
387
388void BasicPortAllocatorSession::OnAllocate() {
389 if (network_manager_started_)
390 DoAllocate();
391
392 allocation_started_ = true;
393 if (running_)
394 network_thread_->PostDelayed(ALLOCATE_DELAY, this, MSG_ALLOCATE);
395}
396
397// For each network, see if we have a sequence that covers it already. If not,
398// create a new sequence to create the appropriate ports.
399void BasicPortAllocatorSession::DoAllocate() {
400 bool done_signal_needed = false;
401 std::vector<talk_base::Network*> networks;
402 allocator_->network_manager()->GetNetworks(&networks);
403 if (networks.empty()) {
404 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
405 done_signal_needed = true;
406 } else {
407 for (uint32 i = 0; i < networks.size(); ++i) {
408 PortConfiguration* config = NULL;
409 if (configs_.size() > 0)
410 config = configs_.back();
411
412 uint32 sequence_flags = flags();
413 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
414 // If all the ports are disabled we should just fire the allocation
415 // done event and return.
416 done_signal_needed = true;
417 break;
418 }
419
420 // Disables phases that are not specified in this config.
421 if (!config || config->stun_address.IsNil()) {
422 // No STUN ports specified in this config.
423 sequence_flags |= PORTALLOCATOR_DISABLE_STUN;
424 }
425 if (!config || config->relays.empty()) {
426 // No relay ports specified in this config.
427 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
428 }
429
430 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
431 networks[i]->ip().family() == AF_INET6) {
432 // Skip IPv6 networks unless the flag's been set.
433 continue;
434 }
435
436 // Disable phases that would only create ports equivalent to
437 // ones that we have already made.
438 DisableEquivalentPhases(networks[i], config, &sequence_flags);
439
440 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
441 // New AllocationSequence would have nothing to do, so don't make it.
442 continue;
443 }
444
445 AllocationSequence* sequence =
446 new AllocationSequence(this, networks[i], config, sequence_flags);
447 if (!sequence->Init()) {
448 delete sequence;
449 continue;
450 }
451 done_signal_needed = true;
452 sequence->SignalPortAllocationComplete.connect(
453 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
454 if (running_)
455 sequence->Start();
456 sequences_.push_back(sequence);
457 }
458 }
459 if (done_signal_needed) {
460 network_thread_->Post(this, MSG_SEQUENCEOBJECTS_CREATED);
461 }
462}
463
464void BasicPortAllocatorSession::OnNetworksChanged() {
465 network_manager_started_ = true;
466 if (allocation_started_)
467 DoAllocate();
468}
469
470void BasicPortAllocatorSession::DisableEquivalentPhases(
471 talk_base::Network* network, PortConfiguration* config, uint32* flags) {
472 for (uint32 i = 0; i < sequences_.size() &&
473 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES; ++i) {
474 sequences_[i]->DisableEquivalentPhases(network, config, flags);
475 }
476}
477
478void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
479 AllocationSequence * seq,
480 bool prepare_address) {
481 if (!port)
482 return;
483
484 LOG(LS_INFO) << "Adding allocated port for " << content_name();
485 port->set_content_name(content_name());
486 port->set_component(component_);
487 port->set_generation(generation());
488 if (allocator_->proxy().type != talk_base::PROXY_NONE)
489 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
490 port->set_send_retransmit_count_attribute((allocator_->flags() &
491 PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
492
493 if (content_name().compare(CN_VIDEO) == 0 &&
494 component_ == cricket::ICE_CANDIDATE_COMPONENT_RTP) {
495 // For video RTP alone, we set send-buffer sizes. This used to be set in the
496 // engines/channels.
497 int sendBufSize = (flags() & PORTALLOCATOR_USE_LARGE_SOCKET_SEND_BUFFERS)
498 ? kLargeSocketSendBufferSize
499 : kNormalSocketSendBufferSize;
500 port->SetOption(talk_base::Socket::OPT_SNDBUF, sendBufSize);
501 }
502
503 PortData data(port, seq);
504 ports_.push_back(data);
505
506 port->SignalCandidateReady.connect(
507 this, &BasicPortAllocatorSession::OnCandidateReady);
508 port->SignalPortComplete.connect(this,
509 &BasicPortAllocatorSession::OnPortComplete);
510 port->SignalDestroyed.connect(this,
511 &BasicPortAllocatorSession::OnPortDestroyed);
512 port->SignalPortError.connect(
513 this, &BasicPortAllocatorSession::OnPortError);
514 LOG_J(LS_INFO, port) << "Added port to allocator";
515
516 if (prepare_address)
517 port->PrepareAddress();
518 if (running_)
519 port->Start();
520}
521
522void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
523 allocation_sequences_created_ = true;
524 // Send candidate allocation complete signal if we have no sequences.
525 MaybeSignalCandidatesAllocationDone();
526}
527
528void BasicPortAllocatorSession::OnCandidateReady(
529 Port* port, const Candidate& c) {
530 ASSERT(talk_base::Thread::Current() == network_thread_);
531 PortData* data = FindPort(port);
532 ASSERT(data != NULL);
533 // Discarding any candidate signal if port allocation status is
534 // already in completed state.
535 if (data->complete())
536 return;
537
538 // Send candidates whose protocol is enabled.
539 std::vector<Candidate> candidates;
540 ProtocolType pvalue;
541 if (StringToProto(c.protocol().c_str(), &pvalue) &&
542 data->sequence()->ProtocolEnabled(pvalue)) {
543 candidates.push_back(c);
544 }
545
546 if (!candidates.empty()) {
547 SignalCandidatesReady(this, candidates);
548 }
549
550 // Moving to READY state as we have atleast one candidate from the port.
551 // Since this port has atleast one candidate we should forward this port
552 // to listners, to allow connections from this port.
553 if (!data->ready()) {
554 data->set_ready();
555 SignalPortReady(this, port);
556 }
557}
558
559void BasicPortAllocatorSession::OnPortComplete(Port* port) {
560 ASSERT(talk_base::Thread::Current() == network_thread_);
561 PortData* data = FindPort(port);
562 ASSERT(data != NULL);
563
564 // Ignore any late signals.
565 if (data->complete())
566 return;
567
568 // Moving to COMPLETE state.
569 data->set_complete();
570 // Send candidate allocation complete signal if this was the last port.
571 MaybeSignalCandidatesAllocationDone();
572}
573
574void BasicPortAllocatorSession::OnPortError(Port* port) {
575 ASSERT(talk_base::Thread::Current() == network_thread_);
576 PortData* data = FindPort(port);
577 ASSERT(data != NULL);
578 // We might have already given up on this port and stopped it.
579 if (data->complete())
580 return;
581
582 // SignalAddressError is currently sent from StunPort/TurnPort.
583 // But this signal itself is generic.
584 data->set_error();
585 // Send candidate allocation complete signal if this was the last port.
586 MaybeSignalCandidatesAllocationDone();
587}
588
589void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
590 ProtocolType proto) {
591 std::vector<Candidate> candidates;
592 for (std::vector<PortData>::iterator it = ports_.begin();
593 it != ports_.end(); ++it) {
594 if (it->sequence() != seq)
595 continue;
596
597 const std::vector<Candidate>& potentials = it->port()->Candidates();
598 for (size_t i = 0; i < potentials.size(); ++i) {
599 ProtocolType pvalue;
600 if (!StringToProto(potentials[i].protocol().c_str(), &pvalue))
601 continue;
602 if (pvalue == proto) {
603 candidates.push_back(potentials[i]);
604 }
605 }
606 }
607
608 if (!candidates.empty()) {
609 SignalCandidatesReady(this, candidates);
610 }
611}
612
613void BasicPortAllocatorSession::OnPortAllocationComplete(
614 AllocationSequence* seq) {
615 // Send candidate allocation complete signal if all ports are done.
616 MaybeSignalCandidatesAllocationDone();
617}
618
619void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
620 // Send signal only if all required AllocationSequence objects
621 // are created.
622 if (!allocation_sequences_created_)
623 return;
624
625 // Check that all port allocation sequences are complete.
626 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
627 it != sequences_.end(); ++it) {
628 if ((*it)->state() == AllocationSequence::kRunning)
629 return;
630 }
631
632 // If all allocated ports are in complete state, session must have got all
633 // expected candidates. Session will trigger candidates allocation complete
634 // signal.
635 for (std::vector<PortData>::iterator it = ports_.begin();
636 it != ports_.end(); ++it) {
637 if (!it->complete())
638 return;
639 }
640 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
641 << component_ << ":" << generation();
642 SignalCandidatesAllocationDone(this);
643}
644
645void BasicPortAllocatorSession::OnPortDestroyed(
646 PortInterface* port) {
647 ASSERT(talk_base::Thread::Current() == network_thread_);
648 for (std::vector<PortData>::iterator iter = ports_.begin();
649 iter != ports_.end(); ++iter) {
650 if (port == iter->port()) {
651 ports_.erase(iter);
652 LOG_J(LS_INFO, port) << "Removed port from allocator ("
653 << static_cast<int>(ports_.size()) << " remaining)";
654 return;
655 }
656 }
657 ASSERT(false);
658}
659
660void BasicPortAllocatorSession::OnShake() {
661 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
662
663 std::vector<Port*> ports;
664 std::vector<Connection*> connections;
665
666 for (size_t i = 0; i < ports_.size(); ++i) {
667 if (ports_[i].ready())
668 ports.push_back(ports_[i].port());
669 }
670
671 for (size_t i = 0; i < ports.size(); ++i) {
672 Port::AddressMap::const_iterator iter;
673 for (iter = ports[i]->connections().begin();
674 iter != ports[i]->connections().end();
675 ++iter) {
676 connections.push_back(iter->second);
677 }
678 }
679
680 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
681 << connections.size() << " connections";
682
683 for (size_t i = 0; i < connections.size(); ++i)
684 connections[i]->Destroy();
685
686 if (running_ || (ports.size() > 0) || (connections.size() > 0))
687 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
688}
689
690BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
691 Port* port) {
692 for (std::vector<PortData>::iterator it = ports_.begin();
693 it != ports_.end(); ++it) {
694 if (it->port() == port) {
695 return &*it;
696 }
697 }
698 return NULL;
699}
700
701// AllocationSequence
702
703AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
704 talk_base::Network* network,
705 PortConfiguration* config,
706 uint32 flags)
707 : session_(session),
708 network_(network),
709 ip_(network->ip()),
710 config_(config),
711 state_(kInit),
712 flags_(flags),
wu@webrtc.org97077a32013-10-25 21:18:33 +0000713 udp_socket_(),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000714 phase_(0) {
715}
716
717bool AllocationSequence::Init() {
718 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
719 !IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_UFRAG)) {
720 LOG(LS_ERROR) << "Shared socket option can't be set without "
721 << "shared ufrag.";
722 ASSERT(false);
723 return false;
724 }
725
726 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
727 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
728 talk_base::SocketAddress(ip_, 0), session_->allocator()->min_port(),
729 session_->allocator()->max_port()));
730 if (udp_socket_) {
731 udp_socket_->SignalReadPacket.connect(
732 this, &AllocationSequence::OnReadPacket);
733 }
734 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
735 // are next available options to setup a communication channel.
736 }
737 return true;
738}
739
740AllocationSequence::~AllocationSequence() {
741 session_->network_thread()->Clear(this);
742}
743
744void AllocationSequence::DisableEquivalentPhases(talk_base::Network* network,
745 PortConfiguration* config, uint32* flags) {
746 if (!((network == network_) && (ip_ == network->ip()))) {
747 // Different network setup; nothing is equivalent.
748 return;
749 }
750
751 // Else turn off the stuff that we've already got covered.
752
753 // Every config implicitly specifies local, so turn that off right away.
754 *flags |= PORTALLOCATOR_DISABLE_UDP;
755 *flags |= PORTALLOCATOR_DISABLE_TCP;
756
757 if (config_ && config) {
758 if (config_->stun_address == config->stun_address) {
759 // Already got this STUN server covered.
760 *flags |= PORTALLOCATOR_DISABLE_STUN;
761 }
762 if (!config_->relays.empty()) {
763 // Already got relays covered.
764 // NOTE: This will even skip a _different_ set of relay servers if we
765 // were to be given one, but that never happens in our codebase. Should
766 // probably get rid of the list in PortConfiguration and just keep a
767 // single relay server in each one.
768 *flags |= PORTALLOCATOR_DISABLE_RELAY;
769 }
770 }
771}
772
773void AllocationSequence::Start() {
774 state_ = kRunning;
775 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
776}
777
778void AllocationSequence::Stop() {
779 // If the port is completed, don't set it to stopped.
780 if (state_ == kRunning) {
781 state_ = kStopped;
782 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
783 }
784}
785
786void AllocationSequence::OnMessage(talk_base::Message* msg) {
787 ASSERT(talk_base::Thread::Current() == session_->network_thread());
788 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
789
790 const char* const PHASE_NAMES[kNumPhases] = {
791 "Udp", "Relay", "Tcp", "SslTcp"
792 };
793
794 // Perform all of the phases in the current step.
795 LOG_J(LS_INFO, network_) << "Allocation Phase="
796 << PHASE_NAMES[phase_];
797
798 switch (phase_) {
799 case PHASE_UDP:
800 CreateUDPPorts();
801 CreateStunPorts();
802 EnableProtocol(PROTO_UDP);
803 break;
804
805 case PHASE_RELAY:
806 CreateRelayPorts();
807 break;
808
809 case PHASE_TCP:
810 CreateTCPPorts();
811 EnableProtocol(PROTO_TCP);
812 break;
813
814 case PHASE_SSLTCP:
815 state_ = kCompleted;
816 EnableProtocol(PROTO_SSLTCP);
817 break;
818
819 default:
820 ASSERT(false);
821 }
822
823 if (state() == kRunning) {
824 ++phase_;
825 session_->network_thread()->PostDelayed(
826 session_->allocator()->step_delay(),
827 this, MSG_ALLOCATION_PHASE);
828 } else {
829 // If all phases in AllocationSequence are completed, no allocation
830 // steps needed further. Canceling pending signal.
831 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
832 SignalPortAllocationComplete(this);
833 }
834}
835
836void AllocationSequence::EnableProtocol(ProtocolType proto) {
837 if (!ProtocolEnabled(proto)) {
838 protocols_.push_back(proto);
839 session_->OnProtocolEnabled(this, proto);
840 }
841}
842
843bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
844 for (ProtocolList::const_iterator it = protocols_.begin();
845 it != protocols_.end(); ++it) {
846 if (*it == proto)
847 return true;
848 }
849 return false;
850}
851
852void AllocationSequence::CreateUDPPorts() {
853 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
854 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
855 return;
856 }
857
858 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
859 // is enabled completely.
860 UDPPort* port = NULL;
861 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +0000862 port = UDPPort::Create(session_->network_thread(),
863 session_->socket_factory(), network_,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864 udp_socket_.get(),
865 session_->username(), session_->password());
866 } else {
867 port = UDPPort::Create(session_->network_thread(),
868 session_->socket_factory(),
869 network_, ip_,
870 session_->allocator()->min_port(),
871 session_->allocator()->max_port(),
872 session_->username(), session_->password());
873 }
874
875 if (port) {
876 ports.push_back(port);
877 // If shared socket is enabled, STUN candidate will be allocated by the
878 // UDPPort.
879 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
880 !IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
881 ASSERT(config_ && !config_->stun_address.IsNil());
882 if (!(config_ && !config_->stun_address.IsNil())) {
883 LOG(LS_WARNING)
884 << "AllocationSequence: No STUN server configured, skipping.";
885 return;
886 }
887 port->set_server_addr(config_->stun_address);
888 }
889
890 session_->AddAllocatedPort(port, this, true);
891 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
892 }
893}
894
895void AllocationSequence::CreateTCPPorts() {
896 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
897 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
898 return;
899 }
900
901 Port* port = TCPPort::Create(session_->network_thread(),
902 session_->socket_factory(),
903 network_, ip_,
904 session_->allocator()->min_port(),
905 session_->allocator()->max_port(),
906 session_->username(), session_->password(),
907 session_->allocator()->allow_tcp_listen());
908 if (port) {
909 session_->AddAllocatedPort(port, this, true);
910 // Since TCPPort is not created using shared socket, |port| will not be
911 // added to the dequeue.
912 }
913}
914
915void AllocationSequence::CreateStunPorts() {
916 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
917 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
918 return;
919 }
920
921 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
922 LOG(LS_INFO) << "AllocationSequence: "
923 << "UDPPort will be handling the STUN candidate generation.";
924 return;
925 }
926
927 // If BasicPortAllocatorSession::OnAllocate left STUN ports enabled then we
928 // ought to have an address for them here.
929 ASSERT(config_ && !config_->stun_address.IsNil());
930 if (!(config_ && !config_->stun_address.IsNil())) {
931 LOG(LS_WARNING)
932 << "AllocationSequence: No STUN server configured, skipping.";
933 return;
934 }
935
936 StunPort* port = StunPort::Create(session_->network_thread(),
937 session_->socket_factory(),
938 network_, ip_,
939 session_->allocator()->min_port(),
940 session_->allocator()->max_port(),
941 session_->username(), session_->password(),
942 config_->stun_address);
943 if (port) {
944 session_->AddAllocatedPort(port, this, true);
945 // Since StunPort is not created using shared socket, |port| will not be
946 // added to the dequeue.
947 }
948}
949
950void AllocationSequence::CreateRelayPorts() {
951 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
952 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
953 return;
954 }
955
956 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
957 // ought to have a relay list for them here.
958 ASSERT(config_ && !config_->relays.empty());
959 if (!(config_ && !config_->relays.empty())) {
960 LOG(LS_WARNING)
961 << "AllocationSequence: No relay server configured, skipping.";
962 return;
963 }
964
965 PortConfiguration::RelayList::const_iterator relay;
966 for (relay = config_->relays.begin();
967 relay != config_->relays.end(); ++relay) {
968 if (relay->type == RELAY_GTURN) {
969 CreateGturnPort(*relay);
970 } else if (relay->type == RELAY_TURN) {
971 CreateTurnPort(*relay);
972 } else {
973 ASSERT(false);
974 }
975 }
976}
977
978void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
979 // TODO(mallinath) - Rename RelayPort to GTurnPort.
980 RelayPort* port = RelayPort::Create(session_->network_thread(),
981 session_->socket_factory(),
982 network_, ip_,
983 session_->allocator()->min_port(),
984 session_->allocator()->max_port(),
985 config_->username, config_->password);
986 if (port) {
987 // Since RelayPort is not created using shared socket, |port| will not be
988 // added to the dequeue.
989 // Note: We must add the allocated port before we add addresses because
990 // the latter will create candidates that need name and preference
991 // settings. However, we also can't prepare the address (normally
992 // done by AddAllocatedPort) until we have these addresses. So we
993 // wait to do that until below.
994 session_->AddAllocatedPort(port, this, false);
995
996 // Add the addresses of this protocol.
997 PortList::const_iterator relay_port;
998 for (relay_port = config.ports.begin();
999 relay_port != config.ports.end();
1000 ++relay_port) {
1001 port->AddServerAddress(*relay_port);
1002 port->AddExternalAddress(*relay_port);
1003 }
1004 // Start fetching an address for this port.
1005 port->PrepareAddress();
1006 }
1007}
1008
1009void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1010 PortList::const_iterator relay_port;
1011 for (relay_port = config.ports.begin();
1012 relay_port != config.ports.end(); ++relay_port) {
1013 TurnPort* port = TurnPort::Create(session_->network_thread(),
1014 session_->socket_factory(),
1015 network_, ip_,
1016 session_->allocator()->min_port(),
1017 session_->allocator()->max_port(),
1018 session_->username(),
1019 session_->password(),
1020 *relay_port, config.credentials);
1021 if (port) {
1022 session_->AddAllocatedPort(port, this, true);
1023 }
1024 }
1025}
1026
1027void AllocationSequence::OnReadPacket(
1028 talk_base::AsyncPacketSocket* socket, const char* data, size_t size,
wu@webrtc.orga9890802013-12-13 00:21:03 +00001029 const talk_base::SocketAddress& remote_addr,
1030 const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031 ASSERT(socket == udp_socket_.get());
1032 for (std::deque<Port*>::iterator iter = ports.begin();
1033 iter != ports.end(); ++iter) {
1034 // We have only one port in the queue.
1035 // TODO(mallinath) - Add shared socket support to Relay and Turn ports.
wu@webrtc.orga9890802013-12-13 00:21:03 +00001036 if ((*iter)->HandleIncomingPacket(
1037 socket, data, size, remote_addr, packet_time)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 break;
1039 }
1040 }
1041}
1042
1043void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1044 std::deque<Port*>::iterator iter =
1045 std::find(ports.begin(), ports.end(), port);
1046 ASSERT(iter != ports.end());
1047 ports.erase(iter);
1048}
1049
1050// PortConfiguration
1051PortConfiguration::PortConfiguration(
1052 const talk_base::SocketAddress& stun_address,
1053 const std::string& username,
1054 const std::string& password)
1055 : stun_address(stun_address),
1056 username(username),
1057 password(password) {
1058}
1059
1060void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1061 relays.push_back(config);
1062}
1063
1064bool PortConfiguration::SupportsProtocol(
1065 const RelayServerConfig& relay, ProtocolType type) {
1066 PortList::const_iterator relay_port;
1067 for (relay_port = relay.ports.begin();
1068 relay_port != relay.ports.end();
1069 ++relay_port) {
1070 if (relay_port->proto == type)
1071 return true;
1072 }
1073 return false;
1074}
1075
1076} // namespace cricket