blob: 664701e100deb0eede31d8596b5dc7f5f524a731 [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
Honghai Zhangd93f50c2016-10-05 11:47:22 -070017#include "webrtc/api/peerconnectioninterface.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000018#include "webrtc/p2p/base/basicpacketsocketfactory.h"
19#include "webrtc/p2p/base/common.h"
20#include "webrtc/p2p/base/port.h"
21#include "webrtc/p2p/base/relayport.h"
22#include "webrtc/p2p/base/stunport.h"
23#include "webrtc/p2p/base/tcpport.h"
24#include "webrtc/p2p/base/turnport.h"
25#include "webrtc/p2p/base/udpport.h"
Guo-wei Shieh38f88932015-08-13 22:24:02 -070026#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000027#include "webrtc/base/common.h"
28#include "webrtc/base/helpers.h"
29#include "webrtc/base/logging.h"
30
31using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000032
33namespace {
34
35enum {
36 MSG_CONFIG_START,
37 MSG_CONFIG_READY,
38 MSG_ALLOCATE,
39 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000040 MSG_SEQUENCEOBJECTS_CREATED,
41 MSG_CONFIG_STOP,
42};
43
44const int PHASE_UDP = 0;
45const int PHASE_RELAY = 1;
46const int PHASE_TCP = 2;
47const int PHASE_SSLTCP = 3;
48
49const int kNumPhases = 4;
50
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070051// Gets protocol priority: UDP > TCP > SSLTCP.
52int GetProtocolPriority(cricket::ProtocolType protocol) {
53 switch (protocol) {
54 case cricket::PROTO_UDP:
55 return 2;
56 case cricket::PROTO_TCP:
57 return 1;
58 case cricket::PROTO_SSLTCP:
59 return 0;
60 default:
61 RTC_DCHECK(false);
62 return 0;
63 }
64}
65// Gets address family priority: IPv6 > IPv4 > Unspecified.
66int GetAddressFamilyPriority(int ip_family) {
67 switch (ip_family) {
68 case AF_INET6:
69 return 2;
70 case AF_INET:
71 return 1;
72 default:
73 RTC_DCHECK(false);
74 return 0;
75 }
76}
77
78// Returns positive if a is better, negative if b is better, and 0 otherwise.
79int ComparePort(const cricket::Port* a, const cricket::Port* b) {
80 int a_protocol = GetProtocolPriority(a->GetProtocol());
81 int b_protocol = GetProtocolPriority(b->GetProtocol());
82 int cmp_protocol = a_protocol - b_protocol;
83 if (cmp_protocol != 0) {
84 return cmp_protocol;
85 }
86
87 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
88 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
89 return a_family - b_family;
90}
91
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000092} // namespace
93
94namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020095const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070096 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
97 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000098
99// BasicPortAllocator
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700100BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
101 rtc::PacketSocketFactory* socket_factory)
102 : network_manager_(network_manager), socket_factory_(socket_factory) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800103 ASSERT(network_manager_ != nullptr);
104 ASSERT(socket_factory_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000105 Construct();
106}
107
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800108BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700109 : network_manager_(network_manager), socket_factory_(nullptr) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800110 ASSERT(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000111 Construct();
112}
113
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700114BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
115 rtc::PacketSocketFactory* socket_factory,
116 const ServerAddresses& stun_servers)
117 : network_manager_(network_manager), socket_factory_(socket_factory) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000118 ASSERT(socket_factory_ != NULL);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700119 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000120 Construct();
121}
122
123BasicPortAllocator::BasicPortAllocator(
124 rtc::NetworkManager* network_manager,
125 const ServerAddresses& stun_servers,
126 const rtc::SocketAddress& relay_address_udp,
127 const rtc::SocketAddress& relay_address_tcp,
128 const rtc::SocketAddress& relay_address_ssl)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700129 : network_manager_(network_manager), socket_factory_(NULL) {
130 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000131 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800132 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800134 }
135 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000136 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800137 }
138 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000139 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800140 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141
deadbeef653b8e02015-11-11 12:55:10 -0800142 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700143 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800144 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000145
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700146 SetConfiguration(stun_servers, turn_servers, 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000147 Construct();
148}
149
150void BasicPortAllocator::Construct() {
151 allow_tcp_listen_ = true;
152}
153
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700154void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
155 IceRegatheringReason reason) {
156 if (!metrics_observer()) {
157 return;
158 }
159 // If the session has not been taken by an active channel, do not report the
160 // metric.
161 for (auto& allocator_session : pooled_sessions()) {
162 if (allocator_session.get() == session) {
163 return;
164 }
165 }
166
167 metrics_observer()->IncrementEnumCounter(
168 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
169 static_cast<int>(IceRegatheringReason::MAX_VALUE));
170}
171
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172BasicPortAllocator::~BasicPortAllocator() {
173}
174
deadbeefc5d0d952015-07-16 10:22:21 -0700175PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 const std::string& content_name, int component,
177 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700178 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700180 session->SignalIceRegathering.connect(this,
181 &BasicPortAllocator::OnIceRegathering);
182 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183}
184
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700185void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
186 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
187 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700188 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
189 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700190}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000191
192// BasicPortAllocatorSession
193BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700194 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000195 const std::string& content_name,
196 int component,
197 const std::string& ice_ufrag,
198 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700199 : PortAllocatorSession(content_name,
200 component,
201 ice_ufrag,
202 ice_pwd,
203 allocator->flags()),
204 allocator_(allocator),
205 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 socket_factory_(allocator->socket_factory()),
207 allocation_started_(false),
208 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700209 allocation_sequences_created_(false),
210 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 allocator_->network_manager()->SignalNetworksChanged.connect(
212 this, &BasicPortAllocatorSession::OnNetworksChanged);
213 allocator_->network_manager()->StartUpdating();
214}
215
216BasicPortAllocatorSession::~BasicPortAllocatorSession() {
217 allocator_->network_manager()->StopUpdating();
218 if (network_thread_ != NULL)
219 network_thread_->Clear(this);
220
Peter Boström0c4e06b2015-10-07 12:23:21 +0200221 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000222 // AllocationSequence should clear it's map entry for turn ports before
223 // ports are destroyed.
224 sequences_[i]->Clear();
225 }
226
227 std::vector<PortData>::iterator it;
228 for (it = ports_.begin(); it != ports_.end(); it++)
229 delete it->port();
230
Peter Boström0c4e06b2015-10-07 12:23:21 +0200231 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232 delete configs_[i];
233
Peter Boström0c4e06b2015-10-07 12:23:21 +0200234 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000235 delete sequences_[i];
236}
237
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700238void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
239 if (filter == candidate_filter_) {
240 return;
241 }
242 // We assume the filter will only change from "ALL" to something else.
243 RTC_DCHECK(candidate_filter_ == CF_ALL);
244 candidate_filter_ = filter;
245 for (PortData& port : ports_) {
246 if (!port.has_pairable_candidate()) {
247 continue;
248 }
249 const auto& candidates = port.port()->Candidates();
250 // Setting a filter may cause a ready port to become non-ready
251 // if it no longer has any pairable candidates.
252 if (!std::any_of(candidates.begin(), candidates.end(),
253 [this, &port](const Candidate& candidate) {
254 return CandidatePairable(candidate, port.port());
255 })) {
256 port.set_has_pairable_candidate(false);
257 }
258 }
259}
260
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261void BasicPortAllocatorSession::StartGettingPorts() {
262 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700263 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 if (!socket_factory_) {
265 owned_socket_factory_.reset(
266 new rtc::BasicPacketSocketFactory(network_thread_));
267 socket_factory_ = owned_socket_factory_.get();
268 }
269
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700270 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700271
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700272 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700273 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000274}
275
276void BasicPortAllocatorSession::StopGettingPorts() {
277 ASSERT(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700278 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700279 // Note: this must be called after ClearGettingPorts because both may set the
280 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700281 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700282}
283
284void BasicPortAllocatorSession::ClearGettingPorts() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700285 ASSERT(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000286 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700287 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700289 }
deadbeefb60a8192016-08-24 15:15:00 -0700290 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700291 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700292}
293
294std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
295 std::vector<rtc::Network*> networks = GetNetworks();
296
297 // A network interface may have both IPv4 and IPv6 networks. Only if
298 // neither of the networks has any connections, the network interface
299 // is considered failed and need to be regathered on.
300 std::set<std::string> networks_with_connection;
301 for (const PortData& data : ports_) {
302 Port* port = data.port();
303 if (!port->connections().empty()) {
304 networks_with_connection.insert(port->Network()->name());
305 }
306 }
307
308 networks.erase(
309 std::remove_if(networks.begin(), networks.end(),
310 [networks_with_connection](rtc::Network* network) {
311 // If a network does not have any connection, it is
312 // considered failed.
313 return networks_with_connection.find(network->name()) !=
314 networks_with_connection.end();
315 }),
316 networks.end());
317 return networks;
318}
319
320void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
321 // Find the list of networks that have no connection.
322 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
323 if (failed_networks.empty()) {
324 return;
325 }
326
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700327 LOG(LS_INFO) << "Regather candidates on failed networks";
328
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700329 // Mark a sequence as "network failed" if its network is in the list of failed
330 // networks, so that it won't be considered as equivalent when the session
331 // regathers ports and candidates.
332 for (AllocationSequence* sequence : sequences_) {
333 if (!sequence->network_failed() &&
334 std::find(failed_networks.begin(), failed_networks.end(),
335 sequence->network()) != failed_networks.end()) {
336 sequence->set_network_failed();
337 }
338 }
339 // Remove ports from being used locally and send signaling to remove
340 // the candidates on the remote side.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700341 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
342 if (!ports_to_prune.empty()) {
343 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
344 << " ports because their networks failed";
345 PrunePortsAndRemoveCandidates(ports_to_prune);
346 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700347
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700348 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
349 SignalIceRegathering(this, IceRegatheringReason::NETWORK_FAILURE);
350
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700351 DoAllocate();
352 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353}
354
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700355std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
356 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700357 for (const PortData& data : ports_) {
358 if (data.ready()) {
359 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700360 }
361 }
362 return ret;
363}
364
365std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
366 std::vector<Candidate> candidates;
367 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700368 if (!data.ready()) {
369 continue;
370 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700371 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700372 }
373 return candidates;
374}
375
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700376void BasicPortAllocatorSession::GetCandidatesFromPort(
377 const PortData& data,
378 std::vector<Candidate>* candidates) const {
379 RTC_CHECK(candidates != nullptr);
380 for (const Candidate& candidate : data.port()->Candidates()) {
381 if (!CheckCandidateFilter(candidate)) {
382 continue;
383 }
384 ProtocolType pvalue;
385 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
386 !data.sequence()->ProtocolEnabled(pvalue)) {
387 continue;
388 }
389 candidates->push_back(SanitizeRelatedAddress(candidate));
390 }
391}
392
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700393Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
394 const Candidate& c) const {
395 Candidate copy = c;
396 // If adapter enumeration is disabled or host candidates are disabled,
397 // clear the raddr of STUN candidates to avoid local address leakage.
398 bool filter_stun_related_address =
399 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
400 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
401 !(candidate_filter_ & CF_HOST);
402 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
403 // to avoid reflexive address leakage.
404 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
405 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
406 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
407 copy.set_related_address(
408 rtc::EmptySocketAddressWithFamily(copy.address().family()));
409 }
410 return copy;
411}
412
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700413bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
414 // Done only if all required AllocationSequence objects
415 // are created.
416 if (!allocation_sequences_created_) {
417 return false;
418 }
419
420 // Check that all port allocation sequences are complete (not running).
421 if (std::any_of(sequences_.begin(), sequences_.end(),
422 [](const AllocationSequence* sequence) {
423 return sequence->state() == AllocationSequence::kRunning;
424 })) {
425 return false;
426 }
427
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700428 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700429 // expected candidates. Session will trigger candidates allocation complete
430 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700431 return std::none_of(ports_.begin(), ports_.end(),
432 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700433}
434
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000435void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
436 switch (message->message_id) {
437 case MSG_CONFIG_START:
438 ASSERT(rtc::Thread::Current() == network_thread_);
439 GetPortConfigurations();
440 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000441 case MSG_CONFIG_READY:
442 ASSERT(rtc::Thread::Current() == network_thread_);
443 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
444 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 case MSG_ALLOCATE:
446 ASSERT(rtc::Thread::Current() == network_thread_);
447 OnAllocate();
448 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449 case MSG_SEQUENCEOBJECTS_CREATED:
450 ASSERT(rtc::Thread::Current() == network_thread_);
451 OnAllocationSequenceObjectsCreated();
452 break;
453 case MSG_CONFIG_STOP:
454 ASSERT(rtc::Thread::Current() == network_thread_);
455 OnConfigStop();
456 break;
457 default:
458 ASSERT(false);
459 }
460}
461
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700462void BasicPortAllocatorSession::UpdateIceParametersInternal() {
463 for (PortData& port : ports_) {
464 port.port()->set_content_name(content_name());
465 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
466 }
467}
468
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469void BasicPortAllocatorSession::GetPortConfigurations() {
470 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
471 username(),
472 password());
473
deadbeef653b8e02015-11-11 12:55:10 -0800474 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
475 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476 }
477 ConfigReady(config);
478}
479
480void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700481 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000482}
483
484// Adds a configuration to the list.
485void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800486 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000487 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800488 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489
490 AllocatePorts();
491}
492
493void BasicPortAllocatorSession::OnConfigStop() {
494 ASSERT(rtc::Thread::Current() == network_thread_);
495
496 // If any of the allocated ports have not completed the candidates allocation,
497 // mark those as error. Since session doesn't need any new candidates
498 // at this stage of the allocation, it's safe to discard any new candidates.
499 bool send_signal = false;
500 for (std::vector<PortData>::iterator it = ports_.begin();
501 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700502 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000503 // Updating port state to error, which didn't finish allocating candidates
504 // yet.
505 it->set_error();
506 send_signal = true;
507 }
508 }
509
510 // Did we stop any running sequences?
511 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
512 it != sequences_.end() && !send_signal; ++it) {
513 if ((*it)->state() == AllocationSequence::kStopped) {
514 send_signal = true;
515 }
516 }
517
518 // If we stopped anything that was running, send a done signal now.
519 if (send_signal) {
520 MaybeSignalCandidatesAllocationDone();
521 }
522}
523
524void BasicPortAllocatorSession::AllocatePorts() {
525 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700526 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000527}
528
529void BasicPortAllocatorSession::OnAllocate() {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700530 if (network_manager_started_ && !IsStopped())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000531 DoAllocate();
532
533 allocation_started_ = true;
534}
535
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700536std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
537 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700538 rtc::NetworkManager* network_manager = allocator_->network_manager();
539 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700540 // If the network permission state is BLOCKED, we just act as if the flag has
541 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700542 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700543 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700544 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
545 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000546 // If the adapter enumeration is disabled, we'll just bind to any address
547 // instead of specific NIC. This is to ensure the same routing for http
548 // traffic by OS is also used here to avoid any local or public IP leakage
549 // during stun process.
550 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700551 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000552 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700553 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800554 // If network enumeration fails, use the ANY address as a fallback, so we
555 // can at least try gathering candidates using the default route chosen by
556 // the OS.
557 if (networks.empty()) {
558 network_manager->GetAnyAddressNetworks(&networks);
559 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000560 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700561 networks.erase(std::remove_if(networks.begin(), networks.end(),
562 [this](rtc::Network* network) {
563 return allocator_->network_ignore_mask() &
564 network->type();
565 }),
566 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700567
568 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
569 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700570 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700571 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
572 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700573 networks.erase(std::remove_if(networks.begin(), networks.end(),
574 [lowest_cost](rtc::Network* network) {
575 return network->GetCost() >
576 lowest_cost + rtc::kNetworkCostLow;
577 }),
578 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700579 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700580 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700581}
582
583// For each network, see if we have a sequence that covers it already. If not,
584// create a new sequence to create the appropriate ports.
585void BasicPortAllocatorSession::DoAllocate() {
586 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700587 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000588 if (networks.empty()) {
589 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
590 done_signal_needed = true;
591 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700592 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700593 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200594 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200595 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000596 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
597 // If all the ports are disabled we should just fire the allocation
598 // done event and return.
599 done_signal_needed = true;
600 break;
601 }
602
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000603 if (!config || config->relays.empty()) {
604 // No relay ports specified in this config.
605 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
606 }
607
608 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000610 // Skip IPv6 networks unless the flag's been set.
611 continue;
612 }
613
614 // Disable phases that would only create ports equivalent to
615 // ones that we have already made.
616 DisableEquivalentPhases(networks[i], config, &sequence_flags);
617
618 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
619 // New AllocationSequence would have nothing to do, so don't make it.
620 continue;
621 }
622
623 AllocationSequence* sequence =
624 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000625 sequence->SignalPortAllocationComplete.connect(
626 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700627 sequence->Init();
628 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000629 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700630 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 }
632 }
633 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700634 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 }
636}
637
638void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700639 std::vector<rtc::Network*> networks = GetNetworks();
640 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700641 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700642 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700643 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700644 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700645 std::find(networks.begin(), networks.end(), sequence->network()) ==
646 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700647 sequence->OnNetworkFailed();
648 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700649 }
650 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700651 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
652 if (!ports_to_prune.empty()) {
653 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
654 << " ports because their networks were gone";
655 PrunePortsAndRemoveCandidates(ports_to_prune);
656 }
honghaiz8c404fa2015-09-28 07:59:43 -0700657
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700658 if (allocation_started_ && !IsStopped()) {
659 if (network_manager_started_) {
660 // If the network manager has started, it must be regathering.
661 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
662 }
663 DoAllocate();
664 }
665
Honghai Zhang5048f572016-08-23 15:47:33 -0700666 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700667 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700668 network_manager_started_ = true;
669 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000670}
671
672void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200673 rtc::Network* network,
674 PortConfiguration* config,
675 uint32_t* flags) {
676 for (uint32_t i = 0; i < sequences_.size() &&
677 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
678 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000679 sequences_[i]->DisableEquivalentPhases(network, config, flags);
680 }
681}
682
683void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
684 AllocationSequence * seq,
685 bool prepare_address) {
686 if (!port)
687 return;
688
689 LOG(LS_INFO) << "Adding allocated port for " << content_name();
690 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700691 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000692 port->set_generation(generation());
693 if (allocator_->proxy().type != rtc::PROXY_NONE)
694 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700695 port->set_send_retransmit_count_attribute(
696 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000697
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000698 PortData data(port, seq);
699 ports_.push_back(data);
700
701 port->SignalCandidateReady.connect(
702 this, &BasicPortAllocatorSession::OnCandidateReady);
703 port->SignalPortComplete.connect(this,
704 &BasicPortAllocatorSession::OnPortComplete);
705 port->SignalDestroyed.connect(this,
706 &BasicPortAllocatorSession::OnPortDestroyed);
707 port->SignalPortError.connect(
708 this, &BasicPortAllocatorSession::OnPortError);
709 LOG_J(LS_INFO, port) << "Added port to allocator";
710
711 if (prepare_address)
712 port->PrepareAddress();
713}
714
715void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
716 allocation_sequences_created_ = true;
717 // Send candidate allocation complete signal if we have no sequences.
718 MaybeSignalCandidatesAllocationDone();
719}
720
721void BasicPortAllocatorSession::OnCandidateReady(
722 Port* port, const Candidate& c) {
723 ASSERT(rtc::Thread::Current() == network_thread_);
724 PortData* data = FindPort(port);
725 ASSERT(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700726 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000727 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700728 // already done with gathering.
729 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700730 LOG(LS_WARNING)
731 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700732 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700733 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700734
danilchapf4e8cf02016-06-30 01:55:03 -0700735 // Mark that the port has a pairable candidate, either because we have a
736 // usable candidate from the port, or simply because the port is bound to the
737 // any address and therefore has no host candidate. This will trigger the port
738 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700739 // checks. If port has already been marked as having a pairable candidate,
740 // do nothing here.
741 // Note: We should check whether any candidates may become ready after this
742 // because there we will check whether the candidate is generated by the ready
743 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700744 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700745 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700746 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700747
748 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700749 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700750 }
751 // If the current port is not pruned yet, SignalPortReady.
752 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700753 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700754 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700755 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700756 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700757 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700758
759 ProtocolType pvalue;
760 bool candidate_protocol_enabled =
761 StringToProto(c.protocol().c_str(), &pvalue) &&
762 data->sequence()->ProtocolEnabled(pvalue);
763
764 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
765 std::vector<Candidate> candidates;
766 candidates.push_back(SanitizeRelatedAddress(c));
767 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700768 } else if (!candidate_protocol_enabled) {
769 LOG(LS_INFO)
770 << "Not yet signaling candidate because protocol is not yet enabled.";
771 } else {
772 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700773 }
774
775 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700776 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700777 MaybeSignalCandidatesAllocationDone();
778 }
779}
780
781Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
782 const std::string& network_name) const {
783 Port* best_turn_port = nullptr;
784 for (const PortData& data : ports_) {
785 if (data.port()->Network()->name() == network_name &&
786 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
787 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
788 best_turn_port = data.port();
789 }
790 }
791 return best_turn_port;
792}
793
794bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700795 // Note: We determine the same network based only on their network names. So
796 // if an IPv4 address and an IPv6 address have the same network name, they
797 // are considered the same network here.
798 const std::string& network_name = newly_pairable_turn_port->Network()->name();
799 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
800 // |port| is already in the list of ports, so the best port cannot be nullptr.
801 RTC_CHECK(best_turn_port != nullptr);
802
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700803 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700804 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700805 for (PortData& data : ports_) {
806 if (data.port()->Network()->name() == network_name &&
807 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
808 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700809 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700810 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700811 // These ports will be pruned in PrunePortsAndRemoveCandidates.
812 ports_to_prune.push_back(&data);
813 } else {
814 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700815 }
816 }
817 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700818
819 if (!ports_to_prune.empty()) {
820 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
821 << " low-priority TURN ports";
822 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700823 }
824 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000825}
826
Honghai Zhanga74363c2016-07-28 18:06:15 -0700827void BasicPortAllocatorSession::PruneAllPorts() {
828 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700829 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700830 }
831}
832
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000833void BasicPortAllocatorSession::OnPortComplete(Port* port) {
834 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700835 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000836 PortData* data = FindPort(port);
837 ASSERT(data != NULL);
838
839 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700840 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000841 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700842 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000843
844 // Moving to COMPLETE state.
845 data->set_complete();
846 // Send candidate allocation complete signal if this was the last port.
847 MaybeSignalCandidatesAllocationDone();
848}
849
850void BasicPortAllocatorSession::OnPortError(Port* port) {
851 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700852 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 PortData* data = FindPort(port);
854 ASSERT(data != NULL);
855 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700856 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000857 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700858 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859
860 // SignalAddressError is currently sent from StunPort/TurnPort.
861 // But this signal itself is generic.
862 data->set_error();
863 // Send candidate allocation complete signal if this was the last port.
864 MaybeSignalCandidatesAllocationDone();
865}
866
867void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
868 ProtocolType proto) {
869 std::vector<Candidate> candidates;
870 for (std::vector<PortData>::iterator it = ports_.begin();
871 it != ports_.end(); ++it) {
872 if (it->sequence() != seq)
873 continue;
874
875 const std::vector<Candidate>& potentials = it->port()->Candidates();
876 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700877 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000878 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700879 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000880 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700881 bool candidate_protocol_enabled =
882 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
883 pvalue == proto;
884 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700885 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
886 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 candidates.push_back(potentials[i]);
888 }
889 }
890 }
891
892 if (!candidates.empty()) {
893 SignalCandidatesReady(this, candidates);
894 }
895}
896
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700897bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700898 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000899
900 // When binding to any address, before sending packets out, the getsockname
901 // returns all 0s, but after sending packets, it'll be the NIC used to
902 // send. All 0s is not a valid ICE candidate address and should be filtered
903 // out.
904 if (c.address().IsAnyIP()) {
905 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000906 }
907
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000908 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000909 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000910 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000911 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000912 } else if (c.type() == LOCAL_PORT_TYPE) {
913 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
914 // We allow host candidates if the filter allows server-reflexive
915 // candidates and the candidate is a public IP. Because we don't generate
916 // server-reflexive candidates if they have the same IP as the host
917 // candidate (i.e. when the host candidate is a public IP), filtering to
918 // only server-reflexive candidates won't work right when the host
919 // candidates have public IPs.
920 return true;
921 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000922
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000923 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000924 }
925 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926}
927
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700928bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
929 const Port* port) const {
930 bool candidate_signalable = CheckCandidateFilter(c);
931
932 // When device enumeration is disabled (to prevent non-default IP addresses
933 // from leaking), we ping from some local candidates even though we don't
934 // signal them. However, if host candidates are also disabled (for example, to
935 // prevent even default IP addresses from leaking), we still don't want to
936 // ping from them, even if device enumeration is disabled. Thus, we check for
937 // both device enumeration and host candidates being disabled.
938 bool network_enumeration_disabled = c.address().IsAnyIP();
939 bool can_ping_from_candidate =
940 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
941 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
942
943 return candidate_signalable ||
944 (network_enumeration_disabled && can_ping_from_candidate &&
945 !host_candidates_disabled);
946}
947
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000948void BasicPortAllocatorSession::OnPortAllocationComplete(
949 AllocationSequence* seq) {
950 // Send candidate allocation complete signal if all ports are done.
951 MaybeSignalCandidatesAllocationDone();
952}
953
954void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700955 if (CandidatesAllocationDone()) {
956 if (pooled()) {
957 LOG(LS_INFO) << "All candidates gathered for pooled session.";
958 } else {
959 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
960 << component() << ":" << generation();
961 }
962 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000963 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000964}
965
966void BasicPortAllocatorSession::OnPortDestroyed(
967 PortInterface* port) {
968 ASSERT(rtc::Thread::Current() == network_thread_);
969 for (std::vector<PortData>::iterator iter = ports_.begin();
970 iter != ports_.end(); ++iter) {
971 if (port == iter->port()) {
972 ports_.erase(iter);
973 LOG_J(LS_INFO, port) << "Removed port from allocator ("
974 << static_cast<int>(ports_.size()) << " remaining)";
975 return;
976 }
977 }
978 ASSERT(false);
979}
980
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000981BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
982 Port* port) {
983 for (std::vector<PortData>::iterator it = ports_.begin();
984 it != ports_.end(); ++it) {
985 if (it->port() == port) {
986 return &*it;
987 }
988 }
989 return NULL;
990}
991
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700992std::vector<BasicPortAllocatorSession::PortData*>
993BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700994 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700995 std::vector<PortData*> unpruned_ports;
996 for (PortData& port : ports_) {
997 if (!port.pruned() &&
998 std::find(networks.begin(), networks.end(),
999 port.sequence()->network()) != networks.end()) {
1000 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001001 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001002 }
1003 return unpruned_ports;
1004}
1005
1006void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1007 const std::vector<PortData*>& port_data_list) {
1008 std::vector<PortInterface*> pruned_ports;
1009 std::vector<Candidate> removed_candidates;
1010 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001011 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001012 data->Prune();
1013 pruned_ports.push_back(data->port());
1014 if (data->has_pairable_candidate()) {
1015 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001016 // Mark the port as having no pairable candidates so that its candidates
1017 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001018 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001019 }
1020 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001021 if (!pruned_ports.empty()) {
1022 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001023 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001024 if (!removed_candidates.empty()) {
1025 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1026 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001027 }
1028}
1029
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030// AllocationSequence
1031
1032AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1033 rtc::Network* network,
1034 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001035 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001036 : session_(session),
1037 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001038 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039 config_(config),
1040 state_(kInit),
1041 flags_(flags),
1042 udp_socket_(),
1043 udp_port_(NULL),
1044 phase_(0) {
1045}
1046
Honghai Zhang5048f572016-08-23 15:47:33 -07001047void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1049 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1050 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1051 session_->allocator()->max_port()));
1052 if (udp_socket_) {
1053 udp_socket_->SignalReadPacket.connect(
1054 this, &AllocationSequence::OnReadPacket);
1055 }
1056 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1057 // are next available options to setup a communication channel.
1058 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001059}
1060
1061void AllocationSequence::Clear() {
1062 udp_port_ = NULL;
1063 turn_ports_.clear();
1064}
1065
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001066void AllocationSequence::OnNetworkFailed() {
1067 RTC_DCHECK(!network_failed_);
1068 network_failed_ = true;
1069 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001070 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001071}
1072
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001073AllocationSequence::~AllocationSequence() {
1074 session_->network_thread()->Clear(this);
1075}
1076
1077void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001078 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001079 if (network_failed_) {
1080 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001081 // it won't be equivalent to the new network.
1082 return;
1083 }
1084
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001085 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001086 // Different network setup; nothing is equivalent.
1087 return;
1088 }
1089
1090 // Else turn off the stuff that we've already got covered.
1091
1092 // Every config implicitly specifies local, so turn that off right away.
1093 *flags |= PORTALLOCATOR_DISABLE_UDP;
1094 *flags |= PORTALLOCATOR_DISABLE_TCP;
1095
1096 if (config_ && config) {
1097 if (config_->StunServers() == config->StunServers()) {
1098 // Already got this STUN servers covered.
1099 *flags |= PORTALLOCATOR_DISABLE_STUN;
1100 }
1101 if (!config_->relays.empty()) {
1102 // Already got relays covered.
1103 // NOTE: This will even skip a _different_ set of relay servers if we
1104 // were to be given one, but that never happens in our codebase. Should
1105 // probably get rid of the list in PortConfiguration and just keep a
1106 // single relay server in each one.
1107 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1108 }
1109 }
1110}
1111
1112void AllocationSequence::Start() {
1113 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001114 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001115}
1116
1117void AllocationSequence::Stop() {
1118 // If the port is completed, don't set it to stopped.
1119 if (state_ == kRunning) {
1120 state_ = kStopped;
1121 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1122 }
1123}
1124
1125void AllocationSequence::OnMessage(rtc::Message* msg) {
1126 ASSERT(rtc::Thread::Current() == session_->network_thread());
1127 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
1128
1129 const char* const PHASE_NAMES[kNumPhases] = {
1130 "Udp", "Relay", "Tcp", "SslTcp"
1131 };
1132
1133 // Perform all of the phases in the current step.
1134 LOG_J(LS_INFO, network_) << "Allocation Phase="
1135 << PHASE_NAMES[phase_];
1136
1137 switch (phase_) {
1138 case PHASE_UDP:
1139 CreateUDPPorts();
1140 CreateStunPorts();
1141 EnableProtocol(PROTO_UDP);
1142 break;
1143
1144 case PHASE_RELAY:
1145 CreateRelayPorts();
1146 break;
1147
1148 case PHASE_TCP:
1149 CreateTCPPorts();
1150 EnableProtocol(PROTO_TCP);
1151 break;
1152
1153 case PHASE_SSLTCP:
1154 state_ = kCompleted;
1155 EnableProtocol(PROTO_SSLTCP);
1156 break;
1157
1158 default:
1159 ASSERT(false);
1160 }
1161
1162 if (state() == kRunning) {
1163 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001164 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1165 session_->allocator()->step_delay(),
1166 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001167 } else {
1168 // If all phases in AllocationSequence are completed, no allocation
1169 // steps needed further. Canceling pending signal.
1170 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1171 SignalPortAllocationComplete(this);
1172 }
1173}
1174
1175void AllocationSequence::EnableProtocol(ProtocolType proto) {
1176 if (!ProtocolEnabled(proto)) {
1177 protocols_.push_back(proto);
1178 session_->OnProtocolEnabled(this, proto);
1179 }
1180}
1181
1182bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1183 for (ProtocolList::const_iterator it = protocols_.begin();
1184 it != protocols_.end(); ++it) {
1185 if (*it == proto)
1186 return true;
1187 }
1188 return false;
1189}
1190
1191void AllocationSequence::CreateUDPPorts() {
1192 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1193 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1194 return;
1195 }
1196
1197 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1198 // is enabled completely.
1199 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001200 bool emit_local_candidate_for_anyaddress =
1201 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001202 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001203 port = UDPPort::Create(
1204 session_->network_thread(), session_->socket_factory(), network_,
1205 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001206 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001207 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001208 port = UDPPort::Create(
1209 session_->network_thread(), session_->socket_factory(), network_, ip_,
1210 session_->allocator()->min_port(), session_->allocator()->max_port(),
1211 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001212 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001213 }
1214
1215 if (port) {
1216 // If shared socket is enabled, STUN candidate will be allocated by the
1217 // UDPPort.
1218 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1219 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001220 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001221
1222 // If STUN is not disabled, setting stun server address to port.
1223 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001224 if (config_ && !config_->StunServers().empty()) {
1225 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1226 << "STUN candidate generation.";
1227 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228 }
1229 }
1230 }
1231
1232 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233 }
1234}
1235
1236void AllocationSequence::CreateTCPPorts() {
1237 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1238 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1239 return;
1240 }
1241
1242 Port* port = TCPPort::Create(session_->network_thread(),
1243 session_->socket_factory(),
1244 network_, ip_,
1245 session_->allocator()->min_port(),
1246 session_->allocator()->max_port(),
1247 session_->username(), session_->password(),
1248 session_->allocator()->allow_tcp_listen());
1249 if (port) {
1250 session_->AddAllocatedPort(port, this, true);
1251 // Since TCPPort is not created using shared socket, |port| will not be
1252 // added to the dequeue.
1253 }
1254}
1255
1256void AllocationSequence::CreateStunPorts() {
1257 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1258 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1259 return;
1260 }
1261
1262 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1263 return;
1264 }
1265
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001266 if (!(config_ && !config_->StunServers().empty())) {
1267 LOG(LS_WARNING)
1268 << "AllocationSequence: No STUN server configured, skipping.";
1269 return;
1270 }
1271
1272 StunPort* port = StunPort::Create(session_->network_thread(),
1273 session_->socket_factory(),
1274 network_, ip_,
1275 session_->allocator()->min_port(),
1276 session_->allocator()->max_port(),
1277 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001278 config_->StunServers(),
1279 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001280 if (port) {
1281 session_->AddAllocatedPort(port, this, true);
1282 // Since StunPort is not created using shared socket, |port| will not be
1283 // added to the dequeue.
1284 }
1285}
1286
1287void AllocationSequence::CreateRelayPorts() {
1288 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1289 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1290 return;
1291 }
1292
1293 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1294 // ought to have a relay list for them here.
1295 ASSERT(config_ && !config_->relays.empty());
1296 if (!(config_ && !config_->relays.empty())) {
1297 LOG(LS_WARNING)
1298 << "AllocationSequence: No relay server configured, skipping.";
1299 return;
1300 }
1301
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001302 for (RelayServerConfig& relay : config_->relays) {
1303 if (relay.type == RELAY_GTURN) {
1304 CreateGturnPort(relay);
1305 } else if (relay.type == RELAY_TURN) {
1306 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001307 } else {
1308 ASSERT(false);
1309 }
1310 }
1311}
1312
1313void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1314 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1315 RelayPort* port = RelayPort::Create(session_->network_thread(),
1316 session_->socket_factory(),
1317 network_, ip_,
1318 session_->allocator()->min_port(),
1319 session_->allocator()->max_port(),
1320 config_->username, config_->password);
1321 if (port) {
1322 // Since RelayPort is not created using shared socket, |port| will not be
1323 // added to the dequeue.
1324 // Note: We must add the allocated port before we add addresses because
1325 // the latter will create candidates that need name and preference
1326 // settings. However, we also can't prepare the address (normally
1327 // done by AddAllocatedPort) until we have these addresses. So we
1328 // wait to do that until below.
1329 session_->AddAllocatedPort(port, this, false);
1330
1331 // Add the addresses of this protocol.
1332 PortList::const_iterator relay_port;
1333 for (relay_port = config.ports.begin();
1334 relay_port != config.ports.end();
1335 ++relay_port) {
1336 port->AddServerAddress(*relay_port);
1337 port->AddExternalAddress(*relay_port);
1338 }
1339 // Start fetching an address for this port.
1340 port->PrepareAddress();
1341 }
1342}
1343
1344void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1345 PortList::const_iterator relay_port;
1346 for (relay_port = config.ports.begin();
1347 relay_port != config.ports.end(); ++relay_port) {
1348 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001349
1350 // Skip UDP connections to relay servers if it's disallowed.
1351 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1352 relay_port->proto == PROTO_UDP) {
1353 continue;
1354 }
1355
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001356 // Do not create a port if the server address family is known and does
1357 // not match the local IP address family.
1358 int server_ip_family = relay_port->address.ipaddr().family();
1359 int local_ip_family = ip_.family();
1360 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1361 LOG(LS_INFO) << "Server and local address families are not compatible. "
1362 << "Server address: "
1363 << relay_port->address.ipaddr().ToString()
1364 << " Local address: " << ip_.ToString();
1365 continue;
1366 }
1367
1368
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001369 // Shared socket mode must be enabled only for UDP based ports. Hence
1370 // don't pass shared socket for ports which will create TCP sockets.
1371 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1372 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1373 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001374 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001375 port = TurnPort::Create(session_->network_thread(),
1376 session_->socket_factory(),
1377 network_, udp_socket_.get(),
1378 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001379 *relay_port, config.credentials, config.priority,
1380 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001381 turn_ports_.push_back(port);
1382 // Listen to the port destroyed signal, to allow AllocationSequence to
1383 // remove entrt from it's map.
1384 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1385 } else {
1386 port = TurnPort::Create(session_->network_thread(),
1387 session_->socket_factory(),
1388 network_, ip_,
1389 session_->allocator()->min_port(),
1390 session_->allocator()->max_port(),
1391 session_->username(),
1392 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001393 *relay_port, config.credentials, config.priority,
1394 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001395 }
1396 ASSERT(port != NULL);
1397 session_->AddAllocatedPort(port, this, true);
1398 }
1399}
1400
1401void AllocationSequence::OnReadPacket(
1402 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1403 const rtc::SocketAddress& remote_addr,
1404 const rtc::PacketTime& packet_time) {
1405 ASSERT(socket == udp_socket_.get());
1406
1407 bool turn_port_found = false;
1408
1409 // Try to find the TurnPort that matches the remote address. Note that the
1410 // message could be a STUN binding response if the TURN server is also used as
1411 // a STUN server. We don't want to parse every message here to check if it is
1412 // a STUN binding response, so we pass the message to TurnPort regardless of
1413 // the message type. The TurnPort will just ignore the message since it will
1414 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001415 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001416 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001417 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1418 packet_time)) {
1419 return;
1420 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 }
1423 }
1424
1425 if (udp_port_) {
1426 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1427
1428 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1429 // the TURN server is also a STUN server.
1430 if (!turn_port_found ||
1431 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001432 RTC_DCHECK(udp_port_->SharedSocket());
1433 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1434 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001435 }
1436 }
1437}
1438
1439void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1440 if (udp_port_ == port) {
1441 udp_port_ = NULL;
1442 return;
1443 }
1444
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001445 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1446 if (it != turn_ports_.end()) {
1447 turn_ports_.erase(it);
1448 } else {
1449 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1450 ASSERT(false);
1451 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001452}
1453
1454// PortConfiguration
1455PortConfiguration::PortConfiguration(
1456 const rtc::SocketAddress& stun_address,
1457 const std::string& username,
1458 const std::string& password)
1459 : stun_address(stun_address), username(username), password(password) {
1460 if (!stun_address.IsNil())
1461 stun_servers.insert(stun_address);
1462}
1463
1464PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1465 const std::string& username,
1466 const std::string& password)
1467 : stun_servers(stun_servers),
1468 username(username),
1469 password(password) {
1470 if (!stun_servers.empty())
1471 stun_address = *(stun_servers.begin());
1472}
1473
1474ServerAddresses PortConfiguration::StunServers() {
1475 if (!stun_address.IsNil() &&
1476 stun_servers.find(stun_address) == stun_servers.end()) {
1477 stun_servers.insert(stun_address);
1478 }
deadbeefc5d0d952015-07-16 10:22:21 -07001479 // Every UDP TURN server should also be used as a STUN server.
1480 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1481 for (const rtc::SocketAddress& turn_server : turn_servers) {
1482 if (stun_servers.find(turn_server) == stun_servers.end()) {
1483 stun_servers.insert(turn_server);
1484 }
1485 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001486 return stun_servers;
1487}
1488
1489void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1490 relays.push_back(config);
1491}
1492
1493bool PortConfiguration::SupportsProtocol(
1494 const RelayServerConfig& relay, ProtocolType type) const {
1495 PortList::const_iterator relay_port;
1496 for (relay_port = relay.ports.begin();
1497 relay_port != relay.ports.end();
1498 ++relay_port) {
1499 if (relay_port->proto == type)
1500 return true;
1501 }
1502 return false;
1503}
1504
1505bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1506 ProtocolType type) const {
1507 for (size_t i = 0; i < relays.size(); ++i) {
1508 if (relays[i].type == turn_type &&
1509 SupportsProtocol(relays[i], type))
1510 return true;
1511 }
1512 return false;
1513}
1514
1515ServerAddresses PortConfiguration::GetRelayServerAddresses(
1516 RelayType turn_type, ProtocolType type) const {
1517 ServerAddresses servers;
1518 for (size_t i = 0; i < relays.size(); ++i) {
1519 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1520 servers.insert(relays[i].ports.front().address);
1521 }
1522 }
1523 return servers;
1524}
1525
1526} // namespace cricket