blob: fe263f597fdc3898adc7e5eaf24e225af7003f13 [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() ==
guoweisea1012b2015-08-21 09:06:28 -0700310 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700311 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
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700565 // If PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE is specified and it's
566 // loopback address, we should allow it as it's for demo page connectivity
567 // when no TURN/STUN specified.
568 if (c.address().IsLoopbackIP() &&
569 (flags() & PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE) != 0) {
570 return true;
571 }
572
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000573 // This is just to prevent the case when binding to any address (all 0s), if
574 // somehow the host candidate address is not all 0s. Either because local
575 // installed proxy changes the address or a packet has been sent for any
576 // reason before getsockname is called.
577 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
578 LOG(LS_WARNING) << "Received non-0 host address: "
579 << c.address().ToString()
580 << " when adapter enumeration is disabled";
581 return false;
582 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000584 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000585 }
586 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587}
588
589void BasicPortAllocatorSession::OnPortAllocationComplete(
590 AllocationSequence* seq) {
591 // Send candidate allocation complete signal if all ports are done.
592 MaybeSignalCandidatesAllocationDone();
593}
594
595void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
596 // Send signal only if all required AllocationSequence objects
597 // are created.
598 if (!allocation_sequences_created_)
599 return;
600
601 // Check that all port allocation sequences are complete.
602 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
603 it != sequences_.end(); ++it) {
604 if ((*it)->state() == AllocationSequence::kRunning)
605 return;
606 }
607
608 // If all allocated ports are in complete state, session must have got all
609 // expected candidates. Session will trigger candidates allocation complete
610 // signal.
611 for (std::vector<PortData>::iterator it = ports_.begin();
612 it != ports_.end(); ++it) {
613 if (!it->complete())
614 return;
615 }
616 LOG(LS_INFO) << "All candidates gathered for " << content_name_ << ":"
617 << component_ << ":" << generation();
618 SignalCandidatesAllocationDone(this);
619}
620
621void BasicPortAllocatorSession::OnPortDestroyed(
622 PortInterface* port) {
623 ASSERT(rtc::Thread::Current() == network_thread_);
624 for (std::vector<PortData>::iterator iter = ports_.begin();
625 iter != ports_.end(); ++iter) {
626 if (port == iter->port()) {
627 ports_.erase(iter);
628 LOG_J(LS_INFO, port) << "Removed port from allocator ("
629 << static_cast<int>(ports_.size()) << " remaining)";
630 return;
631 }
632 }
633 ASSERT(false);
634}
635
636void BasicPortAllocatorSession::OnShake() {
637 LOG(INFO) << ">>>>> SHAKE <<<<< >>>>> SHAKE <<<<< >>>>> SHAKE <<<<<";
638
639 std::vector<Port*> ports;
640 std::vector<Connection*> connections;
641
642 for (size_t i = 0; i < ports_.size(); ++i) {
643 if (ports_[i].ready())
644 ports.push_back(ports_[i].port());
645 }
646
647 for (size_t i = 0; i < ports.size(); ++i) {
648 Port::AddressMap::const_iterator iter;
649 for (iter = ports[i]->connections().begin();
650 iter != ports[i]->connections().end();
651 ++iter) {
652 connections.push_back(iter->second);
653 }
654 }
655
656 LOG(INFO) << ">>>>> Destroying " << ports.size() << " ports and "
657 << connections.size() << " connections";
658
659 for (size_t i = 0; i < connections.size(); ++i)
660 connections[i]->Destroy();
661
662 if (running_ || (ports.size() > 0) || (connections.size() > 0))
663 network_thread_->PostDelayed(ShakeDelay(), this, MSG_SHAKE);
664}
665
666BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
667 Port* port) {
668 for (std::vector<PortData>::iterator it = ports_.begin();
669 it != ports_.end(); ++it) {
670 if (it->port() == port) {
671 return &*it;
672 }
673 }
674 return NULL;
675}
676
677// AllocationSequence
678
679AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
680 rtc::Network* network,
681 PortConfiguration* config,
682 uint32 flags)
683 : session_(session),
684 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000686 config_(config),
687 state_(kInit),
688 flags_(flags),
689 udp_socket_(),
690 udp_port_(NULL),
691 phase_(0) {
692}
693
694bool AllocationSequence::Init() {
minyuel5bdafd42015-08-21 15:52:48 +0200695 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
696 !IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_UFRAG)) {
697 LOG(LS_ERROR) << "Shared socket option can't be set without "
698 << "shared ufrag.";
699 ASSERT(false);
700 return false;
701 }
702
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000703 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
704 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
705 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
706 session_->allocator()->max_port()));
707 if (udp_socket_) {
708 udp_socket_->SignalReadPacket.connect(
709 this, &AllocationSequence::OnReadPacket);
710 }
711 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
712 // are next available options to setup a communication channel.
713 }
714 return true;
715}
716
717void AllocationSequence::Clear() {
718 udp_port_ = NULL;
719 turn_ports_.clear();
720}
721
722AllocationSequence::~AllocationSequence() {
723 session_->network_thread()->Clear(this);
724}
725
726void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
727 PortConfiguration* config, uint32* flags) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000728 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000729 // Different network setup; nothing is equivalent.
730 return;
731 }
732
733 // Else turn off the stuff that we've already got covered.
734
735 // Every config implicitly specifies local, so turn that off right away.
736 *flags |= PORTALLOCATOR_DISABLE_UDP;
737 *flags |= PORTALLOCATOR_DISABLE_TCP;
738
739 if (config_ && config) {
740 if (config_->StunServers() == config->StunServers()) {
741 // Already got this STUN servers covered.
742 *flags |= PORTALLOCATOR_DISABLE_STUN;
743 }
744 if (!config_->relays.empty()) {
745 // Already got relays covered.
746 // NOTE: This will even skip a _different_ set of relay servers if we
747 // were to be given one, but that never happens in our codebase. Should
748 // probably get rid of the list in PortConfiguration and just keep a
749 // single relay server in each one.
750 *flags |= PORTALLOCATOR_DISABLE_RELAY;
751 }
752 }
753}
754
755void AllocationSequence::Start() {
756 state_ = kRunning;
757 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
758}
759
760void AllocationSequence::Stop() {
761 // If the port is completed, don't set it to stopped.
762 if (state_ == kRunning) {
763 state_ = kStopped;
764 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
765 }
766}
767
768void AllocationSequence::OnMessage(rtc::Message* msg) {
769 ASSERT(rtc::Thread::Current() == session_->network_thread());
770 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
771
772 const char* const PHASE_NAMES[kNumPhases] = {
773 "Udp", "Relay", "Tcp", "SslTcp"
774 };
775
776 // Perform all of the phases in the current step.
777 LOG_J(LS_INFO, network_) << "Allocation Phase="
778 << PHASE_NAMES[phase_];
779
780 switch (phase_) {
781 case PHASE_UDP:
782 CreateUDPPorts();
783 CreateStunPorts();
784 EnableProtocol(PROTO_UDP);
785 break;
786
787 case PHASE_RELAY:
788 CreateRelayPorts();
789 break;
790
791 case PHASE_TCP:
792 CreateTCPPorts();
793 EnableProtocol(PROTO_TCP);
794 break;
795
796 case PHASE_SSLTCP:
797 state_ = kCompleted;
798 EnableProtocol(PROTO_SSLTCP);
799 break;
800
801 default:
802 ASSERT(false);
803 }
804
805 if (state() == kRunning) {
806 ++phase_;
807 session_->network_thread()->PostDelayed(
808 session_->allocator()->step_delay(),
809 this, MSG_ALLOCATION_PHASE);
810 } else {
811 // If all phases in AllocationSequence are completed, no allocation
812 // steps needed further. Canceling pending signal.
813 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
814 SignalPortAllocationComplete(this);
815 }
816}
817
818void AllocationSequence::EnableProtocol(ProtocolType proto) {
819 if (!ProtocolEnabled(proto)) {
820 protocols_.push_back(proto);
821 session_->OnProtocolEnabled(this, proto);
822 }
823}
824
825bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
826 for (ProtocolList::const_iterator it = protocols_.begin();
827 it != protocols_.end(); ++it) {
828 if (*it == proto)
829 return true;
830 }
831 return false;
832}
833
834void AllocationSequence::CreateUDPPorts() {
835 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
836 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
837 return;
838 }
839
840 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
841 // is enabled completely.
842 UDPPort* port = NULL;
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700843 bool emit_localhost_for_anyaddress =
844 IsFlagSet(PORTALLOCATOR_ENABLE_LOCALHOST_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700846 port = UDPPort::Create(
847 session_->network_thread(), session_->socket_factory(), network_,
848 udp_socket_.get(), session_->username(), session_->password(),
849 session_->allocator()->origin(), emit_localhost_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700851 port = UDPPort::Create(
852 session_->network_thread(), session_->socket_factory(), network_, ip_,
853 session_->allocator()->min_port(), session_->allocator()->max_port(),
854 session_->username(), session_->password(),
855 session_->allocator()->origin(), emit_localhost_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000856 }
857
858 if (port) {
859 // If shared socket is enabled, STUN candidate will be allocated by the
860 // UDPPort.
861 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
862 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000863 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864
865 // If STUN is not disabled, setting stun server address to port.
866 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000867 if (config_ && !config_->StunServers().empty()) {
868 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
869 << "STUN candidate generation.";
870 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000871 }
872 }
873 }
874
875 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876 }
877}
878
879void AllocationSequence::CreateTCPPorts() {
880 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
881 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
882 return;
883 }
884
885 Port* port = TCPPort::Create(session_->network_thread(),
886 session_->socket_factory(),
887 network_, ip_,
888 session_->allocator()->min_port(),
889 session_->allocator()->max_port(),
890 session_->username(), session_->password(),
891 session_->allocator()->allow_tcp_listen());
892 if (port) {
893 session_->AddAllocatedPort(port, this, true);
894 // Since TCPPort is not created using shared socket, |port| will not be
895 // added to the dequeue.
896 }
897}
898
899void AllocationSequence::CreateStunPorts() {
900 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
901 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
902 return;
903 }
904
905 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
906 return;
907 }
908
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000909 if (!(config_ && !config_->StunServers().empty())) {
910 LOG(LS_WARNING)
911 << "AllocationSequence: No STUN server configured, skipping.";
912 return;
913 }
914
915 StunPort* port = StunPort::Create(session_->network_thread(),
916 session_->socket_factory(),
917 network_, ip_,
918 session_->allocator()->min_port(),
919 session_->allocator()->max_port(),
920 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000921 config_->StunServers(),
922 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 if (port) {
924 session_->AddAllocatedPort(port, this, true);
925 // Since StunPort is not created using shared socket, |port| will not be
926 // added to the dequeue.
927 }
928}
929
930void AllocationSequence::CreateRelayPorts() {
931 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
932 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
933 return;
934 }
935
936 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
937 // ought to have a relay list for them here.
938 ASSERT(config_ && !config_->relays.empty());
939 if (!(config_ && !config_->relays.empty())) {
940 LOG(LS_WARNING)
941 << "AllocationSequence: No relay server configured, skipping.";
942 return;
943 }
944
945 PortConfiguration::RelayList::const_iterator relay;
946 for (relay = config_->relays.begin();
947 relay != config_->relays.end(); ++relay) {
948 if (relay->type == RELAY_GTURN) {
949 CreateGturnPort(*relay);
950 } else if (relay->type == RELAY_TURN) {
951 CreateTurnPort(*relay);
952 } else {
953 ASSERT(false);
954 }
955 }
956}
957
958void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
959 // TODO(mallinath) - Rename RelayPort to GTurnPort.
960 RelayPort* port = RelayPort::Create(session_->network_thread(),
961 session_->socket_factory(),
962 network_, ip_,
963 session_->allocator()->min_port(),
964 session_->allocator()->max_port(),
965 config_->username, config_->password);
966 if (port) {
967 // Since RelayPort is not created using shared socket, |port| will not be
968 // added to the dequeue.
969 // Note: We must add the allocated port before we add addresses because
970 // the latter will create candidates that need name and preference
971 // settings. However, we also can't prepare the address (normally
972 // done by AddAllocatedPort) until we have these addresses. So we
973 // wait to do that until below.
974 session_->AddAllocatedPort(port, this, false);
975
976 // Add the addresses of this protocol.
977 PortList::const_iterator relay_port;
978 for (relay_port = config.ports.begin();
979 relay_port != config.ports.end();
980 ++relay_port) {
981 port->AddServerAddress(*relay_port);
982 port->AddExternalAddress(*relay_port);
983 }
984 // Start fetching an address for this port.
985 port->PrepareAddress();
986 }
987}
988
989void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
990 PortList::const_iterator relay_port;
991 for (relay_port = config.ports.begin();
992 relay_port != config.ports.end(); ++relay_port) {
993 TurnPort* port = NULL;
994 // Shared socket mode must be enabled only for UDP based ports. Hence
995 // don't pass shared socket for ports which will create TCP sockets.
996 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
997 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
998 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -0700999 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001000 port = TurnPort::Create(session_->network_thread(),
1001 session_->socket_factory(),
1002 network_, udp_socket_.get(),
1003 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001004 *relay_port, config.credentials, config.priority,
1005 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006 turn_ports_.push_back(port);
1007 // Listen to the port destroyed signal, to allow AllocationSequence to
1008 // remove entrt from it's map.
1009 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1010 } else {
1011 port = TurnPort::Create(session_->network_thread(),
1012 session_->socket_factory(),
1013 network_, ip_,
1014 session_->allocator()->min_port(),
1015 session_->allocator()->max_port(),
1016 session_->username(),
1017 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001018 *relay_port, config.credentials, config.priority,
1019 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001020 }
1021 ASSERT(port != NULL);
1022 session_->AddAllocatedPort(port, this, true);
1023 }
1024}
1025
1026void AllocationSequence::OnReadPacket(
1027 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1028 const rtc::SocketAddress& remote_addr,
1029 const rtc::PacketTime& packet_time) {
1030 ASSERT(socket == udp_socket_.get());
1031
1032 bool turn_port_found = false;
1033
1034 // Try to find the TurnPort that matches the remote address. Note that the
1035 // message could be a STUN binding response if the TURN server is also used as
1036 // a STUN server. We don't want to parse every message here to check if it is
1037 // a STUN binding response, so we pass the message to TurnPort regardless of
1038 // the message type. The TurnPort will just ignore the message since it will
1039 // not find any request by transaction ID.
1040 for (std::vector<TurnPort*>::const_iterator it = turn_ports_.begin();
1041 it != turn_ports_.end(); ++it) {
1042 TurnPort* port = *it;
1043 if (port->server_address().address == remote_addr) {
1044 port->HandleIncomingPacket(socket, data, size, remote_addr, packet_time);
1045 turn_port_found = true;
1046 break;
1047 }
1048 }
1049
1050 if (udp_port_) {
1051 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1052
1053 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1054 // the TURN server is also a STUN server.
1055 if (!turn_port_found ||
1056 stun_servers.find(remote_addr) != stun_servers.end()) {
1057 udp_port_->HandleIncomingPacket(
1058 socket, data, size, remote_addr, packet_time);
1059 }
1060 }
1061}
1062
1063void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1064 if (udp_port_ == port) {
1065 udp_port_ = NULL;
1066 return;
1067 }
1068
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001069 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1070 if (it != turn_ports_.end()) {
1071 turn_ports_.erase(it);
1072 } else {
1073 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1074 ASSERT(false);
1075 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001076}
1077
1078// PortConfiguration
1079PortConfiguration::PortConfiguration(
1080 const rtc::SocketAddress& stun_address,
1081 const std::string& username,
1082 const std::string& password)
1083 : stun_address(stun_address), username(username), password(password) {
1084 if (!stun_address.IsNil())
1085 stun_servers.insert(stun_address);
1086}
1087
1088PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1089 const std::string& username,
1090 const std::string& password)
1091 : stun_servers(stun_servers),
1092 username(username),
1093 password(password) {
1094 if (!stun_servers.empty())
1095 stun_address = *(stun_servers.begin());
1096}
1097
1098ServerAddresses PortConfiguration::StunServers() {
1099 if (!stun_address.IsNil() &&
1100 stun_servers.find(stun_address) == stun_servers.end()) {
1101 stun_servers.insert(stun_address);
1102 }
deadbeefc5d0d952015-07-16 10:22:21 -07001103 // Every UDP TURN server should also be used as a STUN server.
1104 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1105 for (const rtc::SocketAddress& turn_server : turn_servers) {
1106 if (stun_servers.find(turn_server) == stun_servers.end()) {
1107 stun_servers.insert(turn_server);
1108 }
1109 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001110 return stun_servers;
1111}
1112
1113void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1114 relays.push_back(config);
1115}
1116
1117bool PortConfiguration::SupportsProtocol(
1118 const RelayServerConfig& relay, ProtocolType type) const {
1119 PortList::const_iterator relay_port;
1120 for (relay_port = relay.ports.begin();
1121 relay_port != relay.ports.end();
1122 ++relay_port) {
1123 if (relay_port->proto == type)
1124 return true;
1125 }
1126 return false;
1127}
1128
1129bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1130 ProtocolType type) const {
1131 for (size_t i = 0; i < relays.size(); ++i) {
1132 if (relays[i].type == turn_type &&
1133 SupportsProtocol(relays[i], type))
1134 return true;
1135 }
1136 return false;
1137}
1138
1139ServerAddresses PortConfiguration::GetRelayServerAddresses(
1140 RelayType turn_type, ProtocolType type) const {
1141 ServerAddresses servers;
1142 for (size_t i = 0; i < relays.size(); ++i) {
1143 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1144 servers.insert(relays[i].ports.front().address);
1145 }
1146 }
1147 return servers;
1148}
1149
1150} // namespace cricket