blob: 549d013a255bb54b2a42c472dcfe1d1612413c26 [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
skvlad1d3c7e02017-01-11 17:50:30 -080017#include "webrtc/api/umametrics.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/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:
nisseeb4ca4e2017-01-12 02:24:27 -080060 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070061 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:
nisseeb4ca4e2017-01-12 02:24:27 -080072 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070073 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) {
nisseede5da42017-01-12 05:15:36 -0800102 RTC_DCHECK(network_manager_ != nullptr);
103 RTC_DCHECK(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) {
nisseede5da42017-01-12 05:15:36 -0800109 RTC_DCHECK(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) {
nisseede5da42017-01-12 05:15:36 -0800117 RTC_DCHECK(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
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700153void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
154 IceRegatheringReason reason) {
155 if (!metrics_observer()) {
156 return;
157 }
158 // If the session has not been taken by an active channel, do not report the
159 // metric.
160 for (auto& allocator_session : pooled_sessions()) {
161 if (allocator_session.get() == session) {
162 return;
163 }
164 }
165
166 metrics_observer()->IncrementEnumCounter(
167 webrtc::kEnumCounterIceRegathering, static_cast<int>(reason),
168 static_cast<int>(IceRegatheringReason::MAX_VALUE));
169}
170
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171BasicPortAllocator::~BasicPortAllocator() {
deadbeef42a42632017-03-10 15:18:00 -0800172 // Our created port allocator sessions depend on us, so destroy our remaining
173 // pooled sessions before anything else.
174 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175}
176
deadbeefc5d0d952015-07-16 10:22:21 -0700177PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 const std::string& content_name, int component,
179 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700180 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000181 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700182 session->SignalIceRegathering.connect(this,
183 &BasicPortAllocator::OnIceRegathering);
184 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185}
186
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700187void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
188 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
189 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700190 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
191 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700192}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000193
194// BasicPortAllocatorSession
195BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700196 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 const std::string& content_name,
198 int component,
199 const std::string& ice_ufrag,
200 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700201 : PortAllocatorSession(content_name,
202 component,
203 ice_ufrag,
204 ice_pwd,
205 allocator->flags()),
206 allocator_(allocator),
207 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000208 socket_factory_(allocator->socket_factory()),
209 allocation_started_(false),
210 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700211 allocation_sequences_created_(false),
212 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000213 allocator_->network_manager()->SignalNetworksChanged.connect(
214 this, &BasicPortAllocatorSession::OnNetworksChanged);
215 allocator_->network_manager()->StartUpdating();
216}
217
218BasicPortAllocatorSession::~BasicPortAllocatorSession() {
219 allocator_->network_manager()->StopUpdating();
220 if (network_thread_ != NULL)
221 network_thread_->Clear(this);
222
Peter Boström0c4e06b2015-10-07 12:23:21 +0200223 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000224 // AllocationSequence should clear it's map entry for turn ports before
225 // ports are destroyed.
226 sequences_[i]->Clear();
227 }
228
229 std::vector<PortData>::iterator it;
230 for (it = ports_.begin(); it != ports_.end(); it++)
231 delete it->port();
232
Peter Boström0c4e06b2015-10-07 12:23:21 +0200233 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 delete configs_[i];
235
Peter Boström0c4e06b2015-10-07 12:23:21 +0200236 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000237 delete sequences_[i];
238}
239
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700240void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
241 if (filter == candidate_filter_) {
242 return;
243 }
244 // We assume the filter will only change from "ALL" to something else.
245 RTC_DCHECK(candidate_filter_ == CF_ALL);
246 candidate_filter_ = filter;
247 for (PortData& port : ports_) {
248 if (!port.has_pairable_candidate()) {
249 continue;
250 }
251 const auto& candidates = port.port()->Candidates();
252 // Setting a filter may cause a ready port to become non-ready
253 // if it no longer has any pairable candidates.
254 if (!std::any_of(candidates.begin(), candidates.end(),
255 [this, &port](const Candidate& candidate) {
256 return CandidatePairable(candidate, port.port());
257 })) {
258 port.set_has_pairable_candidate(false);
259 }
260 }
261}
262
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263void BasicPortAllocatorSession::StartGettingPorts() {
264 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700265 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000266 if (!socket_factory_) {
267 owned_socket_factory_.reset(
268 new rtc::BasicPacketSocketFactory(network_thread_));
269 socket_factory_ = owned_socket_factory_.get();
270 }
271
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700272 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700273
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700274 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700275 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000276}
277
278void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800279 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700280 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700281 // Note: this must be called after ClearGettingPorts because both may set the
282 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700283 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700284}
285
286void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800287 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700289 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700291 }
deadbeefb60a8192016-08-24 15:15:00 -0700292 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700293 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700294}
295
296std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
297 std::vector<rtc::Network*> networks = GetNetworks();
298
299 // A network interface may have both IPv4 and IPv6 networks. Only if
300 // neither of the networks has any connections, the network interface
301 // is considered failed and need to be regathered on.
302 std::set<std::string> networks_with_connection;
303 for (const PortData& data : ports_) {
304 Port* port = data.port();
305 if (!port->connections().empty()) {
306 networks_with_connection.insert(port->Network()->name());
307 }
308 }
309
310 networks.erase(
311 std::remove_if(networks.begin(), networks.end(),
312 [networks_with_connection](rtc::Network* network) {
313 // If a network does not have any connection, it is
314 // considered failed.
315 return networks_with_connection.find(network->name()) !=
316 networks_with_connection.end();
317 }),
318 networks.end());
319 return networks;
320}
321
322void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
323 // Find the list of networks that have no connection.
324 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
325 if (failed_networks.empty()) {
326 return;
327 }
328
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700329 LOG(LS_INFO) << "Regather candidates on failed networks";
330
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700331 // Mark a sequence as "network failed" if its network is in the list of failed
332 // networks, so that it won't be considered as equivalent when the session
333 // regathers ports and candidates.
334 for (AllocationSequence* sequence : sequences_) {
335 if (!sequence->network_failed() &&
336 std::find(failed_networks.begin(), failed_networks.end(),
337 sequence->network()) != failed_networks.end()) {
338 sequence->set_network_failed();
339 }
340 }
341 // Remove ports from being used locally and send signaling to remove
342 // the candidates on the remote side.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700343 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
344 if (!ports_to_prune.empty()) {
345 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
346 << " ports because their networks failed";
347 PrunePortsAndRemoveCandidates(ports_to_prune);
348 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700349
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700350 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
351 SignalIceRegathering(this, IceRegatheringReason::NETWORK_FAILURE);
352
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700353 DoAllocate();
354 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355}
356
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700357std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
358 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700359 for (const PortData& data : ports_) {
360 if (data.ready()) {
361 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700362 }
363 }
364 return ret;
365}
366
367std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
368 std::vector<Candidate> candidates;
369 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700370 if (!data.ready()) {
371 continue;
372 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700373 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700374 }
375 return candidates;
376}
377
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700378void BasicPortAllocatorSession::GetCandidatesFromPort(
379 const PortData& data,
380 std::vector<Candidate>* candidates) const {
381 RTC_CHECK(candidates != nullptr);
382 for (const Candidate& candidate : data.port()->Candidates()) {
383 if (!CheckCandidateFilter(candidate)) {
384 continue;
385 }
386 ProtocolType pvalue;
387 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
388 !data.sequence()->ProtocolEnabled(pvalue)) {
389 continue;
390 }
391 candidates->push_back(SanitizeRelatedAddress(candidate));
392 }
393}
394
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700395Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
396 const Candidate& c) const {
397 Candidate copy = c;
398 // If adapter enumeration is disabled or host candidates are disabled,
399 // clear the raddr of STUN candidates to avoid local address leakage.
400 bool filter_stun_related_address =
401 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
402 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
403 !(candidate_filter_ & CF_HOST);
404 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
405 // to avoid reflexive address leakage.
406 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
407 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
408 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
409 copy.set_related_address(
410 rtc::EmptySocketAddressWithFamily(copy.address().family()));
411 }
412 return copy;
413}
414
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700415bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
416 // Done only if all required AllocationSequence objects
417 // are created.
418 if (!allocation_sequences_created_) {
419 return false;
420 }
421
422 // Check that all port allocation sequences are complete (not running).
423 if (std::any_of(sequences_.begin(), sequences_.end(),
424 [](const AllocationSequence* sequence) {
425 return sequence->state() == AllocationSequence::kRunning;
426 })) {
427 return false;
428 }
429
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700430 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700431 // expected candidates. Session will trigger candidates allocation complete
432 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700433 return std::none_of(ports_.begin(), ports_.end(),
434 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700435}
436
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000437void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
438 switch (message->message_id) {
439 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800440 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000441 GetPortConfigurations();
442 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800444 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000445 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
446 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000447 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800448 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449 OnAllocate();
450 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800452 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000453 OnAllocationSequenceObjectsCreated();
454 break;
455 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800456 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457 OnConfigStop();
458 break;
459 default:
nissec80e7412017-01-11 05:56:46 -0800460 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 }
462}
463
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700464void BasicPortAllocatorSession::UpdateIceParametersInternal() {
465 for (PortData& port : ports_) {
466 port.port()->set_content_name(content_name());
467 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
468 }
469}
470
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471void BasicPortAllocatorSession::GetPortConfigurations() {
472 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
473 username(),
474 password());
475
deadbeef653b8e02015-11-11 12:55:10 -0800476 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
477 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000478 }
479 ConfigReady(config);
480}
481
482void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700483 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000484}
485
486// Adds a configuration to the list.
487void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800488 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800490 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000491
492 AllocatePorts();
493}
494
495void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800496 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000497
498 // If any of the allocated ports have not completed the candidates allocation,
499 // mark those as error. Since session doesn't need any new candidates
500 // at this stage of the allocation, it's safe to discard any new candidates.
501 bool send_signal = false;
502 for (std::vector<PortData>::iterator it = ports_.begin();
503 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700504 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000505 // Updating port state to error, which didn't finish allocating candidates
506 // yet.
507 it->set_error();
508 send_signal = true;
509 }
510 }
511
512 // Did we stop any running sequences?
513 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
514 it != sequences_.end() && !send_signal; ++it) {
515 if ((*it)->state() == AllocationSequence::kStopped) {
516 send_signal = true;
517 }
518 }
519
520 // If we stopped anything that was running, send a done signal now.
521 if (send_signal) {
522 MaybeSignalCandidatesAllocationDone();
523 }
524}
525
526void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800527 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700528 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000529}
530
531void BasicPortAllocatorSession::OnAllocate() {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700532 if (network_manager_started_ && !IsStopped())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000533 DoAllocate();
534
535 allocation_started_ = true;
536}
537
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700538std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
539 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700540 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800541 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700542 // If the network permission state is BLOCKED, we just act as if the flag has
543 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700544 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700545 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700546 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
547 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000548 // If the adapter enumeration is disabled, we'll just bind to any address
549 // instead of specific NIC. This is to ensure the same routing for http
550 // traffic by OS is also used here to avoid any local or public IP leakage
551 // during stun process.
552 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700553 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000554 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700555 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800556 // If network enumeration fails, use the ANY address as a fallback, so we
557 // can at least try gathering candidates using the default route chosen by
deadbeef1ee21252017-06-13 15:49:45 -0700558 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
559 // set, we'll use ANY address candidates either way.
560 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
deadbeefe97389c2016-12-23 01:43:45 -0800561 network_manager->GetAnyAddressNetworks(&networks);
562 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000563 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700564 networks.erase(std::remove_if(networks.begin(), networks.end(),
565 [this](rtc::Network* network) {
566 return allocator_->network_ignore_mask() &
567 network->type();
568 }),
569 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700570
571 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
572 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700573 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700574 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
575 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700576 networks.erase(std::remove_if(networks.begin(), networks.end(),
577 [lowest_cost](rtc::Network* network) {
578 return network->GetCost() >
579 lowest_cost + rtc::kNetworkCostLow;
580 }),
581 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700582 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700583 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700584}
585
586// For each network, see if we have a sequence that covers it already. If not,
587// create a new sequence to create the appropriate ports.
588void BasicPortAllocatorSession::DoAllocate() {
589 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700590 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000591 if (networks.empty()) {
592 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
593 done_signal_needed = true;
594 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700595 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700596 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200597 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200598 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000599 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
600 // If all the ports are disabled we should just fire the allocation
601 // done event and return.
602 done_signal_needed = true;
603 break;
604 }
605
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000606 if (!config || config->relays.empty()) {
607 // No relay ports specified in this config.
608 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
609 }
610
611 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 // Skip IPv6 networks unless the flag's been set.
614 continue;
615 }
616
zhihuangb09b3f92017-03-07 14:40:51 -0800617 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
618 networks[i]->GetBestIP().family() == AF_INET6 &&
619 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
620 // Skip IPv6 Wi-Fi networks unless the flag's been set.
621 continue;
622 }
623
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000624 // Disable phases that would only create ports equivalent to
625 // ones that we have already made.
626 DisableEquivalentPhases(networks[i], config, &sequence_flags);
627
628 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
629 // New AllocationSequence would have nothing to do, so don't make it.
630 continue;
631 }
632
633 AllocationSequence* sequence =
634 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 sequence->SignalPortAllocationComplete.connect(
636 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700637 sequence->Init();
638 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700640 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 }
642 }
643 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700644 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645 }
646}
647
648void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700649 std::vector<rtc::Network*> networks = GetNetworks();
650 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700651 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700652 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700653 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700654 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700655 std::find(networks.begin(), networks.end(), sequence->network()) ==
656 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700657 sequence->OnNetworkFailed();
658 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700659 }
660 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700661 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
662 if (!ports_to_prune.empty()) {
663 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
664 << " ports because their networks were gone";
665 PrunePortsAndRemoveCandidates(ports_to_prune);
666 }
honghaiz8c404fa2015-09-28 07:59:43 -0700667
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700668 if (allocation_started_ && !IsStopped()) {
669 if (network_manager_started_) {
670 // If the network manager has started, it must be regathering.
671 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
672 }
673 DoAllocate();
674 }
675
Honghai Zhang5048f572016-08-23 15:47:33 -0700676 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700677 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700678 network_manager_started_ = true;
679 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680}
681
682void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200683 rtc::Network* network,
684 PortConfiguration* config,
685 uint32_t* flags) {
686 for (uint32_t i = 0; i < sequences_.size() &&
687 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
688 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689 sequences_[i]->DisableEquivalentPhases(network, config, flags);
690 }
691}
692
693void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
694 AllocationSequence * seq,
695 bool prepare_address) {
696 if (!port)
697 return;
698
699 LOG(LS_INFO) << "Adding allocated port for " << content_name();
700 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700701 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700703 if (allocator_->proxy().type != rtc::PROXY_NONE)
704 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700705 port->set_send_retransmit_count_attribute(
706 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000707
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000708 PortData data(port, seq);
709 ports_.push_back(data);
710
711 port->SignalCandidateReady.connect(
712 this, &BasicPortAllocatorSession::OnCandidateReady);
713 port->SignalPortComplete.connect(this,
714 &BasicPortAllocatorSession::OnPortComplete);
715 port->SignalDestroyed.connect(this,
716 &BasicPortAllocatorSession::OnPortDestroyed);
717 port->SignalPortError.connect(
718 this, &BasicPortAllocatorSession::OnPortError);
719 LOG_J(LS_INFO, port) << "Added port to allocator";
720
721 if (prepare_address)
722 port->PrepareAddress();
723}
724
725void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
726 allocation_sequences_created_ = true;
727 // Send candidate allocation complete signal if we have no sequences.
728 MaybeSignalCandidatesAllocationDone();
729}
730
731void BasicPortAllocatorSession::OnCandidateReady(
732 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800733 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800735 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700736 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700738 // already done with gathering.
739 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700740 LOG(LS_WARNING)
741 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700742 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700743 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700744
danilchapf4e8cf02016-06-30 01:55:03 -0700745 // Mark that the port has a pairable candidate, either because we have a
746 // usable candidate from the port, or simply because the port is bound to the
747 // any address and therefore has no host candidate. This will trigger the port
748 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700749 // checks. If port has already been marked as having a pairable candidate,
750 // do nothing here.
751 // Note: We should check whether any candidates may become ready after this
752 // because there we will check whether the candidate is generated by the ready
753 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700754 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700755 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700756 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700757
758 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700759 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700760 }
761 // If the current port is not pruned yet, SignalPortReady.
762 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700763 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700764 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700765 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700766 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700767 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700768
769 ProtocolType pvalue;
770 bool candidate_protocol_enabled =
771 StringToProto(c.protocol().c_str(), &pvalue) &&
772 data->sequence()->ProtocolEnabled(pvalue);
773
774 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
775 std::vector<Candidate> candidates;
776 candidates.push_back(SanitizeRelatedAddress(c));
777 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700778 } else if (!candidate_protocol_enabled) {
779 LOG(LS_INFO)
780 << "Not yet signaling candidate because protocol is not yet enabled.";
781 } else {
782 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700783 }
784
785 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700786 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700787 MaybeSignalCandidatesAllocationDone();
788 }
789}
790
791Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
792 const std::string& network_name) const {
793 Port* best_turn_port = nullptr;
794 for (const PortData& data : ports_) {
795 if (data.port()->Network()->name() == network_name &&
796 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
797 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
798 best_turn_port = data.port();
799 }
800 }
801 return best_turn_port;
802}
803
804bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700805 // Note: We determine the same network based only on their network names. So
806 // if an IPv4 address and an IPv6 address have the same network name, they
807 // are considered the same network here.
808 const std::string& network_name = newly_pairable_turn_port->Network()->name();
809 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
810 // |port| is already in the list of ports, so the best port cannot be nullptr.
811 RTC_CHECK(best_turn_port != nullptr);
812
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700813 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700814 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700815 for (PortData& data : ports_) {
816 if (data.port()->Network()->name() == network_name &&
817 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
818 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700819 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700820 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700821 // These ports will be pruned in PrunePortsAndRemoveCandidates.
822 ports_to_prune.push_back(&data);
823 } else {
824 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700825 }
826 }
827 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700828
829 if (!ports_to_prune.empty()) {
830 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
831 << " low-priority TURN ports";
832 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700833 }
834 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000835}
836
Honghai Zhanga74363c2016-07-28 18:06:15 -0700837void BasicPortAllocatorSession::PruneAllPorts() {
838 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700839 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700840 }
841}
842
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000843void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800844 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700845 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000846 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800847 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848
849 // Ignore any late signals.
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 // Moving to COMPLETE state.
855 data->set_complete();
856 // Send candidate allocation complete signal if this was the last port.
857 MaybeSignalCandidatesAllocationDone();
858}
859
860void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800861 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700862 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800864 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000865 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700866 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000867 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700868 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000869
870 // SignalAddressError is currently sent from StunPort/TurnPort.
871 // But this signal itself is generic.
872 data->set_error();
873 // Send candidate allocation complete signal if this was the last port.
874 MaybeSignalCandidatesAllocationDone();
875}
876
877void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
878 ProtocolType proto) {
879 std::vector<Candidate> candidates;
880 for (std::vector<PortData>::iterator it = ports_.begin();
881 it != ports_.end(); ++it) {
882 if (it->sequence() != seq)
883 continue;
884
885 const std::vector<Candidate>& potentials = it->port()->Candidates();
886 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700887 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000888 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700889 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000890 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700891 bool candidate_protocol_enabled =
892 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
893 pvalue == proto;
894 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700895 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
896 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000897 candidates.push_back(potentials[i]);
898 }
899 }
900 }
901
902 if (!candidates.empty()) {
903 SignalCandidatesReady(this, candidates);
904 }
905}
906
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700907bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700908 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000909
910 // When binding to any address, before sending packets out, the getsockname
911 // returns all 0s, but after sending packets, it'll be the NIC used to
912 // send. All 0s is not a valid ICE candidate address and should be filtered
913 // out.
914 if (c.address().IsAnyIP()) {
915 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000916 }
917
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000918 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000919 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000920 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000921 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000922 } else if (c.type() == LOCAL_PORT_TYPE) {
923 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
924 // We allow host candidates if the filter allows server-reflexive
925 // candidates and the candidate is a public IP. Because we don't generate
926 // server-reflexive candidates if they have the same IP as the host
927 // candidate (i.e. when the host candidate is a public IP), filtering to
928 // only server-reflexive candidates won't work right when the host
929 // candidates have public IPs.
930 return true;
931 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000932
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000933 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000934 }
935 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000936}
937
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700938bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
939 const Port* port) const {
940 bool candidate_signalable = CheckCandidateFilter(c);
941
942 // When device enumeration is disabled (to prevent non-default IP addresses
943 // from leaking), we ping from some local candidates even though we don't
944 // signal them. However, if host candidates are also disabled (for example, to
945 // prevent even default IP addresses from leaking), we still don't want to
946 // ping from them, even if device enumeration is disabled. Thus, we check for
947 // both device enumeration and host candidates being disabled.
948 bool network_enumeration_disabled = c.address().IsAnyIP();
949 bool can_ping_from_candidate =
950 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
951 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
952
953 return candidate_signalable ||
954 (network_enumeration_disabled && can_ping_from_candidate &&
955 !host_candidates_disabled);
956}
957
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000958void BasicPortAllocatorSession::OnPortAllocationComplete(
959 AllocationSequence* seq) {
960 // Send candidate allocation complete signal if all ports are done.
961 MaybeSignalCandidatesAllocationDone();
962}
963
964void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700965 if (CandidatesAllocationDone()) {
966 if (pooled()) {
967 LOG(LS_INFO) << "All candidates gathered for pooled session.";
968 } else {
969 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
970 << component() << ":" << generation();
971 }
972 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000974}
975
976void BasicPortAllocatorSession::OnPortDestroyed(
977 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800978 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000979 for (std::vector<PortData>::iterator iter = ports_.begin();
980 iter != ports_.end(); ++iter) {
981 if (port == iter->port()) {
982 ports_.erase(iter);
983 LOG_J(LS_INFO, port) << "Removed port from allocator ("
984 << static_cast<int>(ports_.size()) << " remaining)";
985 return;
986 }
987 }
nissec80e7412017-01-11 05:56:46 -0800988 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000989}
990
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000991BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
992 Port* port) {
993 for (std::vector<PortData>::iterator it = ports_.begin();
994 it != ports_.end(); ++it) {
995 if (it->port() == port) {
996 return &*it;
997 }
998 }
999 return NULL;
1000}
1001
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001002std::vector<BasicPortAllocatorSession::PortData*>
1003BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001004 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001005 std::vector<PortData*> unpruned_ports;
1006 for (PortData& port : ports_) {
1007 if (!port.pruned() &&
1008 std::find(networks.begin(), networks.end(),
1009 port.sequence()->network()) != networks.end()) {
1010 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001011 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001012 }
1013 return unpruned_ports;
1014}
1015
1016void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1017 const std::vector<PortData*>& port_data_list) {
1018 std::vector<PortInterface*> pruned_ports;
1019 std::vector<Candidate> removed_candidates;
1020 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001021 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001022 data->Prune();
1023 pruned_ports.push_back(data->port());
1024 if (data->has_pairable_candidate()) {
1025 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001026 // Mark the port as having no pairable candidates so that its candidates
1027 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001028 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001029 }
1030 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001031 if (!pruned_ports.empty()) {
1032 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001033 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001034 if (!removed_candidates.empty()) {
1035 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1036 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001037 }
1038}
1039
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040// AllocationSequence
1041
1042AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1043 rtc::Network* network,
1044 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001045 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 : session_(session),
1047 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001049 config_(config),
1050 state_(kInit),
1051 flags_(flags),
1052 udp_socket_(),
1053 udp_port_(NULL),
1054 phase_(0) {
1055}
1056
Honghai Zhang5048f572016-08-23 15:47:33 -07001057void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001058 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1059 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1060 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1061 session_->allocator()->max_port()));
1062 if (udp_socket_) {
1063 udp_socket_->SignalReadPacket.connect(
1064 this, &AllocationSequence::OnReadPacket);
1065 }
1066 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1067 // are next available options to setup a communication channel.
1068 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001069}
1070
1071void AllocationSequence::Clear() {
1072 udp_port_ = NULL;
1073 turn_ports_.clear();
1074}
1075
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001076void AllocationSequence::OnNetworkFailed() {
1077 RTC_DCHECK(!network_failed_);
1078 network_failed_ = true;
1079 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001080 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001081}
1082
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001083AllocationSequence::~AllocationSequence() {
1084 session_->network_thread()->Clear(this);
1085}
1086
1087void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001088 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001089 if (network_failed_) {
1090 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001091 // it won't be equivalent to the new network.
1092 return;
1093 }
1094
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001095 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001096 // Different network setup; nothing is equivalent.
1097 return;
1098 }
1099
1100 // Else turn off the stuff that we've already got covered.
1101
1102 // Every config implicitly specifies local, so turn that off right away.
1103 *flags |= PORTALLOCATOR_DISABLE_UDP;
1104 *flags |= PORTALLOCATOR_DISABLE_TCP;
1105
1106 if (config_ && config) {
1107 if (config_->StunServers() == config->StunServers()) {
1108 // Already got this STUN servers covered.
1109 *flags |= PORTALLOCATOR_DISABLE_STUN;
1110 }
1111 if (!config_->relays.empty()) {
1112 // Already got relays covered.
1113 // NOTE: This will even skip a _different_ set of relay servers if we
1114 // were to be given one, but that never happens in our codebase. Should
1115 // probably get rid of the list in PortConfiguration and just keep a
1116 // single relay server in each one.
1117 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1118 }
1119 }
1120}
1121
1122void AllocationSequence::Start() {
1123 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001124 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001125}
1126
1127void AllocationSequence::Stop() {
1128 // If the port is completed, don't set it to stopped.
1129 if (state_ == kRunning) {
1130 state_ = kStopped;
1131 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1132 }
1133}
1134
1135void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001136 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1137 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001138
1139 const char* const PHASE_NAMES[kNumPhases] = {
1140 "Udp", "Relay", "Tcp", "SslTcp"
1141 };
1142
1143 // Perform all of the phases in the current step.
1144 LOG_J(LS_INFO, network_) << "Allocation Phase="
1145 << PHASE_NAMES[phase_];
1146
1147 switch (phase_) {
1148 case PHASE_UDP:
1149 CreateUDPPorts();
1150 CreateStunPorts();
1151 EnableProtocol(PROTO_UDP);
1152 break;
1153
1154 case PHASE_RELAY:
1155 CreateRelayPorts();
1156 break;
1157
1158 case PHASE_TCP:
1159 CreateTCPPorts();
1160 EnableProtocol(PROTO_TCP);
1161 break;
1162
1163 case PHASE_SSLTCP:
1164 state_ = kCompleted;
1165 EnableProtocol(PROTO_SSLTCP);
1166 break;
1167
1168 default:
nissec80e7412017-01-11 05:56:46 -08001169 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001170 }
1171
1172 if (state() == kRunning) {
1173 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001174 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1175 session_->allocator()->step_delay(),
1176 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001177 } else {
1178 // If all phases in AllocationSequence are completed, no allocation
1179 // steps needed further. Canceling pending signal.
1180 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1181 SignalPortAllocationComplete(this);
1182 }
1183}
1184
1185void AllocationSequence::EnableProtocol(ProtocolType proto) {
1186 if (!ProtocolEnabled(proto)) {
1187 protocols_.push_back(proto);
1188 session_->OnProtocolEnabled(this, proto);
1189 }
1190}
1191
1192bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1193 for (ProtocolList::const_iterator it = protocols_.begin();
1194 it != protocols_.end(); ++it) {
1195 if (*it == proto)
1196 return true;
1197 }
1198 return false;
1199}
1200
1201void AllocationSequence::CreateUDPPorts() {
1202 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1203 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1204 return;
1205 }
1206
1207 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1208 // is enabled completely.
1209 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001210 bool emit_local_candidate_for_anyaddress =
1211 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001212 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001213 port = UDPPort::Create(
1214 session_->network_thread(), session_->socket_factory(), network_,
1215 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001216 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001218 port = UDPPort::Create(
1219 session_->network_thread(), session_->socket_factory(), network_, ip_,
1220 session_->allocator()->min_port(), session_->allocator()->max_port(),
1221 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001222 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001223 }
1224
1225 if (port) {
1226 // If shared socket is enabled, STUN candidate will be allocated by the
1227 // UDPPort.
1228 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1229 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001230 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001231
1232 // If STUN is not disabled, setting stun server address to port.
1233 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001234 if (config_ && !config_->StunServers().empty()) {
1235 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1236 << "STUN candidate generation.";
1237 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001238 }
1239 }
1240 }
1241
1242 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001243 }
1244}
1245
1246void AllocationSequence::CreateTCPPorts() {
1247 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1248 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1249 return;
1250 }
1251
1252 Port* port = TCPPort::Create(session_->network_thread(),
1253 session_->socket_factory(),
1254 network_, ip_,
1255 session_->allocator()->min_port(),
1256 session_->allocator()->max_port(),
1257 session_->username(), session_->password(),
1258 session_->allocator()->allow_tcp_listen());
1259 if (port) {
1260 session_->AddAllocatedPort(port, this, true);
1261 // Since TCPPort is not created using shared socket, |port| will not be
1262 // added to the dequeue.
1263 }
1264}
1265
1266void AllocationSequence::CreateStunPorts() {
1267 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1268 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1269 return;
1270 }
1271
1272 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1273 return;
1274 }
1275
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001276 if (!(config_ && !config_->StunServers().empty())) {
1277 LOG(LS_WARNING)
1278 << "AllocationSequence: No STUN server configured, skipping.";
1279 return;
1280 }
1281
1282 StunPort* port = StunPort::Create(session_->network_thread(),
1283 session_->socket_factory(),
1284 network_, ip_,
1285 session_->allocator()->min_port(),
1286 session_->allocator()->max_port(),
1287 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001288 config_->StunServers(),
1289 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001290 if (port) {
1291 session_->AddAllocatedPort(port, this, true);
1292 // Since StunPort is not created using shared socket, |port| will not be
1293 // added to the dequeue.
1294 }
1295}
1296
1297void AllocationSequence::CreateRelayPorts() {
1298 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1299 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1300 return;
1301 }
1302
1303 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1304 // ought to have a relay list for them here.
nisseede5da42017-01-12 05:15:36 -08001305 RTC_DCHECK(config_ && !config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001306 if (!(config_ && !config_->relays.empty())) {
1307 LOG(LS_WARNING)
1308 << "AllocationSequence: No relay server configured, skipping.";
1309 return;
1310 }
1311
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001312 for (RelayServerConfig& relay : config_->relays) {
1313 if (relay.type == RELAY_GTURN) {
1314 CreateGturnPort(relay);
1315 } else if (relay.type == RELAY_TURN) {
1316 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001317 } else {
nissec80e7412017-01-11 05:56:46 -08001318 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001319 }
1320 }
1321}
1322
1323void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1324 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1325 RelayPort* port = RelayPort::Create(session_->network_thread(),
1326 session_->socket_factory(),
1327 network_, ip_,
1328 session_->allocator()->min_port(),
1329 session_->allocator()->max_port(),
1330 config_->username, config_->password);
1331 if (port) {
1332 // Since RelayPort is not created using shared socket, |port| will not be
1333 // added to the dequeue.
1334 // Note: We must add the allocated port before we add addresses because
1335 // the latter will create candidates that need name and preference
1336 // settings. However, we also can't prepare the address (normally
1337 // done by AddAllocatedPort) until we have these addresses. So we
1338 // wait to do that until below.
1339 session_->AddAllocatedPort(port, this, false);
1340
1341 // Add the addresses of this protocol.
1342 PortList::const_iterator relay_port;
1343 for (relay_port = config.ports.begin();
1344 relay_port != config.ports.end();
1345 ++relay_port) {
1346 port->AddServerAddress(*relay_port);
1347 port->AddExternalAddress(*relay_port);
1348 }
1349 // Start fetching an address for this port.
1350 port->PrepareAddress();
1351 }
1352}
1353
1354void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1355 PortList::const_iterator relay_port;
1356 for (relay_port = config.ports.begin();
1357 relay_port != config.ports.end(); ++relay_port) {
1358 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001359
1360 // Skip UDP connections to relay servers if it's disallowed.
1361 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1362 relay_port->proto == PROTO_UDP) {
1363 continue;
1364 }
1365
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001366 // Do not create a port if the server address family is known and does
1367 // not match the local IP address family.
1368 int server_ip_family = relay_port->address.ipaddr().family();
1369 int local_ip_family = ip_.family();
1370 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1371 LOG(LS_INFO) << "Server and local address families are not compatible. "
1372 << "Server address: "
1373 << relay_port->address.ipaddr().ToString()
1374 << " Local address: " << ip_.ToString();
1375 continue;
1376 }
1377
1378
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379 // Shared socket mode must be enabled only for UDP based ports. Hence
1380 // don't pass shared socket for ports which will create TCP sockets.
1381 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1382 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1383 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001384 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385 port = TurnPort::Create(session_->network_thread(),
1386 session_->socket_factory(),
1387 network_, udp_socket_.get(),
1388 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001389 *relay_port, config.credentials, config.priority,
1390 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001391 turn_ports_.push_back(port);
1392 // Listen to the port destroyed signal, to allow AllocationSequence to
1393 // remove entrt from it's map.
1394 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1395 } else {
1396 port = TurnPort::Create(session_->network_thread(),
1397 session_->socket_factory(),
1398 network_, ip_,
1399 session_->allocator()->min_port(),
1400 session_->allocator()->max_port(),
1401 session_->username(),
1402 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001403 *relay_port, config.credentials, config.priority,
1404 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001405 }
nisseede5da42017-01-12 05:15:36 -08001406 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001407 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001408 session_->AddAllocatedPort(port, this, true);
1409 }
1410}
1411
1412void AllocationSequence::OnReadPacket(
1413 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1414 const rtc::SocketAddress& remote_addr,
1415 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001416 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001417
1418 bool turn_port_found = false;
1419
1420 // Try to find the TurnPort that matches the remote address. Note that the
1421 // message could be a STUN binding response if the TURN server is also used as
1422 // a STUN server. We don't want to parse every message here to check if it is
1423 // a STUN binding response, so we pass the message to TurnPort regardless of
1424 // the message type. The TurnPort will just ignore the message since it will
1425 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001426 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001427 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001428 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1429 packet_time)) {
1430 return;
1431 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001432 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001433 }
1434 }
1435
1436 if (udp_port_) {
1437 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1438
1439 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1440 // the TURN server is also a STUN server.
1441 if (!turn_port_found ||
1442 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001443 RTC_DCHECK(udp_port_->SharedSocket());
1444 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1445 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001446 }
1447 }
1448}
1449
1450void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1451 if (udp_port_ == port) {
1452 udp_port_ = NULL;
1453 return;
1454 }
1455
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001456 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1457 if (it != turn_ports_.end()) {
1458 turn_ports_.erase(it);
1459 } else {
1460 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001461 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001462 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001463}
1464
1465// PortConfiguration
1466PortConfiguration::PortConfiguration(
1467 const rtc::SocketAddress& stun_address,
1468 const std::string& username,
1469 const std::string& password)
1470 : stun_address(stun_address), username(username), password(password) {
1471 if (!stun_address.IsNil())
1472 stun_servers.insert(stun_address);
1473}
1474
1475PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1476 const std::string& username,
1477 const std::string& password)
1478 : stun_servers(stun_servers),
1479 username(username),
1480 password(password) {
1481 if (!stun_servers.empty())
1482 stun_address = *(stun_servers.begin());
1483}
1484
1485ServerAddresses PortConfiguration::StunServers() {
1486 if (!stun_address.IsNil() &&
1487 stun_servers.find(stun_address) == stun_servers.end()) {
1488 stun_servers.insert(stun_address);
1489 }
deadbeefc5d0d952015-07-16 10:22:21 -07001490 // Every UDP TURN server should also be used as a STUN server.
1491 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1492 for (const rtc::SocketAddress& turn_server : turn_servers) {
1493 if (stun_servers.find(turn_server) == stun_servers.end()) {
1494 stun_servers.insert(turn_server);
1495 }
1496 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001497 return stun_servers;
1498}
1499
1500void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1501 relays.push_back(config);
1502}
1503
1504bool PortConfiguration::SupportsProtocol(
1505 const RelayServerConfig& relay, ProtocolType type) const {
1506 PortList::const_iterator relay_port;
1507 for (relay_port = relay.ports.begin();
1508 relay_port != relay.ports.end();
1509 ++relay_port) {
1510 if (relay_port->proto == type)
1511 return true;
1512 }
1513 return false;
1514}
1515
1516bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1517 ProtocolType type) const {
1518 for (size_t i = 0; i < relays.size(); ++i) {
1519 if (relays[i].type == turn_type &&
1520 SupportsProtocol(relays[i], type))
1521 return true;
1522 }
1523 return false;
1524}
1525
1526ServerAddresses PortConfiguration::GetRelayServerAddresses(
1527 RelayType turn_type, ProtocolType type) const {
1528 ServerAddresses servers;
1529 for (size_t i = 0; i < relays.size(); ++i) {
1530 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1531 servers.insert(relays[i].ports.front().address);
1532 }
1533 }
1534 return servers;
1535}
1536
1537} // namespace cricket