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