blob: dbac0d3822ee08cc6453bf382bffd4aa9bf8c0f9 [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);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000554 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700555 networks.erase(std::remove_if(networks.begin(), networks.end(),
556 [this](rtc::Network* network) {
557 return allocator_->network_ignore_mask() &
558 network->type();
559 }),
560 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700561
562 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
563 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700564 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700565 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
566 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700567 networks.erase(std::remove_if(networks.begin(), networks.end(),
568 [lowest_cost](rtc::Network* network) {
569 return network->GetCost() >
570 lowest_cost + rtc::kNetworkCostLow;
571 }),
572 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700573 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700574 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700575}
576
577// For each network, see if we have a sequence that covers it already. If not,
578// create a new sequence to create the appropriate ports.
579void BasicPortAllocatorSession::DoAllocate() {
580 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700581 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582 if (networks.empty()) {
583 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
584 done_signal_needed = true;
585 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700586 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700587 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200588 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200589 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
591 // If all the ports are disabled we should just fire the allocation
592 // done event and return.
593 done_signal_needed = true;
594 break;
595 }
596
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000597 if (!config || config->relays.empty()) {
598 // No relay ports specified in this config.
599 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
600 }
601
602 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000603 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604 // Skip IPv6 networks unless the flag's been set.
605 continue;
606 }
607
608 // Disable phases that would only create ports equivalent to
609 // ones that we have already made.
610 DisableEquivalentPhases(networks[i], config, &sequence_flags);
611
612 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
613 // New AllocationSequence would have nothing to do, so don't make it.
614 continue;
615 }
616
617 AllocationSequence* sequence =
618 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000619 sequence->SignalPortAllocationComplete.connect(
620 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700621 sequence->Init();
622 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700624 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000625 }
626 }
627 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700628 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000629 }
630}
631
632void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700633 std::vector<rtc::Network*> networks = GetNetworks();
634 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700635 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700636 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700637 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700638 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700639 std::find(networks.begin(), networks.end(), sequence->network()) ==
640 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700641 sequence->OnNetworkFailed();
642 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700643 }
644 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700645 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
646 if (!ports_to_prune.empty()) {
647 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
648 << " ports because their networks were gone";
649 PrunePortsAndRemoveCandidates(ports_to_prune);
650 }
honghaiz8c404fa2015-09-28 07:59:43 -0700651
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700652 if (allocation_started_ && !IsStopped()) {
653 if (network_manager_started_) {
654 // If the network manager has started, it must be regathering.
655 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
656 }
657 DoAllocate();
658 }
659
Honghai Zhang5048f572016-08-23 15:47:33 -0700660 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700661 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700662 network_manager_started_ = true;
663 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664}
665
666void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200667 rtc::Network* network,
668 PortConfiguration* config,
669 uint32_t* flags) {
670 for (uint32_t i = 0; i < sequences_.size() &&
671 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
672 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000673 sequences_[i]->DisableEquivalentPhases(network, config, flags);
674 }
675}
676
677void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
678 AllocationSequence * seq,
679 bool prepare_address) {
680 if (!port)
681 return;
682
683 LOG(LS_INFO) << "Adding allocated port for " << content_name();
684 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700685 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000686 port->set_generation(generation());
687 if (allocator_->proxy().type != rtc::PROXY_NONE)
688 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700689 port->set_send_retransmit_count_attribute(
690 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000692 PortData data(port, seq);
693 ports_.push_back(data);
694
695 port->SignalCandidateReady.connect(
696 this, &BasicPortAllocatorSession::OnCandidateReady);
697 port->SignalPortComplete.connect(this,
698 &BasicPortAllocatorSession::OnPortComplete);
699 port->SignalDestroyed.connect(this,
700 &BasicPortAllocatorSession::OnPortDestroyed);
701 port->SignalPortError.connect(
702 this, &BasicPortAllocatorSession::OnPortError);
703 LOG_J(LS_INFO, port) << "Added port to allocator";
704
705 if (prepare_address)
706 port->PrepareAddress();
707}
708
709void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
710 allocation_sequences_created_ = true;
711 // Send candidate allocation complete signal if we have no sequences.
712 MaybeSignalCandidatesAllocationDone();
713}
714
715void BasicPortAllocatorSession::OnCandidateReady(
716 Port* port, const Candidate& c) {
717 ASSERT(rtc::Thread::Current() == network_thread_);
718 PortData* data = FindPort(port);
719 ASSERT(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700720 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700722 // already done with gathering.
723 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700724 LOG(LS_WARNING)
725 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700726 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700727 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700728
danilchapf4e8cf02016-06-30 01:55:03 -0700729 // Mark that the port has a pairable candidate, either because we have a
730 // usable candidate from the port, or simply because the port is bound to the
731 // any address and therefore has no host candidate. This will trigger the port
732 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700733 // checks. If port has already been marked as having a pairable candidate,
734 // do nothing here.
735 // Note: We should check whether any candidates may become ready after this
736 // because there we will check whether the candidate is generated by the ready
737 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700738 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700739 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700740 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700741
742 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700743 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700744 }
745 // If the current port is not pruned yet, SignalPortReady.
746 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700747 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700748 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700749 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700750 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700751 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700752
753 ProtocolType pvalue;
754 bool candidate_protocol_enabled =
755 StringToProto(c.protocol().c_str(), &pvalue) &&
756 data->sequence()->ProtocolEnabled(pvalue);
757
758 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
759 std::vector<Candidate> candidates;
760 candidates.push_back(SanitizeRelatedAddress(c));
761 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700762 } else if (!candidate_protocol_enabled) {
763 LOG(LS_INFO)
764 << "Not yet signaling candidate because protocol is not yet enabled.";
765 } else {
766 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700767 }
768
769 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700770 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700771 MaybeSignalCandidatesAllocationDone();
772 }
773}
774
775Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
776 const std::string& network_name) const {
777 Port* best_turn_port = nullptr;
778 for (const PortData& data : ports_) {
779 if (data.port()->Network()->name() == network_name &&
780 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
781 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
782 best_turn_port = data.port();
783 }
784 }
785 return best_turn_port;
786}
787
788bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700789 // Note: We determine the same network based only on their network names. So
790 // if an IPv4 address and an IPv6 address have the same network name, they
791 // are considered the same network here.
792 const std::string& network_name = newly_pairable_turn_port->Network()->name();
793 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
794 // |port| is already in the list of ports, so the best port cannot be nullptr.
795 RTC_CHECK(best_turn_port != nullptr);
796
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700797 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700798 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700799 for (PortData& data : ports_) {
800 if (data.port()->Network()->name() == network_name &&
801 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
802 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700803 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700804 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700805 // These ports will be pruned in PrunePortsAndRemoveCandidates.
806 ports_to_prune.push_back(&data);
807 } else {
808 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700809 }
810 }
811 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700812
813 if (!ports_to_prune.empty()) {
814 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
815 << " low-priority TURN ports";
816 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700817 }
818 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819}
820
Honghai Zhanga74363c2016-07-28 18:06:15 -0700821void BasicPortAllocatorSession::PruneAllPorts() {
822 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700823 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700824 }
825}
826
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000827void BasicPortAllocatorSession::OnPortComplete(Port* port) {
828 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700829 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000830 PortData* data = FindPort(port);
831 ASSERT(data != NULL);
832
833 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700834 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700836 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837
838 // Moving to COMPLETE state.
839 data->set_complete();
840 // Send candidate allocation complete signal if this was the last port.
841 MaybeSignalCandidatesAllocationDone();
842}
843
844void BasicPortAllocatorSession::OnPortError(Port* port) {
845 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700846 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847 PortData* data = FindPort(port);
848 ASSERT(data != NULL);
849 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700850 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000851 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700852 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853
854 // SignalAddressError is currently sent from StunPort/TurnPort.
855 // But this signal itself is generic.
856 data->set_error();
857 // Send candidate allocation complete signal if this was the last port.
858 MaybeSignalCandidatesAllocationDone();
859}
860
861void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
862 ProtocolType proto) {
863 std::vector<Candidate> candidates;
864 for (std::vector<PortData>::iterator it = ports_.begin();
865 it != ports_.end(); ++it) {
866 if (it->sequence() != seq)
867 continue;
868
869 const std::vector<Candidate>& potentials = it->port()->Candidates();
870 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700871 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700873 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000874 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700875 bool candidate_protocol_enabled =
876 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
877 pvalue == proto;
878 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700879 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
880 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000881 candidates.push_back(potentials[i]);
882 }
883 }
884 }
885
886 if (!candidates.empty()) {
887 SignalCandidatesReady(this, candidates);
888 }
889}
890
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700891bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700892 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000893
894 // When binding to any address, before sending packets out, the getsockname
895 // returns all 0s, but after sending packets, it'll be the NIC used to
896 // send. All 0s is not a valid ICE candidate address and should be filtered
897 // out.
898 if (c.address().IsAnyIP()) {
899 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000900 }
901
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000902 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000903 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000904 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000905 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000906 } else if (c.type() == LOCAL_PORT_TYPE) {
907 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
908 // We allow host candidates if the filter allows server-reflexive
909 // candidates and the candidate is a public IP. Because we don't generate
910 // server-reflexive candidates if they have the same IP as the host
911 // candidate (i.e. when the host candidate is a public IP), filtering to
912 // only server-reflexive candidates won't work right when the host
913 // candidates have public IPs.
914 return true;
915 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000917 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000918 }
919 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000920}
921
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700922bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
923 const Port* port) const {
924 bool candidate_signalable = CheckCandidateFilter(c);
925
926 // When device enumeration is disabled (to prevent non-default IP addresses
927 // from leaking), we ping from some local candidates even though we don't
928 // signal them. However, if host candidates are also disabled (for example, to
929 // prevent even default IP addresses from leaking), we still don't want to
930 // ping from them, even if device enumeration is disabled. Thus, we check for
931 // both device enumeration and host candidates being disabled.
932 bool network_enumeration_disabled = c.address().IsAnyIP();
933 bool can_ping_from_candidate =
934 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
935 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
936
937 return candidate_signalable ||
938 (network_enumeration_disabled && can_ping_from_candidate &&
939 !host_candidates_disabled);
940}
941
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000942void BasicPortAllocatorSession::OnPortAllocationComplete(
943 AllocationSequence* seq) {
944 // Send candidate allocation complete signal if all ports are done.
945 MaybeSignalCandidatesAllocationDone();
946}
947
948void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700949 if (CandidatesAllocationDone()) {
950 if (pooled()) {
951 LOG(LS_INFO) << "All candidates gathered for pooled session.";
952 } else {
953 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
954 << component() << ":" << generation();
955 }
956 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000958}
959
960void BasicPortAllocatorSession::OnPortDestroyed(
961 PortInterface* port) {
962 ASSERT(rtc::Thread::Current() == network_thread_);
963 for (std::vector<PortData>::iterator iter = ports_.begin();
964 iter != ports_.end(); ++iter) {
965 if (port == iter->port()) {
966 ports_.erase(iter);
967 LOG_J(LS_INFO, port) << "Removed port from allocator ("
968 << static_cast<int>(ports_.size()) << " remaining)";
969 return;
970 }
971 }
972 ASSERT(false);
973}
974
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000975BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
976 Port* port) {
977 for (std::vector<PortData>::iterator it = ports_.begin();
978 it != ports_.end(); ++it) {
979 if (it->port() == port) {
980 return &*it;
981 }
982 }
983 return NULL;
984}
985
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700986std::vector<BasicPortAllocatorSession::PortData*>
987BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700988 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700989 std::vector<PortData*> unpruned_ports;
990 for (PortData& port : ports_) {
991 if (!port.pruned() &&
992 std::find(networks.begin(), networks.end(),
993 port.sequence()->network()) != networks.end()) {
994 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700995 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700996 }
997 return unpruned_ports;
998}
999
1000void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1001 const std::vector<PortData*>& port_data_list) {
1002 std::vector<PortInterface*> pruned_ports;
1003 std::vector<Candidate> removed_candidates;
1004 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001005 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001006 data->Prune();
1007 pruned_ports.push_back(data->port());
1008 if (data->has_pairable_candidate()) {
1009 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001010 // Mark the port as having no pairable candidates so that its candidates
1011 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001012 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001013 }
1014 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001015 if (!pruned_ports.empty()) {
1016 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001017 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001018 if (!removed_candidates.empty()) {
1019 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1020 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001021 }
1022}
1023
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001024// AllocationSequence
1025
1026AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1027 rtc::Network* network,
1028 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001029 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001030 : session_(session),
1031 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001032 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001033 config_(config),
1034 state_(kInit),
1035 flags_(flags),
1036 udp_socket_(),
1037 udp_port_(NULL),
1038 phase_(0) {
1039}
1040
Honghai Zhang5048f572016-08-23 15:47:33 -07001041void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001042 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1043 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1044 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1045 session_->allocator()->max_port()));
1046 if (udp_socket_) {
1047 udp_socket_->SignalReadPacket.connect(
1048 this, &AllocationSequence::OnReadPacket);
1049 }
1050 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1051 // are next available options to setup a communication channel.
1052 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001053}
1054
1055void AllocationSequence::Clear() {
1056 udp_port_ = NULL;
1057 turn_ports_.clear();
1058}
1059
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001060void AllocationSequence::OnNetworkFailed() {
1061 RTC_DCHECK(!network_failed_);
1062 network_failed_ = true;
1063 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001064 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001065}
1066
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001067AllocationSequence::~AllocationSequence() {
1068 session_->network_thread()->Clear(this);
1069}
1070
1071void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001072 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001073 if (network_failed_) {
1074 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001075 // it won't be equivalent to the new network.
1076 return;
1077 }
1078
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001079 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080 // Different network setup; nothing is equivalent.
1081 return;
1082 }
1083
1084 // Else turn off the stuff that we've already got covered.
1085
1086 // Every config implicitly specifies local, so turn that off right away.
1087 *flags |= PORTALLOCATOR_DISABLE_UDP;
1088 *flags |= PORTALLOCATOR_DISABLE_TCP;
1089
1090 if (config_ && config) {
1091 if (config_->StunServers() == config->StunServers()) {
1092 // Already got this STUN servers covered.
1093 *flags |= PORTALLOCATOR_DISABLE_STUN;
1094 }
1095 if (!config_->relays.empty()) {
1096 // Already got relays covered.
1097 // NOTE: This will even skip a _different_ set of relay servers if we
1098 // were to be given one, but that never happens in our codebase. Should
1099 // probably get rid of the list in PortConfiguration and just keep a
1100 // single relay server in each one.
1101 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1102 }
1103 }
1104}
1105
1106void AllocationSequence::Start() {
1107 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001108 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109}
1110
1111void AllocationSequence::Stop() {
1112 // If the port is completed, don't set it to stopped.
1113 if (state_ == kRunning) {
1114 state_ = kStopped;
1115 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1116 }
1117}
1118
1119void AllocationSequence::OnMessage(rtc::Message* msg) {
1120 ASSERT(rtc::Thread::Current() == session_->network_thread());
1121 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
1122
1123 const char* const PHASE_NAMES[kNumPhases] = {
1124 "Udp", "Relay", "Tcp", "SslTcp"
1125 };
1126
1127 // Perform all of the phases in the current step.
1128 LOG_J(LS_INFO, network_) << "Allocation Phase="
1129 << PHASE_NAMES[phase_];
1130
1131 switch (phase_) {
1132 case PHASE_UDP:
1133 CreateUDPPorts();
1134 CreateStunPorts();
1135 EnableProtocol(PROTO_UDP);
1136 break;
1137
1138 case PHASE_RELAY:
1139 CreateRelayPorts();
1140 break;
1141
1142 case PHASE_TCP:
1143 CreateTCPPorts();
1144 EnableProtocol(PROTO_TCP);
1145 break;
1146
1147 case PHASE_SSLTCP:
1148 state_ = kCompleted;
1149 EnableProtocol(PROTO_SSLTCP);
1150 break;
1151
1152 default:
1153 ASSERT(false);
1154 }
1155
1156 if (state() == kRunning) {
1157 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001158 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1159 session_->allocator()->step_delay(),
1160 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001161 } else {
1162 // If all phases in AllocationSequence are completed, no allocation
1163 // steps needed further. Canceling pending signal.
1164 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1165 SignalPortAllocationComplete(this);
1166 }
1167}
1168
1169void AllocationSequence::EnableProtocol(ProtocolType proto) {
1170 if (!ProtocolEnabled(proto)) {
1171 protocols_.push_back(proto);
1172 session_->OnProtocolEnabled(this, proto);
1173 }
1174}
1175
1176bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1177 for (ProtocolList::const_iterator it = protocols_.begin();
1178 it != protocols_.end(); ++it) {
1179 if (*it == proto)
1180 return true;
1181 }
1182 return false;
1183}
1184
1185void AllocationSequence::CreateUDPPorts() {
1186 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1187 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1188 return;
1189 }
1190
1191 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1192 // is enabled completely.
1193 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001194 bool emit_local_candidate_for_anyaddress =
1195 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001196 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001197 port = UDPPort::Create(
1198 session_->network_thread(), session_->socket_factory(), network_,
1199 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001200 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001201 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001202 port = UDPPort::Create(
1203 session_->network_thread(), session_->socket_factory(), network_, ip_,
1204 session_->allocator()->min_port(), session_->allocator()->max_port(),
1205 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 }
1208
1209 if (port) {
1210 // If shared socket is enabled, STUN candidate will be allocated by the
1211 // UDPPort.
1212 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1213 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001214 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001215
1216 // If STUN is not disabled, setting stun server address to port.
1217 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 if (config_ && !config_->StunServers().empty()) {
1219 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1220 << "STUN candidate generation.";
1221 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 }
1223 }
1224 }
1225
1226 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001227 }
1228}
1229
1230void AllocationSequence::CreateTCPPorts() {
1231 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1232 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1233 return;
1234 }
1235
1236 Port* port = TCPPort::Create(session_->network_thread(),
1237 session_->socket_factory(),
1238 network_, ip_,
1239 session_->allocator()->min_port(),
1240 session_->allocator()->max_port(),
1241 session_->username(), session_->password(),
1242 session_->allocator()->allow_tcp_listen());
1243 if (port) {
1244 session_->AddAllocatedPort(port, this, true);
1245 // Since TCPPort is not created using shared socket, |port| will not be
1246 // added to the dequeue.
1247 }
1248}
1249
1250void AllocationSequence::CreateStunPorts() {
1251 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1252 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1253 return;
1254 }
1255
1256 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1257 return;
1258 }
1259
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001260 if (!(config_ && !config_->StunServers().empty())) {
1261 LOG(LS_WARNING)
1262 << "AllocationSequence: No STUN server configured, skipping.";
1263 return;
1264 }
1265
1266 StunPort* port = StunPort::Create(session_->network_thread(),
1267 session_->socket_factory(),
1268 network_, ip_,
1269 session_->allocator()->min_port(),
1270 session_->allocator()->max_port(),
1271 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001272 config_->StunServers(),
1273 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001274 if (port) {
1275 session_->AddAllocatedPort(port, this, true);
1276 // Since StunPort is not created using shared socket, |port| will not be
1277 // added to the dequeue.
1278 }
1279}
1280
1281void AllocationSequence::CreateRelayPorts() {
1282 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1283 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1284 return;
1285 }
1286
1287 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1288 // ought to have a relay list for them here.
1289 ASSERT(config_ && !config_->relays.empty());
1290 if (!(config_ && !config_->relays.empty())) {
1291 LOG(LS_WARNING)
1292 << "AllocationSequence: No relay server configured, skipping.";
1293 return;
1294 }
1295
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001296 for (RelayServerConfig& relay : config_->relays) {
1297 if (relay.type == RELAY_GTURN) {
1298 CreateGturnPort(relay);
1299 } else if (relay.type == RELAY_TURN) {
1300 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001301 } else {
1302 ASSERT(false);
1303 }
1304 }
1305}
1306
1307void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1308 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1309 RelayPort* port = RelayPort::Create(session_->network_thread(),
1310 session_->socket_factory(),
1311 network_, ip_,
1312 session_->allocator()->min_port(),
1313 session_->allocator()->max_port(),
1314 config_->username, config_->password);
1315 if (port) {
1316 // Since RelayPort is not created using shared socket, |port| will not be
1317 // added to the dequeue.
1318 // Note: We must add the allocated port before we add addresses because
1319 // the latter will create candidates that need name and preference
1320 // settings. However, we also can't prepare the address (normally
1321 // done by AddAllocatedPort) until we have these addresses. So we
1322 // wait to do that until below.
1323 session_->AddAllocatedPort(port, this, false);
1324
1325 // Add the addresses of this protocol.
1326 PortList::const_iterator relay_port;
1327 for (relay_port = config.ports.begin();
1328 relay_port != config.ports.end();
1329 ++relay_port) {
1330 port->AddServerAddress(*relay_port);
1331 port->AddExternalAddress(*relay_port);
1332 }
1333 // Start fetching an address for this port.
1334 port->PrepareAddress();
1335 }
1336}
1337
1338void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1339 PortList::const_iterator relay_port;
1340 for (relay_port = config.ports.begin();
1341 relay_port != config.ports.end(); ++relay_port) {
1342 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001343
1344 // Skip UDP connections to relay servers if it's disallowed.
1345 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1346 relay_port->proto == PROTO_UDP) {
1347 continue;
1348 }
1349
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001350 // Do not create a port if the server address family is known and does
1351 // not match the local IP address family.
1352 int server_ip_family = relay_port->address.ipaddr().family();
1353 int local_ip_family = ip_.family();
1354 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1355 LOG(LS_INFO) << "Server and local address families are not compatible. "
1356 << "Server address: "
1357 << relay_port->address.ipaddr().ToString()
1358 << " Local address: " << ip_.ToString();
1359 continue;
1360 }
1361
1362
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001363 // Shared socket mode must be enabled only for UDP based ports. Hence
1364 // don't pass shared socket for ports which will create TCP sockets.
1365 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1366 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1367 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001368 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001369 port = TurnPort::Create(session_->network_thread(),
1370 session_->socket_factory(),
1371 network_, udp_socket_.get(),
1372 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001373 *relay_port, config.credentials, config.priority,
1374 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001375 turn_ports_.push_back(port);
1376 // Listen to the port destroyed signal, to allow AllocationSequence to
1377 // remove entrt from it's map.
1378 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1379 } else {
1380 port = TurnPort::Create(session_->network_thread(),
1381 session_->socket_factory(),
1382 network_, ip_,
1383 session_->allocator()->min_port(),
1384 session_->allocator()->max_port(),
1385 session_->username(),
1386 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001387 *relay_port, config.credentials, config.priority,
1388 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001389 }
1390 ASSERT(port != NULL);
1391 session_->AddAllocatedPort(port, this, true);
1392 }
1393}
1394
1395void AllocationSequence::OnReadPacket(
1396 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1397 const rtc::SocketAddress& remote_addr,
1398 const rtc::PacketTime& packet_time) {
1399 ASSERT(socket == udp_socket_.get());
1400
1401 bool turn_port_found = false;
1402
1403 // Try to find the TurnPort that matches the remote address. Note that the
1404 // message could be a STUN binding response if the TURN server is also used as
1405 // a STUN server. We don't want to parse every message here to check if it is
1406 // a STUN binding response, so we pass the message to TurnPort regardless of
1407 // the message type. The TurnPort will just ignore the message since it will
1408 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001409 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001410 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001411 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1412 packet_time)) {
1413 return;
1414 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001415 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001416 }
1417 }
1418
1419 if (udp_port_) {
1420 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1421
1422 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1423 // the TURN server is also a STUN server.
1424 if (!turn_port_found ||
1425 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001426 RTC_DCHECK(udp_port_->SharedSocket());
1427 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1428 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 }
1430 }
1431}
1432
1433void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1434 if (udp_port_ == port) {
1435 udp_port_ = NULL;
1436 return;
1437 }
1438
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001439 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1440 if (it != turn_ports_.end()) {
1441 turn_ports_.erase(it);
1442 } else {
1443 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1444 ASSERT(false);
1445 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001446}
1447
1448// PortConfiguration
1449PortConfiguration::PortConfiguration(
1450 const rtc::SocketAddress& stun_address,
1451 const std::string& username,
1452 const std::string& password)
1453 : stun_address(stun_address), username(username), password(password) {
1454 if (!stun_address.IsNil())
1455 stun_servers.insert(stun_address);
1456}
1457
1458PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1459 const std::string& username,
1460 const std::string& password)
1461 : stun_servers(stun_servers),
1462 username(username),
1463 password(password) {
1464 if (!stun_servers.empty())
1465 stun_address = *(stun_servers.begin());
1466}
1467
1468ServerAddresses PortConfiguration::StunServers() {
1469 if (!stun_address.IsNil() &&
1470 stun_servers.find(stun_address) == stun_servers.end()) {
1471 stun_servers.insert(stun_address);
1472 }
deadbeefc5d0d952015-07-16 10:22:21 -07001473 // Every UDP TURN server should also be used as a STUN server.
1474 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1475 for (const rtc::SocketAddress& turn_server : turn_servers) {
1476 if (stun_servers.find(turn_server) == stun_servers.end()) {
1477 stun_servers.insert(turn_server);
1478 }
1479 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001480 return stun_servers;
1481}
1482
1483void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1484 relays.push_back(config);
1485}
1486
1487bool PortConfiguration::SupportsProtocol(
1488 const RelayServerConfig& relay, ProtocolType type) const {
1489 PortList::const_iterator relay_port;
1490 for (relay_port = relay.ports.begin();
1491 relay_port != relay.ports.end();
1492 ++relay_port) {
1493 if (relay_port->proto == type)
1494 return true;
1495 }
1496 return false;
1497}
1498
1499bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1500 ProtocolType type) const {
1501 for (size_t i = 0; i < relays.size(); ++i) {
1502 if (relays[i].type == turn_type &&
1503 SupportsProtocol(relays[i], type))
1504 return true;
1505 }
1506 return false;
1507}
1508
1509ServerAddresses PortConfiguration::GetRelayServerAddresses(
1510 RelayType turn_type, ProtocolType type) const {
1511 ServerAddresses servers;
1512 for (size_t i = 0; i < relays.size(); ++i) {
1513 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1514 servers.insert(relays[i].ports.front().address);
1515 }
1516 }
1517 return servers;
1518}
1519
1520} // namespace cricket