blob: 3a7aa5a33340d1118a2b96c2acb33ec88254e094 [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
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070050// Gets protocol priority: UDP > TCP > SSLTCP.
51int GetProtocolPriority(cricket::ProtocolType protocol) {
52 switch (protocol) {
53 case cricket::PROTO_UDP:
54 return 2;
55 case cricket::PROTO_TCP:
56 return 1;
57 case cricket::PROTO_SSLTCP:
58 return 0;
59 default:
60 RTC_DCHECK(false);
61 return 0;
62 }
63}
64// Gets address family priority: IPv6 > IPv4 > Unspecified.
65int GetAddressFamilyPriority(int ip_family) {
66 switch (ip_family) {
67 case AF_INET6:
68 return 2;
69 case AF_INET:
70 return 1;
71 default:
72 RTC_DCHECK(false);
73 return 0;
74 }
75}
76
77// Returns positive if a is better, negative if b is better, and 0 otherwise.
78int ComparePort(const cricket::Port* a, const cricket::Port* b) {
79 int a_protocol = GetProtocolPriority(a->GetProtocol());
80 int b_protocol = GetProtocolPriority(b->GetProtocol());
81 int cmp_protocol = a_protocol - b_protocol;
82 if (cmp_protocol != 0) {
83 return cmp_protocol;
84 }
85
86 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
87 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
88 return a_family - b_family;
89}
90
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091} // namespace
92
93namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020094const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070095 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
96 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097
98// BasicPortAllocator
Taylor Brandstettera1c30352016-05-13 08:15:11 -070099BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
100 rtc::PacketSocketFactory* socket_factory)
101 : network_manager_(network_manager), socket_factory_(socket_factory) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800102 ASSERT(network_manager_ != nullptr);
103 ASSERT(socket_factory_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000104 Construct();
105}
106
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800107BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700108 : network_manager_(network_manager), socket_factory_(nullptr) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800109 ASSERT(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110 Construct();
111}
112
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700113BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
114 rtc::PacketSocketFactory* socket_factory,
115 const ServerAddresses& stun_servers)
116 : network_manager_(network_manager), socket_factory_(socket_factory) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000117 ASSERT(socket_factory_ != NULL);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700118 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119 Construct();
120}
121
122BasicPortAllocator::BasicPortAllocator(
123 rtc::NetworkManager* network_manager,
124 const ServerAddresses& stun_servers,
125 const rtc::SocketAddress& relay_address_udp,
126 const rtc::SocketAddress& relay_address_tcp,
127 const rtc::SocketAddress& relay_address_ssl)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700128 : network_manager_(network_manager), socket_factory_(NULL) {
129 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800131 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800133 }
134 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800136 }
137 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800139 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140
deadbeef653b8e02015-11-11 12:55:10 -0800141 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700142 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800143 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000144
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700145 SetConfiguration(stun_servers, turn_servers, 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 Construct();
147}
148
149void BasicPortAllocator::Construct() {
150 allow_tcp_listen_ = true;
151}
152
153BasicPortAllocator::~BasicPortAllocator() {
154}
155
deadbeefc5d0d952015-07-16 10:22:21 -0700156PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 const std::string& content_name, int component,
158 const std::string& ice_ufrag, const std::string& ice_pwd) {
159 return new BasicPortAllocatorSession(
160 this, content_name, component, ice_ufrag, ice_pwd);
161}
162
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700163void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
164 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
165 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700166 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
167 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700168}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169
170// BasicPortAllocatorSession
171BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700172 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 const std::string& content_name,
174 int component,
175 const std::string& ice_ufrag,
176 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700177 : PortAllocatorSession(content_name,
178 component,
179 ice_ufrag,
180 ice_pwd,
181 allocator->flags()),
182 allocator_(allocator),
183 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 socket_factory_(allocator->socket_factory()),
185 allocation_started_(false),
186 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700187 allocation_sequences_created_(false),
188 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 allocator_->network_manager()->SignalNetworksChanged.connect(
190 this, &BasicPortAllocatorSession::OnNetworksChanged);
191 allocator_->network_manager()->StartUpdating();
192}
193
194BasicPortAllocatorSession::~BasicPortAllocatorSession() {
195 allocator_->network_manager()->StopUpdating();
196 if (network_thread_ != NULL)
197 network_thread_->Clear(this);
198
Peter Boström0c4e06b2015-10-07 12:23:21 +0200199 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 // AllocationSequence should clear it's map entry for turn ports before
201 // ports are destroyed.
202 sequences_[i]->Clear();
203 }
204
205 std::vector<PortData>::iterator it;
206 for (it = ports_.begin(); it != ports_.end(); it++)
207 delete it->port();
208
Peter Boström0c4e06b2015-10-07 12:23:21 +0200209 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210 delete configs_[i];
211
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 delete sequences_[i];
214}
215
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700216void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
217 if (filter == candidate_filter_) {
218 return;
219 }
220 // We assume the filter will only change from "ALL" to something else.
221 RTC_DCHECK(candidate_filter_ == CF_ALL);
222 candidate_filter_ = filter;
223 for (PortData& port : ports_) {
224 if (!port.has_pairable_candidate()) {
225 continue;
226 }
227 const auto& candidates = port.port()->Candidates();
228 // Setting a filter may cause a ready port to become non-ready
229 // if it no longer has any pairable candidates.
230 if (!std::any_of(candidates.begin(), candidates.end(),
231 [this, &port](const Candidate& candidate) {
232 return CandidatePairable(candidate, port.port());
233 })) {
234 port.set_has_pairable_candidate(false);
235 }
236 }
237}
238
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239void BasicPortAllocatorSession::StartGettingPorts() {
240 network_thread_ = rtc::Thread::Current();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700241 PortAllocatorSession::StartGettingPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242 if (!socket_factory_) {
243 owned_socket_factory_.reset(
244 new rtc::BasicPacketSocketFactory(network_thread_));
245 socket_factory_ = owned_socket_factory_.get();
246 }
247
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700248 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000249}
250
251void BasicPortAllocatorSession::StopGettingPorts() {
252 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700253 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
honghaiz98db68f2015-09-29 07:58:17 -0700254 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700255 // Note: this must be called after ClearGettingPorts because both may set the
256 // session state and we should set the state to STOPPED.
257 PortAllocatorSession::StopGettingPorts();
honghaiz98db68f2015-09-29 07:58:17 -0700258}
259
260void BasicPortAllocatorSession::ClearGettingPorts() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700261 ASSERT(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000262 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700263 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700265 }
266 PortAllocatorSession::ClearGettingPorts();
267}
268
269std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
270 std::vector<rtc::Network*> networks = GetNetworks();
271
272 // A network interface may have both IPv4 and IPv6 networks. Only if
273 // neither of the networks has any connections, the network interface
274 // is considered failed and need to be regathered on.
275 std::set<std::string> networks_with_connection;
276 for (const PortData& data : ports_) {
277 Port* port = data.port();
278 if (!port->connections().empty()) {
279 networks_with_connection.insert(port->Network()->name());
280 }
281 }
282
283 networks.erase(
284 std::remove_if(networks.begin(), networks.end(),
285 [networks_with_connection](rtc::Network* network) {
286 // If a network does not have any connection, it is
287 // considered failed.
288 return networks_with_connection.find(network->name()) !=
289 networks_with_connection.end();
290 }),
291 networks.end());
292 return networks;
293}
294
295void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
296 // Find the list of networks that have no connection.
297 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
298 if (failed_networks.empty()) {
299 return;
300 }
301
302 // Mark a sequence as "network failed" if its network is in the list of failed
303 // networks, so that it won't be considered as equivalent when the session
304 // regathers ports and candidates.
305 for (AllocationSequence* sequence : sequences_) {
306 if (!sequence->network_failed() &&
307 std::find(failed_networks.begin(), failed_networks.end(),
308 sequence->network()) != failed_networks.end()) {
309 sequence->set_network_failed();
310 }
311 }
312 // Remove ports from being used locally and send signaling to remove
313 // the candidates on the remote side.
314 RemovePortsAndCandidates(failed_networks);
315
316 if (allocation_started_ && network_manager_started_) {
317 DoAllocate();
318 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319}
320
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700321std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
322 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700323 for (const PortData& data : ports_) {
324 if (data.ready()) {
325 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700326 }
327 }
328 return ret;
329}
330
331std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
332 std::vector<Candidate> candidates;
333 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700334 if (!data.ready()) {
335 continue;
336 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700337 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700338 }
339 return candidates;
340}
341
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700342void BasicPortAllocatorSession::GetCandidatesFromPort(
343 const PortData& data,
344 std::vector<Candidate>* candidates) const {
345 RTC_CHECK(candidates != nullptr);
346 for (const Candidate& candidate : data.port()->Candidates()) {
347 if (!CheckCandidateFilter(candidate)) {
348 continue;
349 }
350 ProtocolType pvalue;
351 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
352 !data.sequence()->ProtocolEnabled(pvalue)) {
353 continue;
354 }
355 candidates->push_back(SanitizeRelatedAddress(candidate));
356 }
357}
358
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700359Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
360 const Candidate& c) const {
361 Candidate copy = c;
362 // If adapter enumeration is disabled or host candidates are disabled,
363 // clear the raddr of STUN candidates to avoid local address leakage.
364 bool filter_stun_related_address =
365 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
366 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
367 !(candidate_filter_ & CF_HOST);
368 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
369 // to avoid reflexive address leakage.
370 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
371 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
372 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
373 copy.set_related_address(
374 rtc::EmptySocketAddressWithFamily(copy.address().family()));
375 }
376 return copy;
377}
378
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700379bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
380 // Done only if all required AllocationSequence objects
381 // are created.
382 if (!allocation_sequences_created_) {
383 return false;
384 }
385
386 // Check that all port allocation sequences are complete (not running).
387 if (std::any_of(sequences_.begin(), sequences_.end(),
388 [](const AllocationSequence* sequence) {
389 return sequence->state() == AllocationSequence::kRunning;
390 })) {
391 return false;
392 }
393
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700394 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700395 // expected candidates. Session will trigger candidates allocation complete
396 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700397 return std::none_of(ports_.begin(), ports_.end(),
398 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700399}
400
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
402 switch (message->message_id) {
403 case MSG_CONFIG_START:
404 ASSERT(rtc::Thread::Current() == network_thread_);
405 GetPortConfigurations();
406 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000407 case MSG_CONFIG_READY:
408 ASSERT(rtc::Thread::Current() == network_thread_);
409 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
410 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000411 case MSG_ALLOCATE:
412 ASSERT(rtc::Thread::Current() == network_thread_);
413 OnAllocate();
414 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000415 case MSG_SEQUENCEOBJECTS_CREATED:
416 ASSERT(rtc::Thread::Current() == network_thread_);
417 OnAllocationSequenceObjectsCreated();
418 break;
419 case MSG_CONFIG_STOP:
420 ASSERT(rtc::Thread::Current() == network_thread_);
421 OnConfigStop();
422 break;
423 default:
424 ASSERT(false);
425 }
426}
427
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700428void BasicPortAllocatorSession::UpdateIceParametersInternal() {
429 for (PortData& port : ports_) {
430 port.port()->set_content_name(content_name());
431 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
432 }
433}
434
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435void BasicPortAllocatorSession::GetPortConfigurations() {
436 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
437 username(),
438 password());
439
deadbeef653b8e02015-11-11 12:55:10 -0800440 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
441 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 }
443 ConfigReady(config);
444}
445
446void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700447 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448}
449
450// Adds a configuration to the list.
451void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800452 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800454 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000455
456 AllocatePorts();
457}
458
459void BasicPortAllocatorSession::OnConfigStop() {
460 ASSERT(rtc::Thread::Current() == network_thread_);
461
462 // If any of the allocated ports have not completed the candidates allocation,
463 // mark those as error. Since session doesn't need any new candidates
464 // at this stage of the allocation, it's safe to discard any new candidates.
465 bool send_signal = false;
466 for (std::vector<PortData>::iterator it = ports_.begin();
467 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700468 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469 // Updating port state to error, which didn't finish allocating candidates
470 // yet.
471 it->set_error();
472 send_signal = true;
473 }
474 }
475
476 // Did we stop any running sequences?
477 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
478 it != sequences_.end() && !send_signal; ++it) {
479 if ((*it)->state() == AllocationSequence::kStopped) {
480 send_signal = true;
481 }
482 }
483
484 // If we stopped anything that was running, send a done signal now.
485 if (send_signal) {
486 MaybeSignalCandidatesAllocationDone();
487 }
488}
489
490void BasicPortAllocatorSession::AllocatePorts() {
491 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700492 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000493}
494
495void BasicPortAllocatorSession::OnAllocate() {
496 if (network_manager_started_)
497 DoAllocate();
498
499 allocation_started_ = true;
500}
501
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700502std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
503 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700504 rtc::NetworkManager* network_manager = allocator_->network_manager();
505 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700506 // If the network permission state is BLOCKED, we just act as if the flag has
507 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700508 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700509 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700510 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
511 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000512 // If the adapter enumeration is disabled, we'll just bind to any address
513 // instead of specific NIC. This is to ensure the same routing for http
514 // traffic by OS is also used here to avoid any local or public IP leakage
515 // during stun process.
516 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700517 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000518 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700519 network_manager->GetNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000520 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700521 networks.erase(std::remove_if(networks.begin(), networks.end(),
522 [this](rtc::Network* network) {
523 return allocator_->network_ignore_mask() &
524 network->type();
525 }),
526 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700527
528 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
529 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700530 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700531 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
532 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700533 networks.erase(std::remove_if(networks.begin(), networks.end(),
534 [lowest_cost](rtc::Network* network) {
535 return network->GetCost() >
536 lowest_cost + rtc::kNetworkCostLow;
537 }),
538 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700539 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700540 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700541}
542
543// For each network, see if we have a sequence that covers it already. If not,
544// create a new sequence to create the appropriate ports.
545void BasicPortAllocatorSession::DoAllocate() {
546 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700547 std::vector<rtc::Network*> networks = GetNetworks();
honghaiz8c404fa2015-09-28 07:59:43 -0700548
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549 if (networks.empty()) {
550 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
551 done_signal_needed = true;
552 } else {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700553 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200554 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200555 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
557 // If all the ports are disabled we should just fire the allocation
558 // done event and return.
559 done_signal_needed = true;
560 break;
561 }
562
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000563 if (!config || config->relays.empty()) {
564 // No relay ports specified in this config.
565 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
566 }
567
568 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000570 // Skip IPv6 networks unless the flag's been set.
571 continue;
572 }
573
574 // Disable phases that would only create ports equivalent to
575 // ones that we have already made.
576 DisableEquivalentPhases(networks[i], config, &sequence_flags);
577
578 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
579 // New AllocationSequence would have nothing to do, so don't make it.
580 continue;
581 }
582
583 AllocationSequence* sequence =
584 new AllocationSequence(this, networks[i], config, sequence_flags);
585 if (!sequence->Init()) {
586 delete sequence;
587 continue;
588 }
589 done_signal_needed = true;
590 sequence->SignalPortAllocationComplete.connect(
591 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700592 if (!IsStopped()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000593 sequence->Start();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700594 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595 sequences_.push_back(sequence);
596 }
597 }
598 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700599 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000600 }
601}
602
603void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700604 std::vector<rtc::Network*> networks = GetNetworks();
605 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700606 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700607 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700608 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700609 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700610 std::find(networks.begin(), networks.end(), sequence->network()) ==
611 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700612 sequence->OnNetworkFailed();
613 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700614 }
615 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700616 RemovePortsAndCandidates(failed_networks);
honghaiz8c404fa2015-09-28 07:59:43 -0700617
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000618 network_manager_started_ = true;
619 if (allocation_started_)
620 DoAllocate();
621}
622
623void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200624 rtc::Network* network,
625 PortConfiguration* config,
626 uint32_t* flags) {
627 for (uint32_t i = 0; i < sequences_.size() &&
628 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
629 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000630 sequences_[i]->DisableEquivalentPhases(network, config, flags);
631 }
632}
633
634void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
635 AllocationSequence * seq,
636 bool prepare_address) {
637 if (!port)
638 return;
639
640 LOG(LS_INFO) << "Adding allocated port for " << content_name();
641 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700642 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000643 port->set_generation(generation());
644 if (allocator_->proxy().type != rtc::PROXY_NONE)
645 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700646 port->set_send_retransmit_count_attribute(
647 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000648
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000649 PortData data(port, seq);
650 ports_.push_back(data);
651
652 port->SignalCandidateReady.connect(
653 this, &BasicPortAllocatorSession::OnCandidateReady);
654 port->SignalPortComplete.connect(this,
655 &BasicPortAllocatorSession::OnPortComplete);
656 port->SignalDestroyed.connect(this,
657 &BasicPortAllocatorSession::OnPortDestroyed);
658 port->SignalPortError.connect(
659 this, &BasicPortAllocatorSession::OnPortError);
660 LOG_J(LS_INFO, port) << "Added port to allocator";
661
662 if (prepare_address)
663 port->PrepareAddress();
664}
665
666void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
667 allocation_sequences_created_ = true;
668 // Send candidate allocation complete signal if we have no sequences.
669 MaybeSignalCandidatesAllocationDone();
670}
671
672void BasicPortAllocatorSession::OnCandidateReady(
673 Port* port, const Candidate& c) {
674 ASSERT(rtc::Thread::Current() == network_thread_);
675 PortData* data = FindPort(port);
676 ASSERT(data != NULL);
677 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700678 // already done with gathering.
679 if (!data->inprogress()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700680 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700681 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700682
danilchapf4e8cf02016-06-30 01:55:03 -0700683 // Mark that the port has a pairable candidate, either because we have a
684 // usable candidate from the port, or simply because the port is bound to the
685 // any address and therefore has no host candidate. This will trigger the port
686 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700687 // checks. If port has already been marked as having a pairable candidate,
688 // do nothing here.
689 // Note: We should check whether any candidates may become ready after this
690 // because there we will check whether the candidate is generated by the ready
691 // ports, which may include this port.
692 bool pruned_port = false;
693 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700694 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700695
696 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
697 pruned_port = PruneTurnPorts(port);
698 }
699 // If the current port is not pruned yet, SignalPortReady.
700 if (!data->pruned()) {
701 SignalPortReady(this, port);
702 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700703 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700704
705 ProtocolType pvalue;
706 bool candidate_protocol_enabled =
707 StringToProto(c.protocol().c_str(), &pvalue) &&
708 data->sequence()->ProtocolEnabled(pvalue);
709
710 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
711 std::vector<Candidate> candidates;
712 candidates.push_back(SanitizeRelatedAddress(c));
713 SignalCandidatesReady(this, candidates);
714 }
715
716 // If we have pruned any port, maybe need to signal port allocation done.
717 if (pruned_port) {
718 MaybeSignalCandidatesAllocationDone();
719 }
720}
721
722Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
723 const std::string& network_name) const {
724 Port* best_turn_port = nullptr;
725 for (const PortData& data : ports_) {
726 if (data.port()->Network()->name() == network_name &&
727 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
728 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
729 best_turn_port = data.port();
730 }
731 }
732 return best_turn_port;
733}
734
735bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
736 bool pruned_port = false;
737 // Note: We determine the same network based only on their network names. So
738 // if an IPv4 address and an IPv6 address have the same network name, they
739 // are considered the same network here.
740 const std::string& network_name = newly_pairable_turn_port->Network()->name();
741 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
742 // |port| is already in the list of ports, so the best port cannot be nullptr.
743 RTC_CHECK(best_turn_port != nullptr);
744
745 for (PortData& data : ports_) {
746 if (data.port()->Network()->name() == network_name &&
747 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
748 ComparePort(data.port(), best_turn_port) < 0) {
749 data.set_pruned();
750 pruned_port = true;
751 if (data.port() != newly_pairable_turn_port) {
752 SignalPortPruned(this, data.port());
753 }
754 }
755 }
756 return pruned_port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000757}
758
759void BasicPortAllocatorSession::OnPortComplete(Port* port) {
760 ASSERT(rtc::Thread::Current() == network_thread_);
761 PortData* data = FindPort(port);
762 ASSERT(data != NULL);
763
764 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700765 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000766 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700767 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000768
769 // Moving to COMPLETE state.
770 data->set_complete();
771 // Send candidate allocation complete signal if this was the last port.
772 MaybeSignalCandidatesAllocationDone();
773}
774
775void BasicPortAllocatorSession::OnPortError(Port* port) {
776 ASSERT(rtc::Thread::Current() == network_thread_);
777 PortData* data = FindPort(port);
778 ASSERT(data != NULL);
779 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700780 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000781 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700782 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000783
784 // SignalAddressError is currently sent from StunPort/TurnPort.
785 // But this signal itself is generic.
786 data->set_error();
787 // Send candidate allocation complete signal if this was the last port.
788 MaybeSignalCandidatesAllocationDone();
789}
790
791void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
792 ProtocolType proto) {
793 std::vector<Candidate> candidates;
794 for (std::vector<PortData>::iterator it = ports_.begin();
795 it != ports_.end(); ++it) {
796 if (it->sequence() != seq)
797 continue;
798
799 const std::vector<Candidate>& potentials = it->port()->Candidates();
800 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700801 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700803 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000804 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700805 bool candidate_protocol_enabled =
806 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
807 pvalue == proto;
808 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000809 candidates.push_back(potentials[i]);
810 }
811 }
812 }
813
814 if (!candidates.empty()) {
815 SignalCandidatesReady(this, candidates);
816 }
817}
818
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700819bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700820 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000821
822 // When binding to any address, before sending packets out, the getsockname
823 // returns all 0s, but after sending packets, it'll be the NIC used to
824 // send. All 0s is not a valid ICE candidate address and should be filtered
825 // out.
826 if (c.address().IsAnyIP()) {
827 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000828 }
829
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000830 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000831 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000832 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000833 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000834 } else if (c.type() == LOCAL_PORT_TYPE) {
835 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
836 // We allow host candidates if the filter allows server-reflexive
837 // candidates and the candidate is a public IP. Because we don't generate
838 // server-reflexive candidates if they have the same IP as the host
839 // candidate (i.e. when the host candidate is a public IP), filtering to
840 // only server-reflexive candidates won't work right when the host
841 // candidates have public IPs.
842 return true;
843 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000845 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000846 }
847 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848}
849
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700850bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
851 const Port* port) const {
852 bool candidate_signalable = CheckCandidateFilter(c);
853
854 // When device enumeration is disabled (to prevent non-default IP addresses
855 // from leaking), we ping from some local candidates even though we don't
856 // signal them. However, if host candidates are also disabled (for example, to
857 // prevent even default IP addresses from leaking), we still don't want to
858 // ping from them, even if device enumeration is disabled. Thus, we check for
859 // both device enumeration and host candidates being disabled.
860 bool network_enumeration_disabled = c.address().IsAnyIP();
861 bool can_ping_from_candidate =
862 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
863 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
864
865 return candidate_signalable ||
866 (network_enumeration_disabled && can_ping_from_candidate &&
867 !host_candidates_disabled);
868}
869
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870void BasicPortAllocatorSession::OnPortAllocationComplete(
871 AllocationSequence* seq) {
872 // Send candidate allocation complete signal if all ports are done.
873 MaybeSignalCandidatesAllocationDone();
874}
875
876void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700877 if (CandidatesAllocationDone()) {
878 if (pooled()) {
879 LOG(LS_INFO) << "All candidates gathered for pooled session.";
880 } else {
881 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
882 << component() << ":" << generation();
883 }
884 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000886}
887
888void BasicPortAllocatorSession::OnPortDestroyed(
889 PortInterface* port) {
890 ASSERT(rtc::Thread::Current() == network_thread_);
891 for (std::vector<PortData>::iterator iter = ports_.begin();
892 iter != ports_.end(); ++iter) {
893 if (port == iter->port()) {
894 ports_.erase(iter);
895 LOG_J(LS_INFO, port) << "Removed port from allocator ("
896 << static_cast<int>(ports_.size()) << " remaining)";
897 return;
898 }
899 }
900 ASSERT(false);
901}
902
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000903BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
904 Port* port) {
905 for (std::vector<PortData>::iterator it = ports_.begin();
906 it != ports_.end(); ++it) {
907 if (it->port() == port) {
908 return &*it;
909 }
910 }
911 return NULL;
912}
913
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700914// Removes ports and candidates created on a given list of networks.
915void BasicPortAllocatorSession::RemovePortsAndCandidates(
916 const std::vector<rtc::Network*>& networks) {
917 std::vector<PortInterface*> ports_to_remove;
918 std::vector<Candidate> candidates_to_remove;
919 for (PortData& data : ports_) {
920 if (std::find(networks.begin(), networks.end(),
921 data.sequence()->network()) == networks.end()) {
922 continue;
923 }
924 ports_to_remove.push_back(data.port());
925 if (data.has_pairable_candidate()) {
926 GetCandidatesFromPort(data, &candidates_to_remove);
927 // Mark the port as having no pairable candidates so that its candidates
928 // won't be removed multiple times.
929 data.set_has_pairable_candidate(false);
930 }
931 }
932 if (!ports_to_remove.empty()) {
933 SignalPortsRemoved(this, ports_to_remove);
934 }
935 if (!candidates_to_remove.empty()) {
936 SignalCandidatesRemoved(this, candidates_to_remove);
937 }
938}
939
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000940// AllocationSequence
941
942AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
943 rtc::Network* network,
944 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200945 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000946 : session_(session),
947 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000948 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 config_(config),
950 state_(kInit),
951 flags_(flags),
952 udp_socket_(),
953 udp_port_(NULL),
954 phase_(0) {
955}
956
957bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000958 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
959 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
960 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
961 session_->allocator()->max_port()));
962 if (udp_socket_) {
963 udp_socket_->SignalReadPacket.connect(
964 this, &AllocationSequence::OnReadPacket);
965 }
966 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
967 // are next available options to setup a communication channel.
968 }
969 return true;
970}
971
972void AllocationSequence::Clear() {
973 udp_port_ = NULL;
974 turn_ports_.clear();
975}
976
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700977void AllocationSequence::OnNetworkFailed() {
978 RTC_DCHECK(!network_failed_);
979 network_failed_ = true;
980 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -0700981 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -0700982}
983
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000984AllocationSequence::~AllocationSequence() {
985 session_->network_thread()->Clear(this);
986}
987
988void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200989 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700990 if (network_failed_) {
991 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -0700992 // it won't be equivalent to the new network.
993 return;
994 }
995
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000996 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000997 // Different network setup; nothing is equivalent.
998 return;
999 }
1000
1001 // Else turn off the stuff that we've already got covered.
1002
1003 // Every config implicitly specifies local, so turn that off right away.
1004 *flags |= PORTALLOCATOR_DISABLE_UDP;
1005 *flags |= PORTALLOCATOR_DISABLE_TCP;
1006
1007 if (config_ && config) {
1008 if (config_->StunServers() == config->StunServers()) {
1009 // Already got this STUN servers covered.
1010 *flags |= PORTALLOCATOR_DISABLE_STUN;
1011 }
1012 if (!config_->relays.empty()) {
1013 // Already got relays covered.
1014 // NOTE: This will even skip a _different_ set of relay servers if we
1015 // were to be given one, but that never happens in our codebase. Should
1016 // probably get rid of the list in PortConfiguration and just keep a
1017 // single relay server in each one.
1018 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1019 }
1020 }
1021}
1022
1023void AllocationSequence::Start() {
1024 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001025 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001026}
1027
1028void AllocationSequence::Stop() {
1029 // If the port is completed, don't set it to stopped.
1030 if (state_ == kRunning) {
1031 state_ = kStopped;
1032 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1033 }
1034}
1035
1036void AllocationSequence::OnMessage(rtc::Message* msg) {
1037 ASSERT(rtc::Thread::Current() == session_->network_thread());
1038 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
1039
1040 const char* const PHASE_NAMES[kNumPhases] = {
1041 "Udp", "Relay", "Tcp", "SslTcp"
1042 };
1043
1044 // Perform all of the phases in the current step.
1045 LOG_J(LS_INFO, network_) << "Allocation Phase="
1046 << PHASE_NAMES[phase_];
1047
1048 switch (phase_) {
1049 case PHASE_UDP:
1050 CreateUDPPorts();
1051 CreateStunPorts();
1052 EnableProtocol(PROTO_UDP);
1053 break;
1054
1055 case PHASE_RELAY:
1056 CreateRelayPorts();
1057 break;
1058
1059 case PHASE_TCP:
1060 CreateTCPPorts();
1061 EnableProtocol(PROTO_TCP);
1062 break;
1063
1064 case PHASE_SSLTCP:
1065 state_ = kCompleted;
1066 EnableProtocol(PROTO_SSLTCP);
1067 break;
1068
1069 default:
1070 ASSERT(false);
1071 }
1072
1073 if (state() == kRunning) {
1074 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001075 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1076 session_->allocator()->step_delay(),
1077 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001078 } else {
1079 // If all phases in AllocationSequence are completed, no allocation
1080 // steps needed further. Canceling pending signal.
1081 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1082 SignalPortAllocationComplete(this);
1083 }
1084}
1085
1086void AllocationSequence::EnableProtocol(ProtocolType proto) {
1087 if (!ProtocolEnabled(proto)) {
1088 protocols_.push_back(proto);
1089 session_->OnProtocolEnabled(this, proto);
1090 }
1091}
1092
1093bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1094 for (ProtocolList::const_iterator it = protocols_.begin();
1095 it != protocols_.end(); ++it) {
1096 if (*it == proto)
1097 return true;
1098 }
1099 return false;
1100}
1101
1102void AllocationSequence::CreateUDPPorts() {
1103 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1104 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1105 return;
1106 }
1107
1108 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1109 // is enabled completely.
1110 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001111 bool emit_local_candidate_for_anyaddress =
1112 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001113 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001114 port = UDPPort::Create(
1115 session_->network_thread(), session_->socket_factory(), network_,
1116 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001117 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001118 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001119 port = UDPPort::Create(
1120 session_->network_thread(), session_->socket_factory(), network_, ip_,
1121 session_->allocator()->min_port(), session_->allocator()->max_port(),
1122 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001123 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001124 }
1125
1126 if (port) {
1127 // If shared socket is enabled, STUN candidate will be allocated by the
1128 // UDPPort.
1129 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1130 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001131 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132
1133 // If STUN is not disabled, setting stun server address to port.
1134 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001135 if (config_ && !config_->StunServers().empty()) {
1136 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1137 << "STUN candidate generation.";
1138 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001139 }
1140 }
1141 }
1142
1143 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001144 }
1145}
1146
1147void AllocationSequence::CreateTCPPorts() {
1148 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1149 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1150 return;
1151 }
1152
1153 Port* port = TCPPort::Create(session_->network_thread(),
1154 session_->socket_factory(),
1155 network_, ip_,
1156 session_->allocator()->min_port(),
1157 session_->allocator()->max_port(),
1158 session_->username(), session_->password(),
1159 session_->allocator()->allow_tcp_listen());
1160 if (port) {
1161 session_->AddAllocatedPort(port, this, true);
1162 // Since TCPPort is not created using shared socket, |port| will not be
1163 // added to the dequeue.
1164 }
1165}
1166
1167void AllocationSequence::CreateStunPorts() {
1168 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1169 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1170 return;
1171 }
1172
1173 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1174 return;
1175 }
1176
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001177 if (!(config_ && !config_->StunServers().empty())) {
1178 LOG(LS_WARNING)
1179 << "AllocationSequence: No STUN server configured, skipping.";
1180 return;
1181 }
1182
1183 StunPort* port = StunPort::Create(session_->network_thread(),
1184 session_->socket_factory(),
1185 network_, ip_,
1186 session_->allocator()->min_port(),
1187 session_->allocator()->max_port(),
1188 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001189 config_->StunServers(),
1190 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001191 if (port) {
1192 session_->AddAllocatedPort(port, this, true);
1193 // Since StunPort is not created using shared socket, |port| will not be
1194 // added to the dequeue.
1195 }
1196}
1197
1198void AllocationSequence::CreateRelayPorts() {
1199 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1200 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1201 return;
1202 }
1203
1204 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1205 // ought to have a relay list for them here.
1206 ASSERT(config_ && !config_->relays.empty());
1207 if (!(config_ && !config_->relays.empty())) {
1208 LOG(LS_WARNING)
1209 << "AllocationSequence: No relay server configured, skipping.";
1210 return;
1211 }
1212
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001213 for (RelayServerConfig& relay : config_->relays) {
1214 if (relay.type == RELAY_GTURN) {
1215 CreateGturnPort(relay);
1216 } else if (relay.type == RELAY_TURN) {
1217 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 } else {
1219 ASSERT(false);
1220 }
1221 }
1222}
1223
1224void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1225 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1226 RelayPort* port = RelayPort::Create(session_->network_thread(),
1227 session_->socket_factory(),
1228 network_, ip_,
1229 session_->allocator()->min_port(),
1230 session_->allocator()->max_port(),
1231 config_->username, config_->password);
1232 if (port) {
1233 // Since RelayPort is not created using shared socket, |port| will not be
1234 // added to the dequeue.
1235 // Note: We must add the allocated port before we add addresses because
1236 // the latter will create candidates that need name and preference
1237 // settings. However, we also can't prepare the address (normally
1238 // done by AddAllocatedPort) until we have these addresses. So we
1239 // wait to do that until below.
1240 session_->AddAllocatedPort(port, this, false);
1241
1242 // Add the addresses of this protocol.
1243 PortList::const_iterator relay_port;
1244 for (relay_port = config.ports.begin();
1245 relay_port != config.ports.end();
1246 ++relay_port) {
1247 port->AddServerAddress(*relay_port);
1248 port->AddExternalAddress(*relay_port);
1249 }
1250 // Start fetching an address for this port.
1251 port->PrepareAddress();
1252 }
1253}
1254
1255void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1256 PortList::const_iterator relay_port;
1257 for (relay_port = config.ports.begin();
1258 relay_port != config.ports.end(); ++relay_port) {
1259 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001260
1261 // Skip UDP connections to relay servers if it's disallowed.
1262 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1263 relay_port->proto == PROTO_UDP) {
1264 continue;
1265 }
1266
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001267 // Shared socket mode must be enabled only for UDP based ports. Hence
1268 // don't pass shared socket for ports which will create TCP sockets.
1269 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1270 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1271 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001272 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 port = TurnPort::Create(session_->network_thread(),
1274 session_->socket_factory(),
1275 network_, udp_socket_.get(),
1276 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001277 *relay_port, config.credentials, config.priority,
1278 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001279 turn_ports_.push_back(port);
1280 // Listen to the port destroyed signal, to allow AllocationSequence to
1281 // remove entrt from it's map.
1282 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1283 } else {
1284 port = TurnPort::Create(session_->network_thread(),
1285 session_->socket_factory(),
1286 network_, ip_,
1287 session_->allocator()->min_port(),
1288 session_->allocator()->max_port(),
1289 session_->username(),
1290 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001291 *relay_port, config.credentials, config.priority,
1292 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001293 }
1294 ASSERT(port != NULL);
1295 session_->AddAllocatedPort(port, this, true);
1296 }
1297}
1298
1299void AllocationSequence::OnReadPacket(
1300 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1301 const rtc::SocketAddress& remote_addr,
1302 const rtc::PacketTime& packet_time) {
1303 ASSERT(socket == udp_socket_.get());
1304
1305 bool turn_port_found = false;
1306
1307 // Try to find the TurnPort that matches the remote address. Note that the
1308 // message could be a STUN binding response if the TURN server is also used as
1309 // a STUN server. We don't want to parse every message here to check if it is
1310 // a STUN binding response, so we pass the message to TurnPort regardless of
1311 // the message type. The TurnPort will just ignore the message since it will
1312 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001313 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001315 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1316 packet_time)) {
1317 return;
1318 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001319 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001320 }
1321 }
1322
1323 if (udp_port_) {
1324 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1325
1326 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1327 // the TURN server is also a STUN server.
1328 if (!turn_port_found ||
1329 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001330 RTC_DCHECK(udp_port_->SharedSocket());
1331 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1332 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333 }
1334 }
1335}
1336
1337void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1338 if (udp_port_ == port) {
1339 udp_port_ = NULL;
1340 return;
1341 }
1342
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001343 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1344 if (it != turn_ports_.end()) {
1345 turn_ports_.erase(it);
1346 } else {
1347 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1348 ASSERT(false);
1349 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001350}
1351
1352// PortConfiguration
1353PortConfiguration::PortConfiguration(
1354 const rtc::SocketAddress& stun_address,
1355 const std::string& username,
1356 const std::string& password)
1357 : stun_address(stun_address), username(username), password(password) {
1358 if (!stun_address.IsNil())
1359 stun_servers.insert(stun_address);
1360}
1361
1362PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1363 const std::string& username,
1364 const std::string& password)
1365 : stun_servers(stun_servers),
1366 username(username),
1367 password(password) {
1368 if (!stun_servers.empty())
1369 stun_address = *(stun_servers.begin());
1370}
1371
1372ServerAddresses PortConfiguration::StunServers() {
1373 if (!stun_address.IsNil() &&
1374 stun_servers.find(stun_address) == stun_servers.end()) {
1375 stun_servers.insert(stun_address);
1376 }
deadbeefc5d0d952015-07-16 10:22:21 -07001377 // Every UDP TURN server should also be used as a STUN server.
1378 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1379 for (const rtc::SocketAddress& turn_server : turn_servers) {
1380 if (stun_servers.find(turn_server) == stun_servers.end()) {
1381 stun_servers.insert(turn_server);
1382 }
1383 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 return stun_servers;
1385}
1386
1387void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1388 relays.push_back(config);
1389}
1390
1391bool PortConfiguration::SupportsProtocol(
1392 const RelayServerConfig& relay, ProtocolType type) const {
1393 PortList::const_iterator relay_port;
1394 for (relay_port = relay.ports.begin();
1395 relay_port != relay.ports.end();
1396 ++relay_port) {
1397 if (relay_port->proto == type)
1398 return true;
1399 }
1400 return false;
1401}
1402
1403bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1404 ProtocolType type) const {
1405 for (size_t i = 0; i < relays.size(); ++i) {
1406 if (relays[i].type == turn_type &&
1407 SupportsProtocol(relays[i], type))
1408 return true;
1409 }
1410 return false;
1411}
1412
1413ServerAddresses PortConfiguration::GetRelayServerAddresses(
1414 RelayType turn_type, ProtocolType type) const {
1415 ServerAddresses servers;
1416 for (size_t i = 0; i < relays.size(); ++i) {
1417 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1418 servers.insert(relays[i].ports.front().address);
1419 }
1420 }
1421 return servers;
1422}
1423
1424} // namespace cricket