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