blob: dba68f177e5120a496a39d603d622971ac776ac4 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/p2p/client/basicportallocator.h"
12
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000014#include <string>
15#include <vector>
16
17#include "webrtc/p2p/base/basicpacketsocketfactory.h"
18#include "webrtc/p2p/base/common.h"
19#include "webrtc/p2p/base/port.h"
20#include "webrtc/p2p/base/relayport.h"
21#include "webrtc/p2p/base/stunport.h"
22#include "webrtc/p2p/base/tcpport.h"
23#include "webrtc/p2p/base/turnport.h"
24#include "webrtc/p2p/base/udpport.h"
Guo-wei Shieh38f88932015-08-13 22:24:02 -070025#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000026#include "webrtc/base/common.h"
27#include "webrtc/base/helpers.h"
28#include "webrtc/base/logging.h"
29
30using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32namespace {
33
34enum {
35 MSG_CONFIG_START,
36 MSG_CONFIG_READY,
37 MSG_ALLOCATE,
38 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000039 MSG_SEQUENCEOBJECTS_CREATED,
40 MSG_CONFIG_STOP,
41};
42
43const int PHASE_UDP = 0;
44const int PHASE_RELAY = 1;
45const int PHASE_TCP = 2;
46const int PHASE_SSLTCP = 3;
47
48const int kNumPhases = 4;
49
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070050// Gets protocol priority: UDP > TCP > SSLTCP.
51int GetProtocolPriority(cricket::ProtocolType protocol) {
52 switch (protocol) {
53 case cricket::PROTO_UDP:
54 return 2;
55 case cricket::PROTO_TCP:
56 return 1;
57 case cricket::PROTO_SSLTCP:
58 return 0;
59 default:
60 RTC_DCHECK(false);
61 return 0;
62 }
63}
64// Gets address family priority: IPv6 > IPv4 > Unspecified.
65int GetAddressFamilyPriority(int ip_family) {
66 switch (ip_family) {
67 case AF_INET6:
68 return 2;
69 case AF_INET:
70 return 1;
71 default:
72 RTC_DCHECK(false);
73 return 0;
74 }
75}
76
77// Returns positive if a is better, negative if b is better, and 0 otherwise.
78int ComparePort(const cricket::Port* a, const cricket::Port* b) {
79 int a_protocol = GetProtocolPriority(a->GetProtocol());
80 int b_protocol = GetProtocolPriority(b->GetProtocol());
81 int cmp_protocol = a_protocol - b_protocol;
82 if (cmp_protocol != 0) {
83 return cmp_protocol;
84 }
85
86 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
87 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
88 return a_family - b_family;
89}
90
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000091} // namespace
92
93namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +020094const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -070095 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
96 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000097
98// BasicPortAllocator
Taylor Brandstettera1c30352016-05-13 08:15:11 -070099BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
100 rtc::PacketSocketFactory* socket_factory)
101 : network_manager_(network_manager), socket_factory_(socket_factory) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800102 ASSERT(network_manager_ != nullptr);
103 ASSERT(socket_factory_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000104 Construct();
105}
106
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800107BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700108 : network_manager_(network_manager), socket_factory_(nullptr) {
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -0800109 ASSERT(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110 Construct();
111}
112
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700113BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
114 rtc::PacketSocketFactory* socket_factory,
115 const ServerAddresses& stun_servers)
116 : network_manager_(network_manager), socket_factory_(socket_factory) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000117 ASSERT(socket_factory_ != NULL);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700118 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119 Construct();
120}
121
122BasicPortAllocator::BasicPortAllocator(
123 rtc::NetworkManager* network_manager,
124 const ServerAddresses& stun_servers,
125 const rtc::SocketAddress& relay_address_udp,
126 const rtc::SocketAddress& relay_address_tcp,
127 const rtc::SocketAddress& relay_address_ssl)
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700128 : network_manager_(network_manager), socket_factory_(NULL) {
129 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000130 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800131 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000132 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800133 }
134 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800136 }
137 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000138 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800139 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140
deadbeef653b8e02015-11-11 12:55:10 -0800141 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700142 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800143 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000144
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700145 SetConfiguration(stun_servers, turn_servers, 0, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 Construct();
147}
148
149void BasicPortAllocator::Construct() {
150 allow_tcp_listen_ = true;
151}
152
153BasicPortAllocator::~BasicPortAllocator() {
154}
155
deadbeefc5d0d952015-07-16 10:22:21 -0700156PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000157 const std::string& content_name, int component,
158 const std::string& ice_ufrag, const std::string& ice_pwd) {
159 return new BasicPortAllocatorSession(
160 this, content_name, component, ice_ufrag, ice_pwd);
161}
162
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700163void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
164 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
165 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700166 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
167 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700168}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169
170// BasicPortAllocatorSession
171BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700172 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000173 const std::string& content_name,
174 int component,
175 const std::string& ice_ufrag,
176 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700177 : PortAllocatorSession(content_name,
178 component,
179 ice_ufrag,
180 ice_pwd,
181 allocator->flags()),
182 allocator_(allocator),
183 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 socket_factory_(allocator->socket_factory()),
185 allocation_started_(false),
186 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700187 allocation_sequences_created_(false),
188 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000189 allocator_->network_manager()->SignalNetworksChanged.connect(
190 this, &BasicPortAllocatorSession::OnNetworksChanged);
191 allocator_->network_manager()->StartUpdating();
192}
193
194BasicPortAllocatorSession::~BasicPortAllocatorSession() {
195 allocator_->network_manager()->StopUpdating();
196 if (network_thread_ != NULL)
197 network_thread_->Clear(this);
198
Peter Boström0c4e06b2015-10-07 12:23:21 +0200199 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200 // AllocationSequence should clear it's map entry for turn ports before
201 // ports are destroyed.
202 sequences_[i]->Clear();
203 }
204
205 std::vector<PortData>::iterator it;
206 for (it = ports_.begin(); it != ports_.end(); it++)
207 delete it->port();
208
Peter Boström0c4e06b2015-10-07 12:23:21 +0200209 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210 delete configs_[i];
211
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 delete sequences_[i];
214}
215
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700216void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
217 if (filter == candidate_filter_) {
218 return;
219 }
220 // We assume the filter will only change from "ALL" to something else.
221 RTC_DCHECK(candidate_filter_ == CF_ALL);
222 candidate_filter_ = filter;
223 for (PortData& port : ports_) {
224 if (!port.has_pairable_candidate()) {
225 continue;
226 }
227 const auto& candidates = port.port()->Candidates();
228 // Setting a filter may cause a ready port to become non-ready
229 // if it no longer has any pairable candidates.
230 if (!std::any_of(candidates.begin(), candidates.end(),
231 [this, &port](const Candidate& candidate) {
232 return CandidatePairable(candidate, port.port());
233 })) {
234 port.set_has_pairable_candidate(false);
235 }
236 }
237}
238
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000239void BasicPortAllocatorSession::StartGettingPorts() {
240 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700241 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242 if (!socket_factory_) {
243 owned_socket_factory_.reset(
244 new rtc::BasicPacketSocketFactory(network_thread_));
245 socket_factory_ = owned_socket_factory_.get();
246 }
247
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700248 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700249
250 LOG(LS_INFO) << "Pruning turn ports "
251 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000252}
253
254void BasicPortAllocatorSession::StopGettingPorts() {
255 ASSERT(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700256 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700257 // Note: this must be called after ClearGettingPorts because both may set the
258 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700259 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700260}
261
262void BasicPortAllocatorSession::ClearGettingPorts() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700263 ASSERT(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700265 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700267 }
deadbeefb60a8192016-08-24 15:15:00 -0700268 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700269 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700270}
271
272std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
273 std::vector<rtc::Network*> networks = GetNetworks();
274
275 // A network interface may have both IPv4 and IPv6 networks. Only if
276 // neither of the networks has any connections, the network interface
277 // is considered failed and need to be regathered on.
278 std::set<std::string> networks_with_connection;
279 for (const PortData& data : ports_) {
280 Port* port = data.port();
281 if (!port->connections().empty()) {
282 networks_with_connection.insert(port->Network()->name());
283 }
284 }
285
286 networks.erase(
287 std::remove_if(networks.begin(), networks.end(),
288 [networks_with_connection](rtc::Network* network) {
289 // If a network does not have any connection, it is
290 // considered failed.
291 return networks_with_connection.find(network->name()) !=
292 networks_with_connection.end();
293 }),
294 networks.end());
295 return networks;
296}
297
298void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
299 // Find the list of networks that have no connection.
300 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
301 if (failed_networks.empty()) {
302 return;
303 }
304
305 // Mark a sequence as "network failed" if its network is in the list of failed
306 // networks, so that it won't be considered as equivalent when the session
307 // regathers ports and candidates.
308 for (AllocationSequence* sequence : sequences_) {
309 if (!sequence->network_failed() &&
310 std::find(failed_networks.begin(), failed_networks.end(),
311 sequence->network()) != failed_networks.end()) {
312 sequence->set_network_failed();
313 }
314 }
315 // Remove ports from being used locally and send signaling to remove
316 // the candidates on the remote side.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700317 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
318 if (!ports_to_prune.empty()) {
319 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
320 << " ports because their networks failed";
321 PrunePortsAndRemoveCandidates(ports_to_prune);
322 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700323
324 if (allocation_started_ && network_manager_started_) {
325 DoAllocate();
326 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000327}
328
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700329std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
330 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700331 for (const PortData& data : ports_) {
332 if (data.ready()) {
333 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700334 }
335 }
336 return ret;
337}
338
339std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
340 std::vector<Candidate> candidates;
341 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700342 if (!data.ready()) {
343 continue;
344 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700345 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700346 }
347 return candidates;
348}
349
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700350void BasicPortAllocatorSession::GetCandidatesFromPort(
351 const PortData& data,
352 std::vector<Candidate>* candidates) const {
353 RTC_CHECK(candidates != nullptr);
354 for (const Candidate& candidate : data.port()->Candidates()) {
355 if (!CheckCandidateFilter(candidate)) {
356 continue;
357 }
358 ProtocolType pvalue;
359 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
360 !data.sequence()->ProtocolEnabled(pvalue)) {
361 continue;
362 }
363 candidates->push_back(SanitizeRelatedAddress(candidate));
364 }
365}
366
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700367Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
368 const Candidate& c) const {
369 Candidate copy = c;
370 // If adapter enumeration is disabled or host candidates are disabled,
371 // clear the raddr of STUN candidates to avoid local address leakage.
372 bool filter_stun_related_address =
373 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
374 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
375 !(candidate_filter_ & CF_HOST);
376 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
377 // to avoid reflexive address leakage.
378 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
379 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
380 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
381 copy.set_related_address(
382 rtc::EmptySocketAddressWithFamily(copy.address().family()));
383 }
384 return copy;
385}
386
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700387bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
388 // Done only if all required AllocationSequence objects
389 // are created.
390 if (!allocation_sequences_created_) {
391 return false;
392 }
393
394 // Check that all port allocation sequences are complete (not running).
395 if (std::any_of(sequences_.begin(), sequences_.end(),
396 [](const AllocationSequence* sequence) {
397 return sequence->state() == AllocationSequence::kRunning;
398 })) {
399 return false;
400 }
401
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700402 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700403 // expected candidates. Session will trigger candidates allocation complete
404 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700405 return std::none_of(ports_.begin(), ports_.end(),
406 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700407}
408
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000409void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
410 switch (message->message_id) {
411 case MSG_CONFIG_START:
412 ASSERT(rtc::Thread::Current() == network_thread_);
413 GetPortConfigurations();
414 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000415 case MSG_CONFIG_READY:
416 ASSERT(rtc::Thread::Current() == network_thread_);
417 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
418 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000419 case MSG_ALLOCATE:
420 ASSERT(rtc::Thread::Current() == network_thread_);
421 OnAllocate();
422 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000423 case MSG_SEQUENCEOBJECTS_CREATED:
424 ASSERT(rtc::Thread::Current() == network_thread_);
425 OnAllocationSequenceObjectsCreated();
426 break;
427 case MSG_CONFIG_STOP:
428 ASSERT(rtc::Thread::Current() == network_thread_);
429 OnConfigStop();
430 break;
431 default:
432 ASSERT(false);
433 }
434}
435
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700436void BasicPortAllocatorSession::UpdateIceParametersInternal() {
437 for (PortData& port : ports_) {
438 port.port()->set_content_name(content_name());
439 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
440 }
441}
442
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443void BasicPortAllocatorSession::GetPortConfigurations() {
444 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
445 username(),
446 password());
447
deadbeef653b8e02015-11-11 12:55:10 -0800448 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
449 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 }
451 ConfigReady(config);
452}
453
454void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700455 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000456}
457
458// Adds a configuration to the list.
459void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800460 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800462 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463
464 AllocatePorts();
465}
466
467void BasicPortAllocatorSession::OnConfigStop() {
468 ASSERT(rtc::Thread::Current() == network_thread_);
469
470 // If any of the allocated ports have not completed the candidates allocation,
471 // mark those as error. Since session doesn't need any new candidates
472 // at this stage of the allocation, it's safe to discard any new candidates.
473 bool send_signal = false;
474 for (std::vector<PortData>::iterator it = ports_.begin();
475 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700476 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 // Updating port state to error, which didn't finish allocating candidates
478 // yet.
479 it->set_error();
480 send_signal = true;
481 }
482 }
483
484 // Did we stop any running sequences?
485 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
486 it != sequences_.end() && !send_signal; ++it) {
487 if ((*it)->state() == AllocationSequence::kStopped) {
488 send_signal = true;
489 }
490 }
491
492 // If we stopped anything that was running, send a done signal now.
493 if (send_signal) {
494 MaybeSignalCandidatesAllocationDone();
495 }
496}
497
498void BasicPortAllocatorSession::AllocatePorts() {
499 ASSERT(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700500 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000501}
502
503void BasicPortAllocatorSession::OnAllocate() {
504 if (network_manager_started_)
505 DoAllocate();
506
507 allocation_started_ = true;
508}
509
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700510std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
511 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700512 rtc::NetworkManager* network_manager = allocator_->network_manager();
513 ASSERT(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700514 // If the network permission state is BLOCKED, we just act as if the flag has
515 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700516 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700517 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700518 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
519 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000520 // If the adapter enumeration is disabled, we'll just bind to any address
521 // instead of specific NIC. This is to ensure the same routing for http
522 // traffic by OS is also used here to avoid any local or public IP leakage
523 // during stun process.
524 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700525 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000526 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700527 network_manager->GetNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000528 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700529 networks.erase(std::remove_if(networks.begin(), networks.end(),
530 [this](rtc::Network* network) {
531 return allocator_->network_ignore_mask() &
532 network->type();
533 }),
534 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700535
536 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
537 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700538 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700539 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
540 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700541 networks.erase(std::remove_if(networks.begin(), networks.end(),
542 [lowest_cost](rtc::Network* network) {
543 return network->GetCost() >
544 lowest_cost + rtc::kNetworkCostLow;
545 }),
546 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700547 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700548 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700549}
550
551// For each network, see if we have a sequence that covers it already. If not,
552// create a new sequence to create the appropriate ports.
553void BasicPortAllocatorSession::DoAllocate() {
554 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700555 std::vector<rtc::Network*> networks = GetNetworks();
honghaiz8c404fa2015-09-28 07:59:43 -0700556
Honghai Zhang5048f572016-08-23 15:47:33 -0700557 if (IsStopped()) {
558 return;
559 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000560 if (networks.empty()) {
561 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
562 done_signal_needed = true;
563 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700564 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700565 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200566 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200567 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
569 // If all the ports are disabled we should just fire the allocation
570 // done event and return.
571 done_signal_needed = true;
572 break;
573 }
574
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000575 if (!config || config->relays.empty()) {
576 // No relay ports specified in this config.
577 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
578 }
579
580 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000581 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582 // Skip IPv6 networks unless the flag's been set.
583 continue;
584 }
585
586 // Disable phases that would only create ports equivalent to
587 // ones that we have already made.
588 DisableEquivalentPhases(networks[i], config, &sequence_flags);
589
590 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
591 // New AllocationSequence would have nothing to do, so don't make it.
592 continue;
593 }
594
595 AllocationSequence* sequence =
596 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000597 sequence->SignalPortAllocationComplete.connect(
598 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700599 sequence->Init();
600 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000601 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700602 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000603 }
604 }
605 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700606 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000607 }
608}
609
610void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700611 std::vector<rtc::Network*> networks = GetNetworks();
612 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700613 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700614 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700615 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700616 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700617 std::find(networks.begin(), networks.end(), sequence->network()) ==
618 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700619 sequence->OnNetworkFailed();
620 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700621 }
622 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700623 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
624 if (!ports_to_prune.empty()) {
625 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
626 << " ports because their networks were gone";
627 PrunePortsAndRemoveCandidates(ports_to_prune);
628 }
honghaiz8c404fa2015-09-28 07:59:43 -0700629
Honghai Zhang5048f572016-08-23 15:47:33 -0700630 if (!network_manager_started_) {
631 LOG(LS_INFO) << "Network manager is started";
632 network_manager_started_ = true;
633 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 if (allocation_started_)
635 DoAllocate();
636}
637
638void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200639 rtc::Network* network,
640 PortConfiguration* config,
641 uint32_t* flags) {
642 for (uint32_t i = 0; i < sequences_.size() &&
643 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
644 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645 sequences_[i]->DisableEquivalentPhases(network, config, flags);
646 }
647}
648
649void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
650 AllocationSequence * seq,
651 bool prepare_address) {
652 if (!port)
653 return;
654
655 LOG(LS_INFO) << "Adding allocated port for " << content_name();
656 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700657 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000658 port->set_generation(generation());
659 if (allocator_->proxy().type != rtc::PROXY_NONE)
660 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700661 port->set_send_retransmit_count_attribute(
662 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664 PortData data(port, seq);
665 ports_.push_back(data);
666
667 port->SignalCandidateReady.connect(
668 this, &BasicPortAllocatorSession::OnCandidateReady);
669 port->SignalPortComplete.connect(this,
670 &BasicPortAllocatorSession::OnPortComplete);
671 port->SignalDestroyed.connect(this,
672 &BasicPortAllocatorSession::OnPortDestroyed);
673 port->SignalPortError.connect(
674 this, &BasicPortAllocatorSession::OnPortError);
675 LOG_J(LS_INFO, port) << "Added port to allocator";
676
677 if (prepare_address)
678 port->PrepareAddress();
679}
680
681void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
682 allocation_sequences_created_ = true;
683 // Send candidate allocation complete signal if we have no sequences.
684 MaybeSignalCandidatesAllocationDone();
685}
686
687void BasicPortAllocatorSession::OnCandidateReady(
688 Port* port, const Candidate& c) {
689 ASSERT(rtc::Thread::Current() == network_thread_);
690 PortData* data = FindPort(port);
691 ASSERT(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700692 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000693 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700694 // already done with gathering.
695 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700696 LOG(LS_WARNING)
697 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700698 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700699 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700700
danilchapf4e8cf02016-06-30 01:55:03 -0700701 // Mark that the port has a pairable candidate, either because we have a
702 // usable candidate from the port, or simply because the port is bound to the
703 // any address and therefore has no host candidate. This will trigger the port
704 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700705 // checks. If port has already been marked as having a pairable candidate,
706 // do nothing here.
707 // Note: We should check whether any candidates may become ready after this
708 // because there we will check whether the candidate is generated by the ready
709 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700710 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700711 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700712 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700713
714 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700715 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700716 }
717 // If the current port is not pruned yet, SignalPortReady.
718 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700719 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700720 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700721 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700722 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700723 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700724
725 ProtocolType pvalue;
726 bool candidate_protocol_enabled =
727 StringToProto(c.protocol().c_str(), &pvalue) &&
728 data->sequence()->ProtocolEnabled(pvalue);
729
730 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
731 std::vector<Candidate> candidates;
732 candidates.push_back(SanitizeRelatedAddress(c));
733 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700734 } else if (!candidate_protocol_enabled) {
735 LOG(LS_INFO)
736 << "Not yet signaling candidate because protocol is not yet enabled.";
737 } else {
738 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700739 }
740
741 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700742 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700743 MaybeSignalCandidatesAllocationDone();
744 }
745}
746
747Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
748 const std::string& network_name) const {
749 Port* best_turn_port = nullptr;
750 for (const PortData& data : ports_) {
751 if (data.port()->Network()->name() == network_name &&
752 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
753 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
754 best_turn_port = data.port();
755 }
756 }
757 return best_turn_port;
758}
759
760bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700761 // Note: We determine the same network based only on their network names. So
762 // if an IPv4 address and an IPv6 address have the same network name, they
763 // are considered the same network here.
764 const std::string& network_name = newly_pairable_turn_port->Network()->name();
765 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
766 // |port| is already in the list of ports, so the best port cannot be nullptr.
767 RTC_CHECK(best_turn_port != nullptr);
768
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700769 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700770 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700771 for (PortData& data : ports_) {
772 if (data.port()->Network()->name() == network_name &&
773 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
774 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700775 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700776 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700777 // These ports will be pruned in PrunePortsAndRemoveCandidates.
778 ports_to_prune.push_back(&data);
779 } else {
780 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700781 }
782 }
783 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700784
785 if (!ports_to_prune.empty()) {
786 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
787 << " low-priority TURN ports";
788 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700789 }
790 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000791}
792
Honghai Zhanga74363c2016-07-28 18:06:15 -0700793void BasicPortAllocatorSession::PruneAllPorts() {
794 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700795 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700796 }
797}
798
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000799void BasicPortAllocatorSession::OnPortComplete(Port* port) {
800 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700801 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000802 PortData* data = FindPort(port);
803 ASSERT(data != NULL);
804
805 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700806 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000807 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700808 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000809
810 // Moving to COMPLETE state.
811 data->set_complete();
812 // Send candidate allocation complete signal if this was the last port.
813 MaybeSignalCandidatesAllocationDone();
814}
815
816void BasicPortAllocatorSession::OnPortError(Port* port) {
817 ASSERT(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700818 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000819 PortData* data = FindPort(port);
820 ASSERT(data != NULL);
821 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700822 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000823 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700824 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000825
826 // SignalAddressError is currently sent from StunPort/TurnPort.
827 // But this signal itself is generic.
828 data->set_error();
829 // Send candidate allocation complete signal if this was the last port.
830 MaybeSignalCandidatesAllocationDone();
831}
832
833void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
834 ProtocolType proto) {
835 std::vector<Candidate> candidates;
836 for (std::vector<PortData>::iterator it = ports_.begin();
837 it != ports_.end(); ++it) {
838 if (it->sequence() != seq)
839 continue;
840
841 const std::vector<Candidate>& potentials = it->port()->Candidates();
842 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700843 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000844 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700845 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700847 bool candidate_protocol_enabled =
848 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
849 pvalue == proto;
850 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700851 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
852 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000853 candidates.push_back(potentials[i]);
854 }
855 }
856 }
857
858 if (!candidates.empty()) {
859 SignalCandidatesReady(this, candidates);
860 }
861}
862
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700863bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700864 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000865
866 // When binding to any address, before sending packets out, the getsockname
867 // returns all 0s, but after sending packets, it'll be the NIC used to
868 // send. All 0s is not a valid ICE candidate address and should be filtered
869 // out.
870 if (c.address().IsAnyIP()) {
871 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872 }
873
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000874 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000875 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000876 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000877 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000878 } else if (c.type() == LOCAL_PORT_TYPE) {
879 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
880 // We allow host candidates if the filter allows server-reflexive
881 // candidates and the candidate is a public IP. Because we don't generate
882 // server-reflexive candidates if they have the same IP as the host
883 // candidate (i.e. when the host candidate is a public IP), filtering to
884 // only server-reflexive candidates won't work right when the host
885 // candidates have public IPs.
886 return true;
887 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000889 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000890 }
891 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000892}
893
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700894bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
895 const Port* port) const {
896 bool candidate_signalable = CheckCandidateFilter(c);
897
898 // When device enumeration is disabled (to prevent non-default IP addresses
899 // from leaking), we ping from some local candidates even though we don't
900 // signal them. However, if host candidates are also disabled (for example, to
901 // prevent even default IP addresses from leaking), we still don't want to
902 // ping from them, even if device enumeration is disabled. Thus, we check for
903 // both device enumeration and host candidates being disabled.
904 bool network_enumeration_disabled = c.address().IsAnyIP();
905 bool can_ping_from_candidate =
906 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
907 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
908
909 return candidate_signalable ||
910 (network_enumeration_disabled && can_ping_from_candidate &&
911 !host_candidates_disabled);
912}
913
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914void BasicPortAllocatorSession::OnPortAllocationComplete(
915 AllocationSequence* seq) {
916 // Send candidate allocation complete signal if all ports are done.
917 MaybeSignalCandidatesAllocationDone();
918}
919
920void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700921 if (CandidatesAllocationDone()) {
922 if (pooled()) {
923 LOG(LS_INFO) << "All candidates gathered for pooled session.";
924 } else {
925 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
926 << component() << ":" << generation();
927 }
928 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930}
931
932void BasicPortAllocatorSession::OnPortDestroyed(
933 PortInterface* port) {
934 ASSERT(rtc::Thread::Current() == network_thread_);
935 for (std::vector<PortData>::iterator iter = ports_.begin();
936 iter != ports_.end(); ++iter) {
937 if (port == iter->port()) {
938 ports_.erase(iter);
939 LOG_J(LS_INFO, port) << "Removed port from allocator ("
940 << static_cast<int>(ports_.size()) << " remaining)";
941 return;
942 }
943 }
944 ASSERT(false);
945}
946
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000947BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
948 Port* port) {
949 for (std::vector<PortData>::iterator it = ports_.begin();
950 it != ports_.end(); ++it) {
951 if (it->port() == port) {
952 return &*it;
953 }
954 }
955 return NULL;
956}
957
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700958std::vector<BasicPortAllocatorSession::PortData*>
959BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700960 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700961 std::vector<PortData*> unpruned_ports;
962 for (PortData& port : ports_) {
963 if (!port.pruned() &&
964 std::find(networks.begin(), networks.end(),
965 port.sequence()->network()) != networks.end()) {
966 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700967 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700968 }
969 return unpruned_ports;
970}
971
972void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
973 const std::vector<PortData*>& port_data_list) {
974 std::vector<PortInterface*> pruned_ports;
975 std::vector<Candidate> removed_candidates;
976 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -0700977 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700978 data->Prune();
979 pruned_ports.push_back(data->port());
980 if (data->has_pairable_candidate()) {
981 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700982 // Mark the port as having no pairable candidates so that its candidates
983 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700984 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700985 }
986 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700987 if (!pruned_ports.empty()) {
988 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700989 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700990 if (!removed_candidates.empty()) {
991 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
992 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700993 }
994}
995
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000996// AllocationSequence
997
998AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
999 rtc::Network* network,
1000 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001001 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001002 : session_(session),
1003 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001004 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001005 config_(config),
1006 state_(kInit),
1007 flags_(flags),
1008 udp_socket_(),
1009 udp_port_(NULL),
1010 phase_(0) {
1011}
1012
Honghai Zhang5048f572016-08-23 15:47:33 -07001013void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001014 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1015 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1016 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1017 session_->allocator()->max_port()));
1018 if (udp_socket_) {
1019 udp_socket_->SignalReadPacket.connect(
1020 this, &AllocationSequence::OnReadPacket);
1021 }
1022 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1023 // are next available options to setup a communication channel.
1024 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001025}
1026
1027void AllocationSequence::Clear() {
1028 udp_port_ = NULL;
1029 turn_ports_.clear();
1030}
1031
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001032void AllocationSequence::OnNetworkFailed() {
1033 RTC_DCHECK(!network_failed_);
1034 network_failed_ = true;
1035 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001036 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001037}
1038
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039AllocationSequence::~AllocationSequence() {
1040 session_->network_thread()->Clear(this);
1041}
1042
1043void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001044 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001045 if (network_failed_) {
1046 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001047 // it won't be equivalent to the new network.
1048 return;
1049 }
1050
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001051 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001052 // Different network setup; nothing is equivalent.
1053 return;
1054 }
1055
1056 // Else turn off the stuff that we've already got covered.
1057
1058 // Every config implicitly specifies local, so turn that off right away.
1059 *flags |= PORTALLOCATOR_DISABLE_UDP;
1060 *flags |= PORTALLOCATOR_DISABLE_TCP;
1061
1062 if (config_ && config) {
1063 if (config_->StunServers() == config->StunServers()) {
1064 // Already got this STUN servers covered.
1065 *flags |= PORTALLOCATOR_DISABLE_STUN;
1066 }
1067 if (!config_->relays.empty()) {
1068 // Already got relays covered.
1069 // NOTE: This will even skip a _different_ set of relay servers if we
1070 // were to be given one, but that never happens in our codebase. Should
1071 // probably get rid of the list in PortConfiguration and just keep a
1072 // single relay server in each one.
1073 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1074 }
1075 }
1076}
1077
1078void AllocationSequence::Start() {
1079 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001080 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001081}
1082
1083void AllocationSequence::Stop() {
1084 // If the port is completed, don't set it to stopped.
1085 if (state_ == kRunning) {
1086 state_ = kStopped;
1087 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1088 }
1089}
1090
1091void AllocationSequence::OnMessage(rtc::Message* msg) {
1092 ASSERT(rtc::Thread::Current() == session_->network_thread());
1093 ASSERT(msg->message_id == MSG_ALLOCATION_PHASE);
1094
1095 const char* const PHASE_NAMES[kNumPhases] = {
1096 "Udp", "Relay", "Tcp", "SslTcp"
1097 };
1098
1099 // Perform all of the phases in the current step.
1100 LOG_J(LS_INFO, network_) << "Allocation Phase="
1101 << PHASE_NAMES[phase_];
1102
1103 switch (phase_) {
1104 case PHASE_UDP:
1105 CreateUDPPorts();
1106 CreateStunPorts();
1107 EnableProtocol(PROTO_UDP);
1108 break;
1109
1110 case PHASE_RELAY:
1111 CreateRelayPorts();
1112 break;
1113
1114 case PHASE_TCP:
1115 CreateTCPPorts();
1116 EnableProtocol(PROTO_TCP);
1117 break;
1118
1119 case PHASE_SSLTCP:
1120 state_ = kCompleted;
1121 EnableProtocol(PROTO_SSLTCP);
1122 break;
1123
1124 default:
1125 ASSERT(false);
1126 }
1127
1128 if (state() == kRunning) {
1129 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001130 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1131 session_->allocator()->step_delay(),
1132 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001133 } else {
1134 // If all phases in AllocationSequence are completed, no allocation
1135 // steps needed further. Canceling pending signal.
1136 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1137 SignalPortAllocationComplete(this);
1138 }
1139}
1140
1141void AllocationSequence::EnableProtocol(ProtocolType proto) {
1142 if (!ProtocolEnabled(proto)) {
1143 protocols_.push_back(proto);
1144 session_->OnProtocolEnabled(this, proto);
1145 }
1146}
1147
1148bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1149 for (ProtocolList::const_iterator it = protocols_.begin();
1150 it != protocols_.end(); ++it) {
1151 if (*it == proto)
1152 return true;
1153 }
1154 return false;
1155}
1156
1157void AllocationSequence::CreateUDPPorts() {
1158 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1159 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1160 return;
1161 }
1162
1163 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1164 // is enabled completely.
1165 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001166 bool emit_local_candidate_for_anyaddress =
1167 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001168 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001169 port = UDPPort::Create(
1170 session_->network_thread(), session_->socket_factory(), network_,
1171 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001172 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001173 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001174 port = UDPPort::Create(
1175 session_->network_thread(), session_->socket_factory(), network_, ip_,
1176 session_->allocator()->min_port(), session_->allocator()->max_port(),
1177 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001178 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001179 }
1180
1181 if (port) {
1182 // If shared socket is enabled, STUN candidate will be allocated by the
1183 // UDPPort.
1184 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1185 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001186 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001187
1188 // If STUN is not disabled, setting stun server address to port.
1189 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001190 if (config_ && !config_->StunServers().empty()) {
1191 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1192 << "STUN candidate generation.";
1193 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001194 }
1195 }
1196 }
1197
1198 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001199 }
1200}
1201
1202void AllocationSequence::CreateTCPPorts() {
1203 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1204 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1205 return;
1206 }
1207
1208 Port* port = TCPPort::Create(session_->network_thread(),
1209 session_->socket_factory(),
1210 network_, ip_,
1211 session_->allocator()->min_port(),
1212 session_->allocator()->max_port(),
1213 session_->username(), session_->password(),
1214 session_->allocator()->allow_tcp_listen());
1215 if (port) {
1216 session_->AddAllocatedPort(port, this, true);
1217 // Since TCPPort is not created using shared socket, |port| will not be
1218 // added to the dequeue.
1219 }
1220}
1221
1222void AllocationSequence::CreateStunPorts() {
1223 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1224 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1225 return;
1226 }
1227
1228 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1229 return;
1230 }
1231
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001232 if (!(config_ && !config_->StunServers().empty())) {
1233 LOG(LS_WARNING)
1234 << "AllocationSequence: No STUN server configured, skipping.";
1235 return;
1236 }
1237
1238 StunPort* port = StunPort::Create(session_->network_thread(),
1239 session_->socket_factory(),
1240 network_, ip_,
1241 session_->allocator()->min_port(),
1242 session_->allocator()->max_port(),
1243 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001244 config_->StunServers(),
1245 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001246 if (port) {
1247 session_->AddAllocatedPort(port, this, true);
1248 // Since StunPort is not created using shared socket, |port| will not be
1249 // added to the dequeue.
1250 }
1251}
1252
1253void AllocationSequence::CreateRelayPorts() {
1254 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1255 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1256 return;
1257 }
1258
1259 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1260 // ought to have a relay list for them here.
1261 ASSERT(config_ && !config_->relays.empty());
1262 if (!(config_ && !config_->relays.empty())) {
1263 LOG(LS_WARNING)
1264 << "AllocationSequence: No relay server configured, skipping.";
1265 return;
1266 }
1267
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001268 for (RelayServerConfig& relay : config_->relays) {
1269 if (relay.type == RELAY_GTURN) {
1270 CreateGturnPort(relay);
1271 } else if (relay.type == RELAY_TURN) {
1272 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 } else {
1274 ASSERT(false);
1275 }
1276 }
1277}
1278
1279void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1280 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1281 RelayPort* port = RelayPort::Create(session_->network_thread(),
1282 session_->socket_factory(),
1283 network_, ip_,
1284 session_->allocator()->min_port(),
1285 session_->allocator()->max_port(),
1286 config_->username, config_->password);
1287 if (port) {
1288 // Since RelayPort is not created using shared socket, |port| will not be
1289 // added to the dequeue.
1290 // Note: We must add the allocated port before we add addresses because
1291 // the latter will create candidates that need name and preference
1292 // settings. However, we also can't prepare the address (normally
1293 // done by AddAllocatedPort) until we have these addresses. So we
1294 // wait to do that until below.
1295 session_->AddAllocatedPort(port, this, false);
1296
1297 // Add the addresses of this protocol.
1298 PortList::const_iterator relay_port;
1299 for (relay_port = config.ports.begin();
1300 relay_port != config.ports.end();
1301 ++relay_port) {
1302 port->AddServerAddress(*relay_port);
1303 port->AddExternalAddress(*relay_port);
1304 }
1305 // Start fetching an address for this port.
1306 port->PrepareAddress();
1307 }
1308}
1309
1310void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1311 PortList::const_iterator relay_port;
1312 for (relay_port = config.ports.begin();
1313 relay_port != config.ports.end(); ++relay_port) {
1314 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001315
1316 // Skip UDP connections to relay servers if it's disallowed.
1317 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1318 relay_port->proto == PROTO_UDP) {
1319 continue;
1320 }
1321
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001322 // Do not create a port if the server address family is known and does
1323 // not match the local IP address family.
1324 int server_ip_family = relay_port->address.ipaddr().family();
1325 int local_ip_family = ip_.family();
1326 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1327 LOG(LS_INFO) << "Server and local address families are not compatible. "
1328 << "Server address: "
1329 << relay_port->address.ipaddr().ToString()
1330 << " Local address: " << ip_.ToString();
1331 continue;
1332 }
1333
1334
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001335 // Shared socket mode must be enabled only for UDP based ports. Hence
1336 // don't pass shared socket for ports which will create TCP sockets.
1337 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1338 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1339 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001340 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001341 port = TurnPort::Create(session_->network_thread(),
1342 session_->socket_factory(),
1343 network_, udp_socket_.get(),
1344 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001345 *relay_port, config.credentials, config.priority,
1346 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001347 turn_ports_.push_back(port);
1348 // Listen to the port destroyed signal, to allow AllocationSequence to
1349 // remove entrt from it's map.
1350 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1351 } else {
1352 port = TurnPort::Create(session_->network_thread(),
1353 session_->socket_factory(),
1354 network_, ip_,
1355 session_->allocator()->min_port(),
1356 session_->allocator()->max_port(),
1357 session_->username(),
1358 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001359 *relay_port, config.credentials, config.priority,
1360 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001361 }
1362 ASSERT(port != NULL);
1363 session_->AddAllocatedPort(port, this, true);
1364 }
1365}
1366
1367void AllocationSequence::OnReadPacket(
1368 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1369 const rtc::SocketAddress& remote_addr,
1370 const rtc::PacketTime& packet_time) {
1371 ASSERT(socket == udp_socket_.get());
1372
1373 bool turn_port_found = false;
1374
1375 // Try to find the TurnPort that matches the remote address. Note that the
1376 // message could be a STUN binding response if the TURN server is also used as
1377 // a STUN server. We don't want to parse every message here to check if it is
1378 // a STUN binding response, so we pass the message to TurnPort regardless of
1379 // the message type. The TurnPort will just ignore the message since it will
1380 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001381 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001382 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001383 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1384 packet_time)) {
1385 return;
1386 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001387 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 }
1389 }
1390
1391 if (udp_port_) {
1392 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1393
1394 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1395 // the TURN server is also a STUN server.
1396 if (!turn_port_found ||
1397 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001398 RTC_DCHECK(udp_port_->SharedSocket());
1399 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1400 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001401 }
1402 }
1403}
1404
1405void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1406 if (udp_port_ == port) {
1407 udp_port_ = NULL;
1408 return;
1409 }
1410
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001411 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1412 if (it != turn_ports_.end()) {
1413 turn_ports_.erase(it);
1414 } else {
1415 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
1416 ASSERT(false);
1417 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001418}
1419
1420// PortConfiguration
1421PortConfiguration::PortConfiguration(
1422 const rtc::SocketAddress& stun_address,
1423 const std::string& username,
1424 const std::string& password)
1425 : stun_address(stun_address), username(username), password(password) {
1426 if (!stun_address.IsNil())
1427 stun_servers.insert(stun_address);
1428}
1429
1430PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1431 const std::string& username,
1432 const std::string& password)
1433 : stun_servers(stun_servers),
1434 username(username),
1435 password(password) {
1436 if (!stun_servers.empty())
1437 stun_address = *(stun_servers.begin());
1438}
1439
1440ServerAddresses PortConfiguration::StunServers() {
1441 if (!stun_address.IsNil() &&
1442 stun_servers.find(stun_address) == stun_servers.end()) {
1443 stun_servers.insert(stun_address);
1444 }
deadbeefc5d0d952015-07-16 10:22:21 -07001445 // Every UDP TURN server should also be used as a STUN server.
1446 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1447 for (const rtc::SocketAddress& turn_server : turn_servers) {
1448 if (stun_servers.find(turn_server) == stun_servers.end()) {
1449 stun_servers.insert(turn_server);
1450 }
1451 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001452 return stun_servers;
1453}
1454
1455void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1456 relays.push_back(config);
1457}
1458
1459bool PortConfiguration::SupportsProtocol(
1460 const RelayServerConfig& relay, ProtocolType type) const {
1461 PortList::const_iterator relay_port;
1462 for (relay_port = relay.ports.begin();
1463 relay_port != relay.ports.end();
1464 ++relay_port) {
1465 if (relay_port->proto == type)
1466 return true;
1467 }
1468 return false;
1469}
1470
1471bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1472 ProtocolType type) const {
1473 for (size_t i = 0; i < relays.size(); ++i) {
1474 if (relays[i].type == turn_type &&
1475 SupportsProtocol(relays[i], type))
1476 return true;
1477 }
1478 return false;
1479}
1480
1481ServerAddresses PortConfiguration::GetRelayServerAddresses(
1482 RelayType turn_type, ProtocolType type) const {
1483 ServerAddresses servers;
1484 for (size_t i = 0; i < relays.size(); ++i) {
1485 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1486 servers.insert(relays[i].ports.front().address);
1487 }
1488 }
1489 return servers;
1490}
1491
1492} // namespace cricket