blob: 14f7b13212db920adbfd7bc957eb1894ef798e8d [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
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000014#include <string>
15#include <vector>
16
17#include "webrtc/p2p/base/basicpacketsocketfactory.h"
18#include "webrtc/p2p/base/common.h"
19#include "webrtc/p2p/base/port.h"
20#include "webrtc/p2p/base/relayport.h"
21#include "webrtc/p2p/base/stunport.h"
22#include "webrtc/p2p/base/tcpport.h"
23#include "webrtc/p2p/base/turnport.h"
24#include "webrtc/p2p/base/udpport.h"
Guo-wei Shieh38f88932015-08-13 22:24:02 -070025#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000026#include "webrtc/base/common.h"
27#include "webrtc/base/helpers.h"
28#include "webrtc/base/logging.h"
29
30using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32namespace {
33
34enum {
35 MSG_CONFIG_START,
36 MSG_CONFIG_READY,
37 MSG_ALLOCATE,
38 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000039 MSG_SEQUENCEOBJECTS_CREATED,
40 MSG_CONFIG_STOP,
41};
42
43const int PHASE_UDP = 0;
44const int PHASE_RELAY = 1;
45const int PHASE_TCP = 2;
46const int PHASE_SSLTCP = 3;
47
48const int kNumPhases = 4;
49
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050} // namespace
51
52namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020053const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070054 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
55 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000056
57// BasicPortAllocator
Taylor Brandstettera1c30352016-05-13 08:15:11 -070058BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
59 rtc::PacketSocketFactory* socket_factory)
60 : network_manager_(network_manager), socket_factory_(socket_factory) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080061 ASSERT(network_manager_ != nullptr);
62 ASSERT(socket_factory_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063 Construct();
64}
65
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080066BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
Taylor Brandstettera1c30352016-05-13 08:15:11 -070067 : network_manager_(network_manager), socket_factory_(nullptr) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080068 ASSERT(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000069 Construct();
70}
71
Taylor Brandstettera1c30352016-05-13 08:15:11 -070072BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
73 rtc::PacketSocketFactory* socket_factory,
74 const ServerAddresses& stun_servers)
75 : network_manager_(network_manager), socket_factory_(socket_factory) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000076 ASSERT(socket_factory_ != NULL);
Taylor Brandstettera1c30352016-05-13 08:15:11 -070077 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000078 Construct();
79}
80
81BasicPortAllocator::BasicPortAllocator(
82 rtc::NetworkManager* network_manager,
83 const ServerAddresses& stun_servers,
84 const rtc::SocketAddress& relay_address_udp,
85 const rtc::SocketAddress& relay_address_tcp,
86 const rtc::SocketAddress& relay_address_ssl)
Taylor Brandstettera1c30352016-05-13 08:15:11 -070087 : network_manager_(network_manager), socket_factory_(NULL) {
88 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000089 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -080090 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -080092 }
93 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000094 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -080095 }
96 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -080098 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000099
deadbeef653b8e02015-11-11 12:55:10 -0800100 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700101 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800102 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000103
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700104 SetConfiguration(stun_servers, turn_servers, 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000105 Construct();
106}
107
108void BasicPortAllocator::Construct() {
109 allow_tcp_listen_ = true;
110}
111
112BasicPortAllocator::~BasicPortAllocator() {
113}
114
deadbeefc5d0d952015-07-16 10:22:21 -0700115PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000116 const std::string& content_name, int component,
117 const std::string& ice_ufrag, const std::string& ice_pwd) {
118 return new BasicPortAllocatorSession(
119 this, content_name, component, ice_ufrag, ice_pwd);
120}
121
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700122void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
123 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
124 new_turn_servers.push_back(turn_server);
125 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size());
126}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000127
128// BasicPortAllocatorSession
129BasicPortAllocatorSession::BasicPortAllocatorSession(
130 BasicPortAllocator *allocator,
131 const std::string& content_name,
132 int component,
133 const std::string& ice_ufrag,
134 const std::string& ice_pwd)
135 : PortAllocatorSession(content_name, component,
136 ice_ufrag, ice_pwd, allocator->flags()),
137 allocator_(allocator), network_thread_(NULL),
138 socket_factory_(allocator->socket_factory()),
139 allocation_started_(false),
140 network_manager_started_(false),
141 running_(false),
142 allocation_sequences_created_(false) {
143 allocator_->network_manager()->SignalNetworksChanged.connect(
144 this, &BasicPortAllocatorSession::OnNetworksChanged);
145 allocator_->network_manager()->StartUpdating();
146}
147
148BasicPortAllocatorSession::~BasicPortAllocatorSession() {
149 allocator_->network_manager()->StopUpdating();
150 if (network_thread_ != NULL)
151 network_thread_->Clear(this);
152
Peter Boström0c4e06b2015-10-07 12:23:21 +0200153 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 // AllocationSequence should clear it's map entry for turn ports before
155 // ports are destroyed.
156 sequences_[i]->Clear();
157 }
158
159 std::vector<PortData>::iterator it;
160 for (it = ports_.begin(); it != ports_.end(); it++)
161 delete it->port();
162
Peter Boström0c4e06b2015-10-07 12:23:21 +0200163 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000164 delete configs_[i];
165
Peter Boström0c4e06b2015-10-07 12:23:21 +0200166 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167 delete sequences_[i];
168}
169
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700170void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
171 if (filter == candidate_filter_) {
172 return;
173 }
174 // We assume the filter will only change from "ALL" to something else.
175 RTC_DCHECK(candidate_filter_ == CF_ALL);
176 candidate_filter_ = filter;
177 for (PortData& port : ports_) {
178 if (!port.has_pairable_candidate()) {
179 continue;
180 }
181 const auto& candidates = port.port()->Candidates();
182 // Setting a filter may cause a ready port to become non-ready
183 // if it no longer has any pairable candidates.
184 if (!std::any_of(candidates.begin(), candidates.end(),
185 [this, &port](const Candidate& candidate) {
186 return CandidatePairable(candidate, port.port());
187 })) {
188 port.set_has_pairable_candidate(false);
189 }
190 }
191}
192
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193void BasicPortAllocatorSession::StartGettingPorts() {
194 network_thread_ = rtc::Thread::Current();
195 if (!socket_factory_) {
196 owned_socket_factory_.reset(
197 new rtc::BasicPacketSocketFactory(network_thread_));
198 socket_factory_ = owned_socket_factory_.get();
199 }
200
201 running_ = true;
202 network_thread_->Post(this, MSG_CONFIG_START);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203}
204
205void BasicPortAllocatorSession::StopGettingPorts() {
206 ASSERT(rtc::Thread::Current() == network_thread_);
207 running_ = false;
honghaiz98db68f2015-09-29 07:58:17 -0700208 network_thread_->Post(this, MSG_CONFIG_STOP);
209 ClearGettingPorts();
210}
211
212void BasicPortAllocatorSession::ClearGettingPorts() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 network_thread_->Clear(this, MSG_ALLOCATE);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200214 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215 sequences_[i]->Stop();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216}
217
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700218std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
219 std::vector<PortInterface*> ret;
220 for (const PortData& port : ports_) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700221 if (port.has_pairable_candidate() && !port.error()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700222 ret.push_back(port.port());
223 }
224 }
225 return ret;
226}
227
228std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
229 std::vector<Candidate> candidates;
230 for (const PortData& data : ports_) {
231 for (const Candidate& candidate : data.port()->Candidates()) {
232 if (!CheckCandidateFilter(candidate)) {
233 continue;
234 }
235 ProtocolType pvalue;
236 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
237 !data.sequence()->ProtocolEnabled(pvalue)) {
238 continue;
239 }
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700240 candidates.push_back(SanitizeRelatedAddress(candidate));
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700241 }
242 }
243 return candidates;
244}
245
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700246Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
247 const Candidate& c) const {
248 Candidate copy = c;
249 // If adapter enumeration is disabled or host candidates are disabled,
250 // clear the raddr of STUN candidates to avoid local address leakage.
251 bool filter_stun_related_address =
252 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
253 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
254 !(candidate_filter_ & CF_HOST);
255 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
256 // to avoid reflexive address leakage.
257 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
258 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
259 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
260 copy.set_related_address(
261 rtc::EmptySocketAddressWithFamily(copy.address().family()));
262 }
263 return copy;
264}
265
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700266bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
267 // Done only if all required AllocationSequence objects
268 // are created.
269 if (!allocation_sequences_created_) {
270 return false;
271 }
272
273 // Check that all port allocation sequences are complete (not running).
274 if (std::any_of(sequences_.begin(), sequences_.end(),
275 [](const AllocationSequence* sequence) {
276 return sequence->state() == AllocationSequence::kRunning;
277 })) {
278 return false;
279 }
280
281 // If all allocated ports are in complete state, session must have got all
282 // expected candidates. Session will trigger candidates allocation complete
283 // signal.
284 if (!std::all_of(ports_.begin(), ports_.end(), [](const PortData& port) {
285 return (port.complete() || port.error());
286 })) {
287 return false;
288 }
289
290 return true;
291}
292
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000293void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
294 switch (message->message_id) {
295 case MSG_CONFIG_START:
296 ASSERT(rtc::Thread::Current() == network_thread_);
297 GetPortConfigurations();
298 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 case MSG_CONFIG_READY:
300 ASSERT(rtc::Thread::Current() == network_thread_);
301 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
302 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000303 case MSG_ALLOCATE:
304 ASSERT(rtc::Thread::Current() == network_thread_);
305 OnAllocate();
306 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000307 case MSG_SEQUENCEOBJECTS_CREATED:
308 ASSERT(rtc::Thread::Current() == network_thread_);
309 OnAllocationSequenceObjectsCreated();
310 break;
311 case MSG_CONFIG_STOP:
312 ASSERT(rtc::Thread::Current() == network_thread_);
313 OnConfigStop();
314 break;
315 default:
316 ASSERT(false);
317 }
318}
319
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700320void BasicPortAllocatorSession::UpdateIceParametersInternal() {
321 for (PortData& port : ports_) {
322 port.port()->set_content_name(content_name());
323 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
324 }
325}
326
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327void BasicPortAllocatorSession::GetPortConfigurations() {
328 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
329 username(),
330 password());
331
deadbeef653b8e02015-11-11 12:55:10 -0800332 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
333 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000334 }
335 ConfigReady(config);
336}
337
338void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
339 network_thread_->Post(this, MSG_CONFIG_READY, config);
340}
341
342// Adds a configuration to the list.
343void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800344 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000345 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800346 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000347
348 AllocatePorts();
349}
350
351void BasicPortAllocatorSession::OnConfigStop() {
352 ASSERT(rtc::Thread::Current() == network_thread_);
353
354 // If any of the allocated ports have not completed the candidates allocation,
355 // mark those as error. Since session doesn't need any new candidates
356 // at this stage of the allocation, it's safe to discard any new candidates.
357 bool send_signal = false;
358 for (std::vector<PortData>::iterator it = ports_.begin();
359 it != ports_.end(); ++it) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700360 if (!it->complete() && !it->error()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000361 // Updating port state to error, which didn't finish allocating candidates
362 // yet.
363 it->set_error();
364 send_signal = true;
365 }
366 }
367
368 // Did we stop any running sequences?
369 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
370 it != sequences_.end() && !send_signal; ++it) {
371 if ((*it)->state() == AllocationSequence::kStopped) {
372 send_signal = true;
373 }
374 }
375
376 // If we stopped anything that was running, send a done signal now.
377 if (send_signal) {
378 MaybeSignalCandidatesAllocationDone();
379 }
380}
381
382void BasicPortAllocatorSession::AllocatePorts() {
383 ASSERT(rtc::Thread::Current() == network_thread_);
384 network_thread_->Post(this, MSG_ALLOCATE);
385}
386
387void BasicPortAllocatorSession::OnAllocate() {
388 if (network_manager_started_)
389 DoAllocate();
390
391 allocation_started_ = true;
392}
393
honghaiz8c404fa2015-09-28 07:59:43 -0700394void BasicPortAllocatorSession::GetNetworks(
395 std::vector<rtc::Network*>* networks) {
396 networks->clear();
397 rtc::NetworkManager* network_manager = allocator_->network_manager();
398 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700399 // If the network permission state is BLOCKED, we just act as if the flag has
400 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700401 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700402 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700403 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
404 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000405 // If the adapter enumeration is disabled, we'll just bind to any address
406 // instead of specific NIC. This is to ensure the same routing for http
407 // traffic by OS is also used here to avoid any local or public IP leakage
408 // during stun process.
409 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
honghaiz8c404fa2015-09-28 07:59:43 -0700410 network_manager->GetAnyAddressNetworks(networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000411 } else {
honghaiz8c404fa2015-09-28 07:59:43 -0700412 network_manager->GetNetworks(networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000413 }
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800414 networks->erase(std::remove_if(networks->begin(), networks->end(),
415 [this](rtc::Network* network) {
416 return allocator_->network_ignore_mask() &
417 network->type();
418 }),
419 networks->end());
honghaiz8c404fa2015-09-28 07:59:43 -0700420}
421
422// For each network, see if we have a sequence that covers it already. If not,
423// create a new sequence to create the appropriate ports.
424void BasicPortAllocatorSession::DoAllocate() {
425 bool done_signal_needed = false;
426 std::vector<rtc::Network*> networks;
427 GetNetworks(&networks);
428
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000429 if (networks.empty()) {
430 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
431 done_signal_needed = true;
432 } else {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200433 for (uint32_t i = 0; i < networks.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000434 PortConfiguration* config = NULL;
435 if (configs_.size() > 0)
436 config = configs_.back();
437
Peter Boström0c4e06b2015-10-07 12:23:21 +0200438 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000439 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
440 // If all the ports are disabled we should just fire the allocation
441 // done event and return.
442 done_signal_needed = true;
443 break;
444 }
445
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446 if (!config || config->relays.empty()) {
447 // No relay ports specified in this config.
448 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
449 }
450
451 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000452 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 // Skip IPv6 networks unless the flag's been set.
454 continue;
455 }
456
457 // Disable phases that would only create ports equivalent to
458 // ones that we have already made.
459 DisableEquivalentPhases(networks[i], config, &sequence_flags);
460
461 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
462 // New AllocationSequence would have nothing to do, so don't make it.
463 continue;
464 }
465
466 AllocationSequence* sequence =
467 new AllocationSequence(this, networks[i], config, sequence_flags);
468 if (!sequence->Init()) {
469 delete sequence;
470 continue;
471 }
472 done_signal_needed = true;
473 sequence->SignalPortAllocationComplete.connect(
474 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
475 if (running_)
476 sequence->Start();
477 sequences_.push_back(sequence);
478 }
479 }
480 if (done_signal_needed) {
481 network_thread_->Post(this, MSG_SEQUENCEOBJECTS_CREATED);
482 }
483}
484
485void BasicPortAllocatorSession::OnNetworksChanged() {
honghaiz8c404fa2015-09-28 07:59:43 -0700486 std::vector<rtc::Network*> networks;
487 GetNetworks(&networks);
488 for (AllocationSequence* sequence : sequences_) {
489 // Remove the network from the allocation sequence if it is not in
490 // |networks|.
491 if (!sequence->network_removed() &&
492 std::find(networks.begin(), networks.end(), sequence->network()) ==
493 networks.end()) {
494 sequence->OnNetworkRemoved();
495 }
496 }
497
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000498 network_manager_started_ = true;
499 if (allocation_started_)
500 DoAllocate();
501}
502
503void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200504 rtc::Network* network,
505 PortConfiguration* config,
506 uint32_t* flags) {
507 for (uint32_t i = 0; i < sequences_.size() &&
508 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
509 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000510 sequences_[i]->DisableEquivalentPhases(network, config, flags);
511 }
512}
513
514void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
515 AllocationSequence * seq,
516 bool prepare_address) {
517 if (!port)
518 return;
519
520 LOG(LS_INFO) << "Adding allocated port for " << content_name();
521 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700522 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000523 port->set_generation(generation());
524 if (allocator_->proxy().type != rtc::PROXY_NONE)
525 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700526 port->set_send_retransmit_count_attribute(
527 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000528
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000529 PortData data(port, seq);
530 ports_.push_back(data);
531
532 port->SignalCandidateReady.connect(
533 this, &BasicPortAllocatorSession::OnCandidateReady);
534 port->SignalPortComplete.connect(this,
535 &BasicPortAllocatorSession::OnPortComplete);
536 port->SignalDestroyed.connect(this,
537 &BasicPortAllocatorSession::OnPortDestroyed);
538 port->SignalPortError.connect(
539 this, &BasicPortAllocatorSession::OnPortError);
540 LOG_J(LS_INFO, port) << "Added port to allocator";
541
542 if (prepare_address)
543 port->PrepareAddress();
544}
545
546void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
547 allocation_sequences_created_ = true;
548 // Send candidate allocation complete signal if we have no sequences.
549 MaybeSignalCandidatesAllocationDone();
550}
551
552void BasicPortAllocatorSession::OnCandidateReady(
553 Port* port, const Candidate& c) {
554 ASSERT(rtc::Thread::Current() == network_thread_);
555 PortData* data = FindPort(port);
556 ASSERT(data != NULL);
557 // Discarding any candidate signal if port allocation status is
558 // already in completed state.
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700559 if (data->complete() || data->error()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700561 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000562
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700564 bool candidate_protocol_enabled =
565 StringToProto(c.protocol().c_str(), &pvalue) &&
566 data->sequence()->ProtocolEnabled(pvalue);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700568 if (CheckCandidateFilter(c) && candidate_protocol_enabled) {
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700569 std::vector<Candidate> candidates;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700570 candidates.push_back(SanitizeRelatedAddress(c));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000571 SignalCandidatesReady(this, candidates);
572 }
573
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700574 // Port has already been marked as having a pairable candidate.
575 // Nothing to do here.
576 if (data->has_pairable_candidate()) {
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700577 return;
578 }
579
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700580 // Mark that the port has a pairable candidate, either because we have a
581 // usable candidate from the port, or simply because the port is bound to the
582 // any address and therefore has no host candidate. This will trigger the port
583 // to start creating candidate pairs (connections) and issue connectivity
584 // checks.
585 if (CandidatePairable(c, port)) {
586 data->set_has_pairable_candidate(true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 SignalPortReady(this, port);
588 }
589}
590
591void BasicPortAllocatorSession::OnPortComplete(Port* port) {
592 ASSERT(rtc::Thread::Current() == network_thread_);
593 PortData* data = FindPort(port);
594 ASSERT(data != NULL);
595
596 // Ignore any late signals.
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700597 if (data->complete() || data->error()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700599 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000600
601 // Moving to COMPLETE state.
602 data->set_complete();
603 // Send candidate allocation complete signal if this was the last port.
604 MaybeSignalCandidatesAllocationDone();
605}
606
607void BasicPortAllocatorSession::OnPortError(Port* port) {
608 ASSERT(rtc::Thread::Current() == network_thread_);
609 PortData* data = FindPort(port);
610 ASSERT(data != NULL);
611 // We might have already given up on this port and stopped it.
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700612 if (data->complete() || data->error()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700614 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000615
616 // SignalAddressError is currently sent from StunPort/TurnPort.
617 // But this signal itself is generic.
618 data->set_error();
619 // Send candidate allocation complete signal if this was the last port.
620 MaybeSignalCandidatesAllocationDone();
621}
622
623void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
624 ProtocolType proto) {
625 std::vector<Candidate> candidates;
626 for (std::vector<PortData>::iterator it = ports_.begin();
627 it != ports_.end(); ++it) {
628 if (it->sequence() != seq)
629 continue;
630
631 const std::vector<Candidate>& potentials = it->port()->Candidates();
632 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700633 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700635 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700637 bool candidate_protocol_enabled =
638 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
639 pvalue == proto;
640 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 candidates.push_back(potentials[i]);
642 }
643 }
644 }
645
646 if (!candidates.empty()) {
647 SignalCandidatesReady(this, candidates);
648 }
649}
650
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700651bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700652 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000653
654 // When binding to any address, before sending packets out, the getsockname
655 // returns all 0s, but after sending packets, it'll be the NIC used to
656 // send. All 0s is not a valid ICE candidate address and should be filtered
657 // out.
658 if (c.address().IsAnyIP()) {
659 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 }
661
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000662 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000663 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000664 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000665 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000666 } else if (c.type() == LOCAL_PORT_TYPE) {
667 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
668 // We allow host candidates if the filter allows server-reflexive
669 // candidates and the candidate is a public IP. Because we don't generate
670 // server-reflexive candidates if they have the same IP as the host
671 // candidate (i.e. when the host candidate is a public IP), filtering to
672 // only server-reflexive candidates won't work right when the host
673 // candidates have public IPs.
674 return true;
675 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000676
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000677 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000678 }
679 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680}
681
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700682bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
683 const Port* port) const {
684 bool candidate_signalable = CheckCandidateFilter(c);
685
686 // When device enumeration is disabled (to prevent non-default IP addresses
687 // from leaking), we ping from some local candidates even though we don't
688 // signal them. However, if host candidates are also disabled (for example, to
689 // prevent even default IP addresses from leaking), we still don't want to
690 // ping from them, even if device enumeration is disabled. Thus, we check for
691 // both device enumeration and host candidates being disabled.
692 bool network_enumeration_disabled = c.address().IsAnyIP();
693 bool can_ping_from_candidate =
694 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
695 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
696
697 return candidate_signalable ||
698 (network_enumeration_disabled && can_ping_from_candidate &&
699 !host_candidates_disabled);
700}
701
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702void BasicPortAllocatorSession::OnPortAllocationComplete(
703 AllocationSequence* seq) {
704 // Send candidate allocation complete signal if all ports are done.
705 MaybeSignalCandidatesAllocationDone();
706}
707
708void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700709 if (CandidatesAllocationDone()) {
710 if (pooled()) {
711 LOG(LS_INFO) << "All candidates gathered for pooled session.";
712 } else {
713 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
714 << component() << ":" << generation();
715 }
716 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000717 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000718}
719
720void BasicPortAllocatorSession::OnPortDestroyed(
721 PortInterface* port) {
722 ASSERT(rtc::Thread::Current() == network_thread_);
723 for (std::vector<PortData>::iterator iter = ports_.begin();
724 iter != ports_.end(); ++iter) {
725 if (port == iter->port()) {
726 ports_.erase(iter);
727 LOG_J(LS_INFO, port) << "Removed port from allocator ("
728 << static_cast<int>(ports_.size()) << " remaining)";
729 return;
730 }
731 }
732 ASSERT(false);
733}
734
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000735BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
736 Port* port) {
737 for (std::vector<PortData>::iterator it = ports_.begin();
738 it != ports_.end(); ++it) {
739 if (it->port() == port) {
740 return &*it;
741 }
742 }
743 return NULL;
744}
745
746// AllocationSequence
747
748AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
749 rtc::Network* network,
750 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200751 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000752 : session_(session),
753 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000754 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000755 config_(config),
756 state_(kInit),
757 flags_(flags),
758 udp_socket_(),
759 udp_port_(NULL),
760 phase_(0) {
761}
762
763bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000764 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
765 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
766 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
767 session_->allocator()->max_port()));
768 if (udp_socket_) {
769 udp_socket_->SignalReadPacket.connect(
770 this, &AllocationSequence::OnReadPacket);
771 }
772 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
773 // are next available options to setup a communication channel.
774 }
775 return true;
776}
777
778void AllocationSequence::Clear() {
779 udp_port_ = NULL;
780 turn_ports_.clear();
781}
782
honghaiz8c404fa2015-09-28 07:59:43 -0700783void AllocationSequence::OnNetworkRemoved() {
784 // Stop the allocation sequence if its network is gone.
785 Stop();
786 network_removed_ = true;
787}
788
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789AllocationSequence::~AllocationSequence() {
790 session_->network_thread()->Clear(this);
791}
792
793void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200794 PortConfiguration* config, uint32_t* flags) {
honghaiz8c404fa2015-09-28 07:59:43 -0700795 if (network_removed_) {
796 // If the network of this allocation sequence has ever gone away,
797 // it won't be equivalent to the new network.
798 return;
799 }
800
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000801 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 // Different network setup; nothing is equivalent.
803 return;
804 }
805
806 // Else turn off the stuff that we've already got covered.
807
808 // Every config implicitly specifies local, so turn that off right away.
809 *flags |= PORTALLOCATOR_DISABLE_UDP;
810 *flags |= PORTALLOCATOR_DISABLE_TCP;
811
812 if (config_ && config) {
813 if (config_->StunServers() == config->StunServers()) {
814 // Already got this STUN servers covered.
815 *flags |= PORTALLOCATOR_DISABLE_STUN;
816 }
817 if (!config_->relays.empty()) {
818 // Already got relays covered.
819 // NOTE: This will even skip a _different_ set of relay servers if we
820 // were to be given one, but that never happens in our codebase. Should
821 // probably get rid of the list in PortConfiguration and just keep a
822 // single relay server in each one.
823 *flags |= PORTALLOCATOR_DISABLE_RELAY;
824 }
825 }
826}
827
828void AllocationSequence::Start() {
829 state_ = kRunning;
830 session_->network_thread()->Post(this, MSG_ALLOCATION_PHASE);
831}
832
833void AllocationSequence::Stop() {
834 // If the port is completed, don't set it to stopped.
835 if (state_ == kRunning) {
836 state_ = kStopped;
837 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
838 }
839}
840
841void AllocationSequence::OnMessage(rtc::Message* msg) {
842 ASSERT(rtc::Thread::Current() == session_->network_thread());
843 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
844
845 const char* const PHASE_NAMES[kNumPhases] = {
846 "Udp", "Relay", "Tcp", "SslTcp"
847 };
848
849 // Perform all of the phases in the current step.
850 LOG_J(LS_INFO, network_) << "Allocation Phase="
851 << PHASE_NAMES[phase_];
852
853 switch (phase_) {
854 case PHASE_UDP:
855 CreateUDPPorts();
856 CreateStunPorts();
857 EnableProtocol(PROTO_UDP);
858 break;
859
860 case PHASE_RELAY:
861 CreateRelayPorts();
862 break;
863
864 case PHASE_TCP:
865 CreateTCPPorts();
866 EnableProtocol(PROTO_TCP);
867 break;
868
869 case PHASE_SSLTCP:
870 state_ = kCompleted;
871 EnableProtocol(PROTO_SSLTCP);
872 break;
873
874 default:
875 ASSERT(false);
876 }
877
878 if (state() == kRunning) {
879 ++phase_;
880 session_->network_thread()->PostDelayed(
881 session_->allocator()->step_delay(),
882 this, MSG_ALLOCATION_PHASE);
883 } else {
884 // If all phases in AllocationSequence are completed, no allocation
885 // steps needed further. Canceling pending signal.
886 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
887 SignalPortAllocationComplete(this);
888 }
889}
890
891void AllocationSequence::EnableProtocol(ProtocolType proto) {
892 if (!ProtocolEnabled(proto)) {
893 protocols_.push_back(proto);
894 session_->OnProtocolEnabled(this, proto);
895 }
896}
897
898bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
899 for (ProtocolList::const_iterator it = protocols_.begin();
900 it != protocols_.end(); ++it) {
901 if (*it == proto)
902 return true;
903 }
904 return false;
905}
906
907void AllocationSequence::CreateUDPPorts() {
908 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
909 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
910 return;
911 }
912
913 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
914 // is enabled completely.
915 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800916 bool emit_local_candidate_for_anyaddress =
917 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000918 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700919 port = UDPPort::Create(
920 session_->network_thread(), session_->socket_factory(), network_,
921 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800922 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000923 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -0700924 port = UDPPort::Create(
925 session_->network_thread(), session_->socket_factory(), network_, ip_,
926 session_->allocator()->min_port(), session_->allocator()->max_port(),
927 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -0800928 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929 }
930
931 if (port) {
932 // If shared socket is enabled, STUN candidate will be allocated by the
933 // UDPPort.
934 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
935 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +0000936 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000937
938 // If STUN is not disabled, setting stun server address to port.
939 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940 if (config_ && !config_->StunServers().empty()) {
941 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
942 << "STUN candidate generation.";
943 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000944 }
945 }
946 }
947
948 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 }
950}
951
952void AllocationSequence::CreateTCPPorts() {
953 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
954 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
955 return;
956 }
957
958 Port* port = TCPPort::Create(session_->network_thread(),
959 session_->socket_factory(),
960 network_, ip_,
961 session_->allocator()->min_port(),
962 session_->allocator()->max_port(),
963 session_->username(), session_->password(),
964 session_->allocator()->allow_tcp_listen());
965 if (port) {
966 session_->AddAllocatedPort(port, this, true);
967 // Since TCPPort is not created using shared socket, |port| will not be
968 // added to the dequeue.
969 }
970}
971
972void AllocationSequence::CreateStunPorts() {
973 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
974 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
975 return;
976 }
977
978 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
979 return;
980 }
981
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000982 if (!(config_ && !config_->StunServers().empty())) {
983 LOG(LS_WARNING)
984 << "AllocationSequence: No STUN server configured, skipping.";
985 return;
986 }
987
988 StunPort* port = StunPort::Create(session_->network_thread(),
989 session_->socket_factory(),
990 network_, ip_,
991 session_->allocator()->min_port(),
992 session_->allocator()->max_port(),
993 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000994 config_->StunServers(),
995 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000996 if (port) {
997 session_->AddAllocatedPort(port, this, true);
998 // Since StunPort is not created using shared socket, |port| will not be
999 // added to the dequeue.
1000 }
1001}
1002
1003void AllocationSequence::CreateRelayPorts() {
1004 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1005 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1006 return;
1007 }
1008
1009 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1010 // ought to have a relay list for them here.
1011 ASSERT(config_ && !config_->relays.empty());
1012 if (!(config_ && !config_->relays.empty())) {
1013 LOG(LS_WARNING)
1014 << "AllocationSequence: No relay server configured, skipping.";
1015 return;
1016 }
1017
1018 PortConfiguration::RelayList::const_iterator relay;
1019 for (relay = config_->relays.begin();
1020 relay != config_->relays.end(); ++relay) {
1021 if (relay->type == RELAY_GTURN) {
1022 CreateGturnPort(*relay);
1023 } else if (relay->type == RELAY_TURN) {
1024 CreateTurnPort(*relay);
1025 } else {
1026 ASSERT(false);
1027 }
1028 }
1029}
1030
1031void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1032 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1033 RelayPort* port = RelayPort::Create(session_->network_thread(),
1034 session_->socket_factory(),
1035 network_, ip_,
1036 session_->allocator()->min_port(),
1037 session_->allocator()->max_port(),
1038 config_->username, config_->password);
1039 if (port) {
1040 // Since RelayPort is not created using shared socket, |port| will not be
1041 // added to the dequeue.
1042 // Note: We must add the allocated port before we add addresses because
1043 // the latter will create candidates that need name and preference
1044 // settings. However, we also can't prepare the address (normally
1045 // done by AddAllocatedPort) until we have these addresses. So we
1046 // wait to do that until below.
1047 session_->AddAllocatedPort(port, this, false);
1048
1049 // Add the addresses of this protocol.
1050 PortList::const_iterator relay_port;
1051 for (relay_port = config.ports.begin();
1052 relay_port != config.ports.end();
1053 ++relay_port) {
1054 port->AddServerAddress(*relay_port);
1055 port->AddExternalAddress(*relay_port);
1056 }
1057 // Start fetching an address for this port.
1058 port->PrepareAddress();
1059 }
1060}
1061
1062void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1063 PortList::const_iterator relay_port;
1064 for (relay_port = config.ports.begin();
1065 relay_port != config.ports.end(); ++relay_port) {
1066 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001067
1068 // Skip UDP connections to relay servers if it's disallowed.
1069 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1070 relay_port->proto == PROTO_UDP) {
1071 continue;
1072 }
1073
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001074 // Shared socket mode must be enabled only for UDP based ports. Hence
1075 // don't pass shared socket for ports which will create TCP sockets.
1076 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1077 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1078 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001079 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080 port = TurnPort::Create(session_->network_thread(),
1081 session_->socket_factory(),
1082 network_, udp_socket_.get(),
1083 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001084 *relay_port, config.credentials, config.priority,
1085 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086 turn_ports_.push_back(port);
1087 // Listen to the port destroyed signal, to allow AllocationSequence to
1088 // remove entrt from it's map.
1089 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1090 } else {
1091 port = TurnPort::Create(session_->network_thread(),
1092 session_->socket_factory(),
1093 network_, ip_,
1094 session_->allocator()->min_port(),
1095 session_->allocator()->max_port(),
1096 session_->username(),
1097 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001098 *relay_port, config.credentials, config.priority,
1099 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001100 }
1101 ASSERT(port != NULL);
1102 session_->AddAllocatedPort(port, this, true);
1103 }
1104}
1105
1106void AllocationSequence::OnReadPacket(
1107 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1108 const rtc::SocketAddress& remote_addr,
1109 const rtc::PacketTime& packet_time) {
1110 ASSERT(socket == udp_socket_.get());
1111
1112 bool turn_port_found = false;
1113
1114 // Try to find the TurnPort that matches the remote address. Note that the
1115 // message could be a STUN binding response if the TURN server is also used as
1116 // a STUN server. We don't want to parse every message here to check if it is
1117 // a STUN binding response, so we pass the message to TurnPort regardless of
1118 // the message type. The TurnPort will just ignore the message since it will
1119 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001120 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001122 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1123 packet_time)) {
1124 return;
1125 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001126 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001127 }
1128 }
1129
1130 if (udp_port_) {
1131 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1132
1133 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1134 // the TURN server is also a STUN server.
1135 if (!turn_port_found ||
1136 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001137 RTC_DCHECK(udp_port_->SharedSocket());
1138 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1139 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001140 }
1141 }
1142}
1143
1144void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1145 if (udp_port_ == port) {
1146 udp_port_ = NULL;
1147 return;
1148 }
1149
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001150 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1151 if (it != turn_ports_.end()) {
1152 turn_ports_.erase(it);
1153 } else {
1154 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1155 ASSERT(false);
1156 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001157}
1158
1159// PortConfiguration
1160PortConfiguration::PortConfiguration(
1161 const rtc::SocketAddress& stun_address,
1162 const std::string& username,
1163 const std::string& password)
1164 : stun_address(stun_address), username(username), password(password) {
1165 if (!stun_address.IsNil())
1166 stun_servers.insert(stun_address);
1167}
1168
1169PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1170 const std::string& username,
1171 const std::string& password)
1172 : stun_servers(stun_servers),
1173 username(username),
1174 password(password) {
1175 if (!stun_servers.empty())
1176 stun_address = *(stun_servers.begin());
1177}
1178
1179ServerAddresses PortConfiguration::StunServers() {
1180 if (!stun_address.IsNil() &&
1181 stun_servers.find(stun_address) == stun_servers.end()) {
1182 stun_servers.insert(stun_address);
1183 }
deadbeefc5d0d952015-07-16 10:22:21 -07001184 // Every UDP TURN server should also be used as a STUN server.
1185 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1186 for (const rtc::SocketAddress& turn_server : turn_servers) {
1187 if (stun_servers.find(turn_server) == stun_servers.end()) {
1188 stun_servers.insert(turn_server);
1189 }
1190 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191 return stun_servers;
1192}
1193
1194void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1195 relays.push_back(config);
1196}
1197
1198bool PortConfiguration::SupportsProtocol(
1199 const RelayServerConfig& relay, ProtocolType type) const {
1200 PortList::const_iterator relay_port;
1201 for (relay_port = relay.ports.begin();
1202 relay_port != relay.ports.end();
1203 ++relay_port) {
1204 if (relay_port->proto == type)
1205 return true;
1206 }
1207 return false;
1208}
1209
1210bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1211 ProtocolType type) const {
1212 for (size_t i = 0; i < relays.size(); ++i) {
1213 if (relays[i].type == turn_type &&
1214 SupportsProtocol(relays[i], type))
1215 return true;
1216 }
1217 return false;
1218}
1219
1220ServerAddresses PortConfiguration::GetRelayServerAddresses(
1221 RelayType turn_type, ProtocolType type) const {
1222 ServerAddresses servers;
1223 for (size_t i = 0; i < relays.size(); ++i) {
1224 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1225 servers.insert(relays[i].ports.front().address);
1226 }
1227 }
1228 return servers;
1229}
1230
1231} // namespace cricket