blob: fabbc429e5292a941ec726f0571cbb113f01be47 [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 Zhangd8f6fc42016-07-01 17:31:12 -0700241 state_ = SessionState::GATHERING;
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);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700249
250 LOG(LS_INFO) << "Pruning turn ports "
251 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252}
253
254void BasicPortAllocatorSession::StopGettingPorts() {
255 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700256 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
honghaiz98db68f2015-09-29 07:58:17 -0700257 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700258 // Note: this must be called after ClearGettingPorts because both may set the
259 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700260 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700261}
262
263void BasicPortAllocatorSession::ClearGettingPorts() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700264 ASSERT(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000265 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700266 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700268 }
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700269 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700270}
271
272std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
273 std::vector<rtc::Network*> networks = GetNetworks();
274
275 // A network interface may have both IPv4 and IPv6 networks. Only if
276 // neither of the networks has any connections, the network interface
277 // is considered failed and need to be regathered on.
278 std::set<std::string> networks_with_connection;
279 for (const PortData& data : ports_) {
280 Port* port = data.port();
281 if (!port->connections().empty()) {
282 networks_with_connection.insert(port->Network()->name());
283 }
284 }
285
286 networks.erase(
287 std::remove_if(networks.begin(), networks.end(),
288 [networks_with_connection](rtc::Network* network) {
289 // If a network does not have any connection, it is
290 // considered failed.
291 return networks_with_connection.find(network->name()) !=
292 networks_with_connection.end();
293 }),
294 networks.end());
295 return networks;
296}
297
298void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
299 // Find the list of networks that have no connection.
300 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
301 if (failed_networks.empty()) {
302 return;
303 }
304
305 // Mark a sequence as "network failed" if its network is in the list of failed
306 // networks, so that it won't be considered as equivalent when the session
307 // regathers ports and candidates.
308 for (AllocationSequence* sequence : sequences_) {
309 if (!sequence->network_failed() &&
310 std::find(failed_networks.begin(), failed_networks.end(),
311 sequence->network()) != failed_networks.end()) {
312 sequence->set_network_failed();
313 }
314 }
315 // Remove ports from being used locally and send signaling to remove
316 // the candidates on the remote side.
317 RemovePortsAndCandidates(failed_networks);
318
319 if (allocation_started_ && network_manager_started_) {
320 DoAllocate();
321 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322}
323
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700324std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
325 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700326 for (const PortData& data : ports_) {
327 if (data.ready()) {
328 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700329 }
330 }
331 return ret;
332}
333
334std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
335 std::vector<Candidate> candidates;
336 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700337 if (!data.ready()) {
338 continue;
339 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700340 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700341 }
342 return candidates;
343}
344
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700345void BasicPortAllocatorSession::GetCandidatesFromPort(
346 const PortData& data,
347 std::vector<Candidate>* candidates) const {
348 RTC_CHECK(candidates != nullptr);
349 for (const Candidate& candidate : data.port()->Candidates()) {
350 if (!CheckCandidateFilter(candidate)) {
351 continue;
352 }
353 ProtocolType pvalue;
354 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
355 !data.sequence()->ProtocolEnabled(pvalue)) {
356 continue;
357 }
358 candidates->push_back(SanitizeRelatedAddress(candidate));
359 }
360}
361
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700362Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
363 const Candidate& c) const {
364 Candidate copy = c;
365 // If adapter enumeration is disabled or host candidates are disabled,
366 // clear the raddr of STUN candidates to avoid local address leakage.
367 bool filter_stun_related_address =
368 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
369 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
370 !(candidate_filter_ & CF_HOST);
371 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
372 // to avoid reflexive address leakage.
373 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
374 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
375 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
376 copy.set_related_address(
377 rtc::EmptySocketAddressWithFamily(copy.address().family()));
378 }
379 return copy;
380}
381
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700382bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
383 // Done only if all required AllocationSequence objects
384 // are created.
385 if (!allocation_sequences_created_) {
386 return false;
387 }
388
389 // Check that all port allocation sequences are complete (not running).
390 if (std::any_of(sequences_.begin(), sequences_.end(),
391 [](const AllocationSequence* sequence) {
392 return sequence->state() == AllocationSequence::kRunning;
393 })) {
394 return false;
395 }
396
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700397 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700398 // expected candidates. Session will trigger candidates allocation complete
399 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700400 return std::none_of(ports_.begin(), ports_.end(),
401 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700402}
403
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
405 switch (message->message_id) {
406 case MSG_CONFIG_START:
407 ASSERT(rtc::Thread::Current() == network_thread_);
408 GetPortConfigurations();
409 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 case MSG_CONFIG_READY:
411 ASSERT(rtc::Thread::Current() == network_thread_);
412 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
413 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 case MSG_ALLOCATE:
415 ASSERT(rtc::Thread::Current() == network_thread_);
416 OnAllocate();
417 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 case MSG_SEQUENCEOBJECTS_CREATED:
419 ASSERT(rtc::Thread::Current() == network_thread_);
420 OnAllocationSequenceObjectsCreated();
421 break;
422 case MSG_CONFIG_STOP:
423 ASSERT(rtc::Thread::Current() == network_thread_);
424 OnConfigStop();
425 break;
426 default:
427 ASSERT(false);
428 }
429}
430
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700431void BasicPortAllocatorSession::UpdateIceParametersInternal() {
432 for (PortData& port : ports_) {
433 port.port()->set_content_name(content_name());
434 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
435 }
436}
437
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438void BasicPortAllocatorSession::GetPortConfigurations() {
439 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
440 username(),
441 password());
442
deadbeef653b8e02015-11-11 12:55:10 -0800443 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
444 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 }
446 ConfigReady(config);
447}
448
449void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700450 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451}
452
453// Adds a configuration to the list.
454void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800455 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800457 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458
459 AllocatePorts();
460}
461
462void BasicPortAllocatorSession::OnConfigStop() {
463 ASSERT(rtc::Thread::Current() == network_thread_);
464
465 // If any of the allocated ports have not completed the candidates allocation,
466 // mark those as error. Since session doesn't need any new candidates
467 // at this stage of the allocation, it's safe to discard any new candidates.
468 bool send_signal = false;
469 for (std::vector<PortData>::iterator it = ports_.begin();
470 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700471 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472 // Updating port state to error, which didn't finish allocating candidates
473 // yet.
474 it->set_error();
475 send_signal = true;
476 }
477 }
478
479 // Did we stop any running sequences?
480 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
481 it != sequences_.end() && !send_signal; ++it) {
482 if ((*it)->state() == AllocationSequence::kStopped) {
483 send_signal = true;
484 }
485 }
486
487 // If we stopped anything that was running, send a done signal now.
488 if (send_signal) {
489 MaybeSignalCandidatesAllocationDone();
490 }
491}
492
493void BasicPortAllocatorSession::AllocatePorts() {
494 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700495 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496}
497
498void BasicPortAllocatorSession::OnAllocate() {
499 if (network_manager_started_)
500 DoAllocate();
501
502 allocation_started_ = true;
503}
504
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700505std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
506 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700507 rtc::NetworkManager* network_manager = allocator_->network_manager();
508 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700509 // If the network permission state is BLOCKED, we just act as if the flag has
510 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700511 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700512 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700513 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
514 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000515 // If the adapter enumeration is disabled, we'll just bind to any address
516 // instead of specific NIC. This is to ensure the same routing for http
517 // traffic by OS is also used here to avoid any local or public IP leakage
518 // during stun process.
519 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700520 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000521 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700522 network_manager->GetNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000523 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700524 networks.erase(std::remove_if(networks.begin(), networks.end(),
525 [this](rtc::Network* network) {
526 return allocator_->network_ignore_mask() &
527 network->type();
528 }),
529 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700530
531 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
532 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700533 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700534 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
535 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700536 networks.erase(std::remove_if(networks.begin(), networks.end(),
537 [lowest_cost](rtc::Network* network) {
538 return network->GetCost() >
539 lowest_cost + rtc::kNetworkCostLow;
540 }),
541 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700542 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700543 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700544}
545
546// For each network, see if we have a sequence that covers it already. If not,
547// create a new sequence to create the appropriate ports.
548void BasicPortAllocatorSession::DoAllocate() {
549 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700550 std::vector<rtc::Network*> networks = GetNetworks();
honghaiz8c404fa2015-09-28 07:59:43 -0700551
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000552 if (networks.empty()) {
553 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
554 done_signal_needed = true;
555 } else {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700556 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200557 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200558 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
560 // If all the ports are disabled we should just fire the allocation
561 // done event and return.
562 done_signal_needed = true;
563 break;
564 }
565
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000566 if (!config || config->relays.empty()) {
567 // No relay ports specified in this config.
568 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
569 }
570
571 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000573 // Skip IPv6 networks unless the flag's been set.
574 continue;
575 }
576
577 // Disable phases that would only create ports equivalent to
578 // ones that we have already made.
579 DisableEquivalentPhases(networks[i], config, &sequence_flags);
580
581 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
582 // New AllocationSequence would have nothing to do, so don't make it.
583 continue;
584 }
585
586 AllocationSequence* sequence =
587 new AllocationSequence(this, networks[i], config, sequence_flags);
588 if (!sequence->Init()) {
589 delete sequence;
590 continue;
591 }
592 done_signal_needed = true;
593 sequence->SignalPortAllocationComplete.connect(
594 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700595 if (!IsStopped()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000596 sequence->Start();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700597 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 sequences_.push_back(sequence);
599 }
600 }
601 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700602 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000603 }
604}
605
606void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700607 std::vector<rtc::Network*> networks = GetNetworks();
608 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700609 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700610 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700611 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700612 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700613 std::find(networks.begin(), networks.end(), sequence->network()) ==
614 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700615 sequence->OnNetworkFailed();
616 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700617 }
618 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700619 RemovePortsAndCandidates(failed_networks);
honghaiz8c404fa2015-09-28 07:59:43 -0700620
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621 network_manager_started_ = true;
622 if (allocation_started_)
623 DoAllocate();
624}
625
626void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200627 rtc::Network* network,
628 PortConfiguration* config,
629 uint32_t* flags) {
630 for (uint32_t i = 0; i < sequences_.size() &&
631 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
632 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633 sequences_[i]->DisableEquivalentPhases(network, config, flags);
634 }
635}
636
637void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
638 AllocationSequence * seq,
639 bool prepare_address) {
640 if (!port)
641 return;
642
643 LOG(LS_INFO) << "Adding allocated port for " << content_name();
644 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700645 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000646 port->set_generation(generation());
647 if (allocator_->proxy().type != rtc::PROXY_NONE)
648 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700649 port->set_send_retransmit_count_attribute(
650 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000652 PortData data(port, seq);
653 ports_.push_back(data);
654
655 port->SignalCandidateReady.connect(
656 this, &BasicPortAllocatorSession::OnCandidateReady);
657 port->SignalPortComplete.connect(this,
658 &BasicPortAllocatorSession::OnPortComplete);
659 port->SignalDestroyed.connect(this,
660 &BasicPortAllocatorSession::OnPortDestroyed);
661 port->SignalPortError.connect(
662 this, &BasicPortAllocatorSession::OnPortError);
663 LOG_J(LS_INFO, port) << "Added port to allocator";
664
665 if (prepare_address)
666 port->PrepareAddress();
667}
668
669void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
670 allocation_sequences_created_ = true;
671 // Send candidate allocation complete signal if we have no sequences.
672 MaybeSignalCandidatesAllocationDone();
673}
674
675void BasicPortAllocatorSession::OnCandidateReady(
676 Port* port, const Candidate& c) {
677 ASSERT(rtc::Thread::Current() == network_thread_);
678 PortData* data = FindPort(port);
679 ASSERT(data != NULL);
680 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700681 // already done with gathering.
682 if (!data->inprogress()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700683 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700684 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700685
danilchapf4e8cf02016-06-30 01:55:03 -0700686 // Mark that the port has a pairable candidate, either because we have a
687 // usable candidate from the port, or simply because the port is bound to the
688 // any address and therefore has no host candidate. This will trigger the port
689 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700690 // checks. If port has already been marked as having a pairable candidate,
691 // do nothing here.
692 // Note: We should check whether any candidates may become ready after this
693 // because there we will check whether the candidate is generated by the ready
694 // ports, which may include this port.
695 bool pruned_port = false;
696 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700697 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700698
699 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
700 pruned_port = PruneTurnPorts(port);
701 }
702 // If the current port is not pruned yet, SignalPortReady.
703 if (!data->pruned()) {
704 SignalPortReady(this, port);
705 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700706 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700707
708 ProtocolType pvalue;
709 bool candidate_protocol_enabled =
710 StringToProto(c.protocol().c_str(), &pvalue) &&
711 data->sequence()->ProtocolEnabled(pvalue);
712
713 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
714 std::vector<Candidate> candidates;
715 candidates.push_back(SanitizeRelatedAddress(c));
716 SignalCandidatesReady(this, candidates);
717 }
718
719 // If we have pruned any port, maybe need to signal port allocation done.
720 if (pruned_port) {
721 MaybeSignalCandidatesAllocationDone();
722 }
723}
724
725Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
726 const std::string& network_name) const {
727 Port* best_turn_port = nullptr;
728 for (const PortData& data : ports_) {
729 if (data.port()->Network()->name() == network_name &&
730 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
731 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
732 best_turn_port = data.port();
733 }
734 }
735 return best_turn_port;
736}
737
738bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
739 bool pruned_port = false;
740 // Note: We determine the same network based only on their network names. So
741 // if an IPv4 address and an IPv6 address have the same network name, they
742 // are considered the same network here.
743 const std::string& network_name = newly_pairable_turn_port->Network()->name();
744 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
745 // |port| is already in the list of ports, so the best port cannot be nullptr.
746 RTC_CHECK(best_turn_port != nullptr);
747
748 for (PortData& data : ports_) {
749 if (data.port()->Network()->name() == network_name &&
750 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
751 ComparePort(data.port(), best_turn_port) < 0) {
752 data.set_pruned();
753 pruned_port = true;
754 if (data.port() != newly_pairable_turn_port) {
755 SignalPortPruned(this, data.port());
756 }
757 }
758 }
759 return pruned_port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000760}
761
762void BasicPortAllocatorSession::OnPortComplete(Port* port) {
763 ASSERT(rtc::Thread::Current() == network_thread_);
764 PortData* data = FindPort(port);
765 ASSERT(data != NULL);
766
767 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700768 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000769 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700770 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000771
772 // Moving to COMPLETE state.
773 data->set_complete();
774 // Send candidate allocation complete signal if this was the last port.
775 MaybeSignalCandidatesAllocationDone();
776}
777
778void BasicPortAllocatorSession::OnPortError(Port* port) {
779 ASSERT(rtc::Thread::Current() == network_thread_);
780 PortData* data = FindPort(port);
781 ASSERT(data != NULL);
782 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700783 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000784 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700785 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786
787 // SignalAddressError is currently sent from StunPort/TurnPort.
788 // But this signal itself is generic.
789 data->set_error();
790 // Send candidate allocation complete signal if this was the last port.
791 MaybeSignalCandidatesAllocationDone();
792}
793
794void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
795 ProtocolType proto) {
796 std::vector<Candidate> candidates;
797 for (std::vector<PortData>::iterator it = ports_.begin();
798 it != ports_.end(); ++it) {
799 if (it->sequence() != seq)
800 continue;
801
802 const std::vector<Candidate>& potentials = it->port()->Candidates();
803 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700804 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000805 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700806 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000807 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700808 bool candidate_protocol_enabled =
809 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
810 pvalue == proto;
811 if (candidate_protocol_enabled) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812 candidates.push_back(potentials[i]);
813 }
814 }
815 }
816
817 if (!candidates.empty()) {
818 SignalCandidatesReady(this, candidates);
819 }
820}
821
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700822bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700823 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000824
825 // When binding to any address, before sending packets out, the getsockname
826 // returns all 0s, but after sending packets, it'll be the NIC used to
827 // send. All 0s is not a valid ICE candidate address and should be filtered
828 // out.
829 if (c.address().IsAnyIP()) {
830 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000831 }
832
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000833 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000834 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000835 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000836 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000837 } else if (c.type() == LOCAL_PORT_TYPE) {
838 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
839 // We allow host candidates if the filter allows server-reflexive
840 // candidates and the candidate is a public IP. Because we don't generate
841 // server-reflexive candidates if they have the same IP as the host
842 // candidate (i.e. when the host candidate is a public IP), filtering to
843 // only server-reflexive candidates won't work right when the host
844 // candidates have public IPs.
845 return true;
846 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000848 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000849 }
850 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851}
852
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700853bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
854 const Port* port) const {
855 bool candidate_signalable = CheckCandidateFilter(c);
856
857 // When device enumeration is disabled (to prevent non-default IP addresses
858 // from leaking), we ping from some local candidates even though we don't
859 // signal them. However, if host candidates are also disabled (for example, to
860 // prevent even default IP addresses from leaking), we still don't want to
861 // ping from them, even if device enumeration is disabled. Thus, we check for
862 // both device enumeration and host candidates being disabled.
863 bool network_enumeration_disabled = c.address().IsAnyIP();
864 bool can_ping_from_candidate =
865 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
866 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
867
868 return candidate_signalable ||
869 (network_enumeration_disabled && can_ping_from_candidate &&
870 !host_candidates_disabled);
871}
872
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000873void BasicPortAllocatorSession::OnPortAllocationComplete(
874 AllocationSequence* seq) {
875 // Send candidate allocation complete signal if all ports are done.
876 MaybeSignalCandidatesAllocationDone();
877}
878
879void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700880 if (CandidatesAllocationDone()) {
881 if (pooled()) {
882 LOG(LS_INFO) << "All candidates gathered for pooled session.";
883 } else {
884 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
885 << component() << ":" << generation();
886 }
887 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889}
890
891void BasicPortAllocatorSession::OnPortDestroyed(
892 PortInterface* port) {
893 ASSERT(rtc::Thread::Current() == network_thread_);
894 for (std::vector<PortData>::iterator iter = ports_.begin();
895 iter != ports_.end(); ++iter) {
896 if (port == iter->port()) {
897 ports_.erase(iter);
898 LOG_J(LS_INFO, port) << "Removed port from allocator ("
899 << static_cast<int>(ports_.size()) << " remaining)";
900 return;
901 }
902 }
903 ASSERT(false);
904}
905
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
907 Port* port) {
908 for (std::vector<PortData>::iterator it = ports_.begin();
909 it != ports_.end(); ++it) {
910 if (it->port() == port) {
911 return &*it;
912 }
913 }
914 return NULL;
915}
916
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700917// Removes ports and candidates created on a given list of networks.
918void BasicPortAllocatorSession::RemovePortsAndCandidates(
919 const std::vector<rtc::Network*>& networks) {
920 std::vector<PortInterface*> ports_to_remove;
921 std::vector<Candidate> candidates_to_remove;
922 for (PortData& data : ports_) {
923 if (std::find(networks.begin(), networks.end(),
924 data.sequence()->network()) == networks.end()) {
925 continue;
926 }
927 ports_to_remove.push_back(data.port());
928 if (data.has_pairable_candidate()) {
929 GetCandidatesFromPort(data, &candidates_to_remove);
930 // Mark the port as having no pairable candidates so that its candidates
931 // won't be removed multiple times.
932 data.set_has_pairable_candidate(false);
933 }
934 }
935 if (!ports_to_remove.empty()) {
936 SignalPortsRemoved(this, ports_to_remove);
937 }
938 if (!candidates_to_remove.empty()) {
939 SignalCandidatesRemoved(this, candidates_to_remove);
940 }
941}
942
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000943// AllocationSequence
944
945AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
946 rtc::Network* network,
947 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200948 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000949 : session_(session),
950 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000951 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952 config_(config),
953 state_(kInit),
954 flags_(flags),
955 udp_socket_(),
956 udp_port_(NULL),
957 phase_(0) {
958}
959
960bool AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000961 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
962 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
963 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
964 session_->allocator()->max_port()));
965 if (udp_socket_) {
966 udp_socket_->SignalReadPacket.connect(
967 this, &AllocationSequence::OnReadPacket);
968 }
969 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
970 // are next available options to setup a communication channel.
971 }
972 return true;
973}
974
975void AllocationSequence::Clear() {
976 udp_port_ = NULL;
977 turn_ports_.clear();
978}
979
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700980void AllocationSequence::OnNetworkFailed() {
981 RTC_DCHECK(!network_failed_);
982 network_failed_ = true;
983 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -0700984 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -0700985}
986
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000987AllocationSequence::~AllocationSequence() {
988 session_->network_thread()->Clear(this);
989}
990
991void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200992 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700993 if (network_failed_) {
994 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -0700995 // it won't be equivalent to the new network.
996 return;
997 }
998
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000999 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001000 // Different network setup; nothing is equivalent.
1001 return;
1002 }
1003
1004 // Else turn off the stuff that we've already got covered.
1005
1006 // Every config implicitly specifies local, so turn that off right away.
1007 *flags |= PORTALLOCATOR_DISABLE_UDP;
1008 *flags |= PORTALLOCATOR_DISABLE_TCP;
1009
1010 if (config_ && config) {
1011 if (config_->StunServers() == config->StunServers()) {
1012 // Already got this STUN servers covered.
1013 *flags |= PORTALLOCATOR_DISABLE_STUN;
1014 }
1015 if (!config_->relays.empty()) {
1016 // Already got relays covered.
1017 // NOTE: This will even skip a _different_ set of relay servers if we
1018 // were to be given one, but that never happens in our codebase. Should
1019 // probably get rid of the list in PortConfiguration and just keep a
1020 // single relay server in each one.
1021 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1022 }
1023 }
1024}
1025
1026void AllocationSequence::Start() {
1027 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001028 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001029}
1030
1031void AllocationSequence::Stop() {
1032 // If the port is completed, don't set it to stopped.
1033 if (state_ == kRunning) {
1034 state_ = kStopped;
1035 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1036 }
1037}
1038
1039void AllocationSequence::OnMessage(rtc::Message* msg) {
1040 ASSERT(rtc::Thread::Current() == session_->network_thread());
1041 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
1042
1043 const char* const PHASE_NAMES[kNumPhases] = {
1044 "Udp", "Relay", "Tcp", "SslTcp"
1045 };
1046
1047 // Perform all of the phases in the current step.
1048 LOG_J(LS_INFO, network_) << "Allocation Phase="
1049 << PHASE_NAMES[phase_];
1050
1051 switch (phase_) {
1052 case PHASE_UDP:
1053 CreateUDPPorts();
1054 CreateStunPorts();
1055 EnableProtocol(PROTO_UDP);
1056 break;
1057
1058 case PHASE_RELAY:
1059 CreateRelayPorts();
1060 break;
1061
1062 case PHASE_TCP:
1063 CreateTCPPorts();
1064 EnableProtocol(PROTO_TCP);
1065 break;
1066
1067 case PHASE_SSLTCP:
1068 state_ = kCompleted;
1069 EnableProtocol(PROTO_SSLTCP);
1070 break;
1071
1072 default:
1073 ASSERT(false);
1074 }
1075
1076 if (state() == kRunning) {
1077 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001078 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1079 session_->allocator()->step_delay(),
1080 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001081 } else {
1082 // If all phases in AllocationSequence are completed, no allocation
1083 // steps needed further. Canceling pending signal.
1084 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1085 SignalPortAllocationComplete(this);
1086 }
1087}
1088
1089void AllocationSequence::EnableProtocol(ProtocolType proto) {
1090 if (!ProtocolEnabled(proto)) {
1091 protocols_.push_back(proto);
1092 session_->OnProtocolEnabled(this, proto);
1093 }
1094}
1095
1096bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1097 for (ProtocolList::const_iterator it = protocols_.begin();
1098 it != protocols_.end(); ++it) {
1099 if (*it == proto)
1100 return true;
1101 }
1102 return false;
1103}
1104
1105void AllocationSequence::CreateUDPPorts() {
1106 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1107 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1108 return;
1109 }
1110
1111 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1112 // is enabled completely.
1113 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001114 bool emit_local_candidate_for_anyaddress =
1115 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001116 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001117 port = UDPPort::Create(
1118 session_->network_thread(), session_->socket_factory(), network_,
1119 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001120 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001121 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001122 port = UDPPort::Create(
1123 session_->network_thread(), session_->socket_factory(), network_, ip_,
1124 session_->allocator()->min_port(), session_->allocator()->max_port(),
1125 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001126 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001127 }
1128
1129 if (port) {
1130 // If shared socket is enabled, STUN candidate will be allocated by the
1131 // UDPPort.
1132 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1133 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001134 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001135
1136 // If STUN is not disabled, setting stun server address to port.
1137 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001138 if (config_ && !config_->StunServers().empty()) {
1139 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1140 << "STUN candidate generation.";
1141 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001142 }
1143 }
1144 }
1145
1146 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001147 }
1148}
1149
1150void AllocationSequence::CreateTCPPorts() {
1151 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1152 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1153 return;
1154 }
1155
1156 Port* port = TCPPort::Create(session_->network_thread(),
1157 session_->socket_factory(),
1158 network_, ip_,
1159 session_->allocator()->min_port(),
1160 session_->allocator()->max_port(),
1161 session_->username(), session_->password(),
1162 session_->allocator()->allow_tcp_listen());
1163 if (port) {
1164 session_->AddAllocatedPort(port, this, true);
1165 // Since TCPPort is not created using shared socket, |port| will not be
1166 // added to the dequeue.
1167 }
1168}
1169
1170void AllocationSequence::CreateStunPorts() {
1171 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1172 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1173 return;
1174 }
1175
1176 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1177 return;
1178 }
1179
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001180 if (!(config_ && !config_->StunServers().empty())) {
1181 LOG(LS_WARNING)
1182 << "AllocationSequence: No STUN server configured, skipping.";
1183 return;
1184 }
1185
1186 StunPort* port = StunPort::Create(session_->network_thread(),
1187 session_->socket_factory(),
1188 network_, ip_,
1189 session_->allocator()->min_port(),
1190 session_->allocator()->max_port(),
1191 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001192 config_->StunServers(),
1193 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001194 if (port) {
1195 session_->AddAllocatedPort(port, this, true);
1196 // Since StunPort is not created using shared socket, |port| will not be
1197 // added to the dequeue.
1198 }
1199}
1200
1201void AllocationSequence::CreateRelayPorts() {
1202 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1203 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1204 return;
1205 }
1206
1207 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1208 // ought to have a relay list for them here.
1209 ASSERT(config_ && !config_->relays.empty());
1210 if (!(config_ && !config_->relays.empty())) {
1211 LOG(LS_WARNING)
1212 << "AllocationSequence: No relay server configured, skipping.";
1213 return;
1214 }
1215
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001216 for (RelayServerConfig& relay : config_->relays) {
1217 if (relay.type == RELAY_GTURN) {
1218 CreateGturnPort(relay);
1219 } else if (relay.type == RELAY_TURN) {
1220 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221 } else {
1222 ASSERT(false);
1223 }
1224 }
1225}
1226
1227void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1228 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1229 RelayPort* port = RelayPort::Create(session_->network_thread(),
1230 session_->socket_factory(),
1231 network_, ip_,
1232 session_->allocator()->min_port(),
1233 session_->allocator()->max_port(),
1234 config_->username, config_->password);
1235 if (port) {
1236 // Since RelayPort is not created using shared socket, |port| will not be
1237 // added to the dequeue.
1238 // Note: We must add the allocated port before we add addresses because
1239 // the latter will create candidates that need name and preference
1240 // settings. However, we also can't prepare the address (normally
1241 // done by AddAllocatedPort) until we have these addresses. So we
1242 // wait to do that until below.
1243 session_->AddAllocatedPort(port, this, false);
1244
1245 // Add the addresses of this protocol.
1246 PortList::const_iterator relay_port;
1247 for (relay_port = config.ports.begin();
1248 relay_port != config.ports.end();
1249 ++relay_port) {
1250 port->AddServerAddress(*relay_port);
1251 port->AddExternalAddress(*relay_port);
1252 }
1253 // Start fetching an address for this port.
1254 port->PrepareAddress();
1255 }
1256}
1257
1258void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1259 PortList::const_iterator relay_port;
1260 for (relay_port = config.ports.begin();
1261 relay_port != config.ports.end(); ++relay_port) {
1262 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001263
1264 // Skip UDP connections to relay servers if it's disallowed.
1265 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1266 relay_port->proto == PROTO_UDP) {
1267 continue;
1268 }
1269
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270 // Shared socket mode must be enabled only for UDP based ports. Hence
1271 // don't pass shared socket for ports which will create TCP sockets.
1272 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1273 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1274 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001275 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001276 port = TurnPort::Create(session_->network_thread(),
1277 session_->socket_factory(),
1278 network_, udp_socket_.get(),
1279 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001280 *relay_port, config.credentials, config.priority,
1281 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001282 turn_ports_.push_back(port);
1283 // Listen to the port destroyed signal, to allow AllocationSequence to
1284 // remove entrt from it's map.
1285 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1286 } else {
1287 port = TurnPort::Create(session_->network_thread(),
1288 session_->socket_factory(),
1289 network_, ip_,
1290 session_->allocator()->min_port(),
1291 session_->allocator()->max_port(),
1292 session_->username(),
1293 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001294 *relay_port, config.credentials, config.priority,
1295 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001296 }
1297 ASSERT(port != NULL);
1298 session_->AddAllocatedPort(port, this, true);
1299 }
1300}
1301
1302void AllocationSequence::OnReadPacket(
1303 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1304 const rtc::SocketAddress& remote_addr,
1305 const rtc::PacketTime& packet_time) {
1306 ASSERT(socket == udp_socket_.get());
1307
1308 bool turn_port_found = false;
1309
1310 // Try to find the TurnPort that matches the remote address. Note that the
1311 // message could be a STUN binding response if the TURN server is also used as
1312 // a STUN server. We don't want to parse every message here to check if it is
1313 // a STUN binding response, so we pass the message to TurnPort regardless of
1314 // the message type. The TurnPort will just ignore the message since it will
1315 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001316 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001318 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1319 packet_time)) {
1320 return;
1321 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001322 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001323 }
1324 }
1325
1326 if (udp_port_) {
1327 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1328
1329 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1330 // the TURN server is also a STUN server.
1331 if (!turn_port_found ||
1332 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001333 RTC_DCHECK(udp_port_->SharedSocket());
1334 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1335 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001336 }
1337 }
1338}
1339
1340void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1341 if (udp_port_ == port) {
1342 udp_port_ = NULL;
1343 return;
1344 }
1345
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001346 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1347 if (it != turn_ports_.end()) {
1348 turn_ports_.erase(it);
1349 } else {
1350 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1351 ASSERT(false);
1352 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001353}
1354
1355// PortConfiguration
1356PortConfiguration::PortConfiguration(
1357 const rtc::SocketAddress& stun_address,
1358 const std::string& username,
1359 const std::string& password)
1360 : stun_address(stun_address), username(username), password(password) {
1361 if (!stun_address.IsNil())
1362 stun_servers.insert(stun_address);
1363}
1364
1365PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1366 const std::string& username,
1367 const std::string& password)
1368 : stun_servers(stun_servers),
1369 username(username),
1370 password(password) {
1371 if (!stun_servers.empty())
1372 stun_address = *(stun_servers.begin());
1373}
1374
1375ServerAddresses PortConfiguration::StunServers() {
1376 if (!stun_address.IsNil() &&
1377 stun_servers.find(stun_address) == stun_servers.end()) {
1378 stun_servers.insert(stun_address);
1379 }
deadbeefc5d0d952015-07-16 10:22:21 -07001380 // Every UDP TURN server should also be used as a STUN server.
1381 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1382 for (const rtc::SocketAddress& turn_server : turn_servers) {
1383 if (stun_servers.find(turn_server) == stun_servers.end()) {
1384 stun_servers.insert(turn_server);
1385 }
1386 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001387 return stun_servers;
1388}
1389
1390void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1391 relays.push_back(config);
1392}
1393
1394bool PortConfiguration::SupportsProtocol(
1395 const RelayServerConfig& relay, ProtocolType type) const {
1396 PortList::const_iterator relay_port;
1397 for (relay_port = relay.ports.begin();
1398 relay_port != relay.ports.end();
1399 ++relay_port) {
1400 if (relay_port->proto == type)
1401 return true;
1402 }
1403 return false;
1404}
1405
1406bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1407 ProtocolType type) const {
1408 for (size_t i = 0; i < relays.size(); ++i) {
1409 if (relays[i].type == turn_type &&
1410 SupportsProtocol(relays[i], type))
1411 return true;
1412 }
1413 return false;
1414}
1415
1416ServerAddresses PortConfiguration::GetRelayServerAddresses(
1417 RelayType turn_type, ProtocolType type) const {
1418 ServerAddresses servers;
1419 for (size_t i = 0; i < relays.size(); ++i) {
1420 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1421 servers.insert(relays[i].ports.front().address);
1422 }
1423 }
1424 return servers;
1425}
1426
1427} // namespace cricket