blob: 94de2b55f54fbd772fca7c776e8ba6254ede47e6 [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
558 // the OS.
559 if (networks.empty()) {
560 network_manager->GetAnyAddressNetworks(&networks);
561 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000562 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700563 networks.erase(std::remove_if(networks.begin(), networks.end(),
564 [this](rtc::Network* network) {
565 return allocator_->network_ignore_mask() &
566 network->type();
567 }),
568 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700569
570 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
571 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700572 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700573 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
574 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700575 networks.erase(std::remove_if(networks.begin(), networks.end(),
576 [lowest_cost](rtc::Network* network) {
577 return network->GetCost() >
578 lowest_cost + rtc::kNetworkCostLow;
579 }),
580 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700581 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700582 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700583}
584
585// For each network, see if we have a sequence that covers it already. If not,
586// create a new sequence to create the appropriate ports.
587void BasicPortAllocatorSession::DoAllocate() {
588 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700589 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 if (networks.empty()) {
591 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
592 done_signal_needed = true;
593 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700594 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700595 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200596 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200597 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
599 // If all the ports are disabled we should just fire the allocation
600 // done event and return.
601 done_signal_needed = true;
602 break;
603 }
604
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000605 if (!config || config->relays.empty()) {
606 // No relay ports specified in this config.
607 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
608 }
609
610 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612 // Skip IPv6 networks unless the flag's been set.
613 continue;
614 }
615
zhihuangb09b3f92017-03-07 14:40:51 -0800616 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
617 networks[i]->GetBestIP().family() == AF_INET6 &&
618 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
619 // Skip IPv6 Wi-Fi networks unless the flag's been set.
620 continue;
621 }
622
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623 // Disable phases that would only create ports equivalent to
624 // ones that we have already made.
625 DisableEquivalentPhases(networks[i], config, &sequence_flags);
626
627 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
628 // New AllocationSequence would have nothing to do, so don't make it.
629 continue;
630 }
631
632 AllocationSequence* sequence =
633 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 sequence->SignalPortAllocationComplete.connect(
635 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700636 sequence->Init();
637 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000638 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700639 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640 }
641 }
642 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700643 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000644 }
645}
646
647void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700648 std::vector<rtc::Network*> networks = GetNetworks();
649 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700650 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700651 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700652 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700653 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700654 std::find(networks.begin(), networks.end(), sequence->network()) ==
655 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700656 sequence->OnNetworkFailed();
657 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700658 }
659 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700660 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
661 if (!ports_to_prune.empty()) {
662 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
663 << " ports because their networks were gone";
664 PrunePortsAndRemoveCandidates(ports_to_prune);
665 }
honghaiz8c404fa2015-09-28 07:59:43 -0700666
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700667 if (allocation_started_ && !IsStopped()) {
668 if (network_manager_started_) {
669 // If the network manager has started, it must be regathering.
670 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
671 }
672 DoAllocate();
673 }
674
Honghai Zhang5048f572016-08-23 15:47:33 -0700675 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700676 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700677 network_manager_started_ = true;
678 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000679}
680
681void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200682 rtc::Network* network,
683 PortConfiguration* config,
684 uint32_t* flags) {
685 for (uint32_t i = 0; i < sequences_.size() &&
686 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
687 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000688 sequences_[i]->DisableEquivalentPhases(network, config, flags);
689 }
690}
691
692void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
693 AllocationSequence * seq,
694 bool prepare_address) {
695 if (!port)
696 return;
697
698 LOG(LS_INFO) << "Adding allocated port for " << content_name();
699 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700700 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000701 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700702 if (allocator_->proxy().type != rtc::PROXY_NONE)
703 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700704 port->set_send_retransmit_count_attribute(
705 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000706
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000707 PortData data(port, seq);
708 ports_.push_back(data);
709
710 port->SignalCandidateReady.connect(
711 this, &BasicPortAllocatorSession::OnCandidateReady);
712 port->SignalPortComplete.connect(this,
713 &BasicPortAllocatorSession::OnPortComplete);
714 port->SignalDestroyed.connect(this,
715 &BasicPortAllocatorSession::OnPortDestroyed);
716 port->SignalPortError.connect(
717 this, &BasicPortAllocatorSession::OnPortError);
718 LOG_J(LS_INFO, port) << "Added port to allocator";
719
720 if (prepare_address)
721 port->PrepareAddress();
722}
723
724void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
725 allocation_sequences_created_ = true;
726 // Send candidate allocation complete signal if we have no sequences.
727 MaybeSignalCandidatesAllocationDone();
728}
729
730void BasicPortAllocatorSession::OnCandidateReady(
731 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800732 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000733 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800734 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700735 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000736 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700737 // already done with gathering.
738 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700739 LOG(LS_WARNING)
740 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700741 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700742 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700743
danilchapf4e8cf02016-06-30 01:55:03 -0700744 // Mark that the port has a pairable candidate, either because we have a
745 // usable candidate from the port, or simply because the port is bound to the
746 // any address and therefore has no host candidate. This will trigger the port
747 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700748 // checks. If port has already been marked as having a pairable candidate,
749 // do nothing here.
750 // Note: We should check whether any candidates may become ready after this
751 // because there we will check whether the candidate is generated by the ready
752 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700753 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700754 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700755 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700756
757 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700758 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700759 }
760 // If the current port is not pruned yet, SignalPortReady.
761 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700762 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700763 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700764 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700765 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700766 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700767
768 ProtocolType pvalue;
769 bool candidate_protocol_enabled =
770 StringToProto(c.protocol().c_str(), &pvalue) &&
771 data->sequence()->ProtocolEnabled(pvalue);
772
773 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
774 std::vector<Candidate> candidates;
775 candidates.push_back(SanitizeRelatedAddress(c));
776 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700777 } else if (!candidate_protocol_enabled) {
778 LOG(LS_INFO)
779 << "Not yet signaling candidate because protocol is not yet enabled.";
780 } else {
781 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700782 }
783
784 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700785 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700786 MaybeSignalCandidatesAllocationDone();
787 }
788}
789
790Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
791 const std::string& network_name) const {
792 Port* best_turn_port = nullptr;
793 for (const PortData& data : ports_) {
794 if (data.port()->Network()->name() == network_name &&
795 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
796 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
797 best_turn_port = data.port();
798 }
799 }
800 return best_turn_port;
801}
802
803bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700804 // Note: We determine the same network based only on their network names. So
805 // if an IPv4 address and an IPv6 address have the same network name, they
806 // are considered the same network here.
807 const std::string& network_name = newly_pairable_turn_port->Network()->name();
808 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
809 // |port| is already in the list of ports, so the best port cannot be nullptr.
810 RTC_CHECK(best_turn_port != nullptr);
811
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700812 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700813 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700814 for (PortData& data : ports_) {
815 if (data.port()->Network()->name() == network_name &&
816 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
817 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700818 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700819 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700820 // These ports will be pruned in PrunePortsAndRemoveCandidates.
821 ports_to_prune.push_back(&data);
822 } else {
823 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700824 }
825 }
826 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700827
828 if (!ports_to_prune.empty()) {
829 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
830 << " low-priority TURN ports";
831 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700832 }
833 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000834}
835
Honghai Zhanga74363c2016-07-28 18:06:15 -0700836void BasicPortAllocatorSession::PruneAllPorts() {
837 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700838 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700839 }
840}
841
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800843 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700844 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800846 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847
848 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700849 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700851 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000852
853 // Moving to COMPLETE state.
854 data->set_complete();
855 // Send candidate allocation complete signal if this was the last port.
856 MaybeSignalCandidatesAllocationDone();
857}
858
859void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800860 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700861 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800863 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700865 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700867 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000868
869 // SignalAddressError is currently sent from StunPort/TurnPort.
870 // But this signal itself is generic.
871 data->set_error();
872 // Send candidate allocation complete signal if this was the last port.
873 MaybeSignalCandidatesAllocationDone();
874}
875
876void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
877 ProtocolType proto) {
878 std::vector<Candidate> candidates;
879 for (std::vector<PortData>::iterator it = ports_.begin();
880 it != ports_.end(); ++it) {
881 if (it->sequence() != seq)
882 continue;
883
884 const std::vector<Candidate>& potentials = it->port()->Candidates();
885 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700886 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700888 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000889 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700890 bool candidate_protocol_enabled =
891 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
892 pvalue == proto;
893 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700894 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
895 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000896 candidates.push_back(potentials[i]);
897 }
898 }
899 }
900
901 if (!candidates.empty()) {
902 SignalCandidatesReady(this, candidates);
903 }
904}
905
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700906bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700907 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000908
909 // When binding to any address, before sending packets out, the getsockname
910 // returns all 0s, but after sending packets, it'll be the NIC used to
911 // send. All 0s is not a valid ICE candidate address and should be filtered
912 // out.
913 if (c.address().IsAnyIP()) {
914 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000915 }
916
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000917 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000918 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000919 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000920 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000921 } else if (c.type() == LOCAL_PORT_TYPE) {
922 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
923 // We allow host candidates if the filter allows server-reflexive
924 // candidates and the candidate is a public IP. Because we don't generate
925 // server-reflexive candidates if they have the same IP as the host
926 // candidate (i.e. when the host candidate is a public IP), filtering to
927 // only server-reflexive candidates won't work right when the host
928 // candidates have public IPs.
929 return true;
930 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000931
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000932 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000933 }
934 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000935}
936
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700937bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
938 const Port* port) const {
939 bool candidate_signalable = CheckCandidateFilter(c);
940
941 // When device enumeration is disabled (to prevent non-default IP addresses
942 // from leaking), we ping from some local candidates even though we don't
943 // signal them. However, if host candidates are also disabled (for example, to
944 // prevent even default IP addresses from leaking), we still don't want to
945 // ping from them, even if device enumeration is disabled. Thus, we check for
946 // both device enumeration and host candidates being disabled.
947 bool network_enumeration_disabled = c.address().IsAnyIP();
948 bool can_ping_from_candidate =
949 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
950 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
951
952 return candidate_signalable ||
953 (network_enumeration_disabled && can_ping_from_candidate &&
954 !host_candidates_disabled);
955}
956
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000957void BasicPortAllocatorSession::OnPortAllocationComplete(
958 AllocationSequence* seq) {
959 // Send candidate allocation complete signal if all ports are done.
960 MaybeSignalCandidatesAllocationDone();
961}
962
963void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700964 if (CandidatesAllocationDone()) {
965 if (pooled()) {
966 LOG(LS_INFO) << "All candidates gathered for pooled session.";
967 } else {
968 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
969 << component() << ":" << generation();
970 }
971 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000972 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973}
974
975void BasicPortAllocatorSession::OnPortDestroyed(
976 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800977 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000978 for (std::vector<PortData>::iterator iter = ports_.begin();
979 iter != ports_.end(); ++iter) {
980 if (port == iter->port()) {
981 ports_.erase(iter);
982 LOG_J(LS_INFO, port) << "Removed port from allocator ("
983 << static_cast<int>(ports_.size()) << " remaining)";
984 return;
985 }
986 }
nissec80e7412017-01-11 05:56:46 -0800987 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988}
989
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000990BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
991 Port* port) {
992 for (std::vector<PortData>::iterator it = ports_.begin();
993 it != ports_.end(); ++it) {
994 if (it->port() == port) {
995 return &*it;
996 }
997 }
998 return NULL;
999}
1000
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001001std::vector<BasicPortAllocatorSession::PortData*>
1002BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001003 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001004 std::vector<PortData*> unpruned_ports;
1005 for (PortData& port : ports_) {
1006 if (!port.pruned() &&
1007 std::find(networks.begin(), networks.end(),
1008 port.sequence()->network()) != networks.end()) {
1009 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001010 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001011 }
1012 return unpruned_ports;
1013}
1014
1015void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1016 const std::vector<PortData*>& port_data_list) {
1017 std::vector<PortInterface*> pruned_ports;
1018 std::vector<Candidate> removed_candidates;
1019 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001020 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001021 data->Prune();
1022 pruned_ports.push_back(data->port());
1023 if (data->has_pairable_candidate()) {
1024 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001025 // Mark the port as having no pairable candidates so that its candidates
1026 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001027 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001028 }
1029 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001030 if (!pruned_ports.empty()) {
1031 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001032 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001033 if (!removed_candidates.empty()) {
1034 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1035 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001036 }
1037}
1038
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039// AllocationSequence
1040
1041AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1042 rtc::Network* network,
1043 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001044 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045 : session_(session),
1046 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001048 config_(config),
1049 state_(kInit),
1050 flags_(flags),
1051 udp_socket_(),
1052 udp_port_(NULL),
1053 phase_(0) {
1054}
1055
Honghai Zhang5048f572016-08-23 15:47:33 -07001056void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001057 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1058 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1059 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1060 session_->allocator()->max_port()));
1061 if (udp_socket_) {
1062 udp_socket_->SignalReadPacket.connect(
1063 this, &AllocationSequence::OnReadPacket);
1064 }
1065 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1066 // are next available options to setup a communication channel.
1067 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001068}
1069
1070void AllocationSequence::Clear() {
1071 udp_port_ = NULL;
1072 turn_ports_.clear();
1073}
1074
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001075void AllocationSequence::OnNetworkFailed() {
1076 RTC_DCHECK(!network_failed_);
1077 network_failed_ = true;
1078 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001079 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001080}
1081
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001082AllocationSequence::~AllocationSequence() {
1083 session_->network_thread()->Clear(this);
1084}
1085
1086void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001087 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001088 if (network_failed_) {
1089 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001090 // it won't be equivalent to the new network.
1091 return;
1092 }
1093
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001094 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001095 // Different network setup; nothing is equivalent.
1096 return;
1097 }
1098
1099 // Else turn off the stuff that we've already got covered.
1100
1101 // Every config implicitly specifies local, so turn that off right away.
1102 *flags |= PORTALLOCATOR_DISABLE_UDP;
1103 *flags |= PORTALLOCATOR_DISABLE_TCP;
1104
1105 if (config_ && config) {
1106 if (config_->StunServers() == config->StunServers()) {
1107 // Already got this STUN servers covered.
1108 *flags |= PORTALLOCATOR_DISABLE_STUN;
1109 }
1110 if (!config_->relays.empty()) {
1111 // Already got relays covered.
1112 // NOTE: This will even skip a _different_ set of relay servers if we
1113 // were to be given one, but that never happens in our codebase. Should
1114 // probably get rid of the list in PortConfiguration and just keep a
1115 // single relay server in each one.
1116 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1117 }
1118 }
1119}
1120
1121void AllocationSequence::Start() {
1122 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001123 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001124}
1125
1126void AllocationSequence::Stop() {
1127 // If the port is completed, don't set it to stopped.
1128 if (state_ == kRunning) {
1129 state_ = kStopped;
1130 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1131 }
1132}
1133
1134void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001135 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1136 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001137
1138 const char* const PHASE_NAMES[kNumPhases] = {
1139 "Udp", "Relay", "Tcp", "SslTcp"
1140 };
1141
1142 // Perform all of the phases in the current step.
1143 LOG_J(LS_INFO, network_) << "Allocation Phase="
1144 << PHASE_NAMES[phase_];
1145
1146 switch (phase_) {
1147 case PHASE_UDP:
1148 CreateUDPPorts();
1149 CreateStunPorts();
1150 EnableProtocol(PROTO_UDP);
1151 break;
1152
1153 case PHASE_RELAY:
1154 CreateRelayPorts();
1155 break;
1156
1157 case PHASE_TCP:
1158 CreateTCPPorts();
1159 EnableProtocol(PROTO_TCP);
1160 break;
1161
1162 case PHASE_SSLTCP:
1163 state_ = kCompleted;
1164 EnableProtocol(PROTO_SSLTCP);
1165 break;
1166
1167 default:
nissec80e7412017-01-11 05:56:46 -08001168 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001169 }
1170
1171 if (state() == kRunning) {
1172 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001173 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1174 session_->allocator()->step_delay(),
1175 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001176 } else {
1177 // If all phases in AllocationSequence are completed, no allocation
1178 // steps needed further. Canceling pending signal.
1179 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1180 SignalPortAllocationComplete(this);
1181 }
1182}
1183
1184void AllocationSequence::EnableProtocol(ProtocolType proto) {
1185 if (!ProtocolEnabled(proto)) {
1186 protocols_.push_back(proto);
1187 session_->OnProtocolEnabled(this, proto);
1188 }
1189}
1190
1191bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1192 for (ProtocolList::const_iterator it = protocols_.begin();
1193 it != protocols_.end(); ++it) {
1194 if (*it == proto)
1195 return true;
1196 }
1197 return false;
1198}
1199
1200void AllocationSequence::CreateUDPPorts() {
1201 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1202 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1203 return;
1204 }
1205
1206 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1207 // is enabled completely.
1208 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001209 bool emit_local_candidate_for_anyaddress =
1210 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001211 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001212 port = UDPPort::Create(
1213 session_->network_thread(), session_->socket_factory(), network_,
1214 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001215 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001216 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001217 port = UDPPort::Create(
1218 session_->network_thread(), session_->socket_factory(), network_, ip_,
1219 session_->allocator()->min_port(), session_->allocator()->max_port(),
1220 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001221 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001222 }
1223
1224 if (port) {
1225 // If shared socket is enabled, STUN candidate will be allocated by the
1226 // UDPPort.
1227 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1228 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001229 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001230
1231 // If STUN is not disabled, setting stun server address to port.
1232 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233 if (config_ && !config_->StunServers().empty()) {
1234 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1235 << "STUN candidate generation.";
1236 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237 }
1238 }
1239 }
1240
1241 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001242 }
1243}
1244
1245void AllocationSequence::CreateTCPPorts() {
1246 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1247 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1248 return;
1249 }
1250
1251 Port* port = TCPPort::Create(session_->network_thread(),
1252 session_->socket_factory(),
1253 network_, ip_,
1254 session_->allocator()->min_port(),
1255 session_->allocator()->max_port(),
1256 session_->username(), session_->password(),
1257 session_->allocator()->allow_tcp_listen());
1258 if (port) {
1259 session_->AddAllocatedPort(port, this, true);
1260 // Since TCPPort is not created using shared socket, |port| will not be
1261 // added to the dequeue.
1262 }
1263}
1264
1265void AllocationSequence::CreateStunPorts() {
1266 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1267 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1268 return;
1269 }
1270
1271 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1272 return;
1273 }
1274
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001275 if (!(config_ && !config_->StunServers().empty())) {
1276 LOG(LS_WARNING)
1277 << "AllocationSequence: No STUN server configured, skipping.";
1278 return;
1279 }
1280
1281 StunPort* port = StunPort::Create(session_->network_thread(),
1282 session_->socket_factory(),
1283 network_, ip_,
1284 session_->allocator()->min_port(),
1285 session_->allocator()->max_port(),
1286 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001287 config_->StunServers(),
1288 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001289 if (port) {
1290 session_->AddAllocatedPort(port, this, true);
1291 // Since StunPort is not created using shared socket, |port| will not be
1292 // added to the dequeue.
1293 }
1294}
1295
1296void AllocationSequence::CreateRelayPorts() {
1297 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1298 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1299 return;
1300 }
1301
1302 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1303 // ought to have a relay list for them here.
nisseede5da42017-01-12 05:15:36 -08001304 RTC_DCHECK(config_ && !config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001305 if (!(config_ && !config_->relays.empty())) {
1306 LOG(LS_WARNING)
1307 << "AllocationSequence: No relay server configured, skipping.";
1308 return;
1309 }
1310
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001311 for (RelayServerConfig& relay : config_->relays) {
1312 if (relay.type == RELAY_GTURN) {
1313 CreateGturnPort(relay);
1314 } else if (relay.type == RELAY_TURN) {
1315 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316 } else {
nissec80e7412017-01-11 05:56:46 -08001317 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001318 }
1319 }
1320}
1321
1322void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1323 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1324 RelayPort* port = RelayPort::Create(session_->network_thread(),
1325 session_->socket_factory(),
1326 network_, ip_,
1327 session_->allocator()->min_port(),
1328 session_->allocator()->max_port(),
1329 config_->username, config_->password);
1330 if (port) {
1331 // Since RelayPort is not created using shared socket, |port| will not be
1332 // added to the dequeue.
1333 // Note: We must add the allocated port before we add addresses because
1334 // the latter will create candidates that need name and preference
1335 // settings. However, we also can't prepare the address (normally
1336 // done by AddAllocatedPort) until we have these addresses. So we
1337 // wait to do that until below.
1338 session_->AddAllocatedPort(port, this, false);
1339
1340 // Add the addresses of this protocol.
1341 PortList::const_iterator relay_port;
1342 for (relay_port = config.ports.begin();
1343 relay_port != config.ports.end();
1344 ++relay_port) {
1345 port->AddServerAddress(*relay_port);
1346 port->AddExternalAddress(*relay_port);
1347 }
1348 // Start fetching an address for this port.
1349 port->PrepareAddress();
1350 }
1351}
1352
1353void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1354 PortList::const_iterator relay_port;
1355 for (relay_port = config.ports.begin();
1356 relay_port != config.ports.end(); ++relay_port) {
1357 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001358
1359 // Skip UDP connections to relay servers if it's disallowed.
1360 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1361 relay_port->proto == PROTO_UDP) {
1362 continue;
1363 }
1364
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001365 // Do not create a port if the server address family is known and does
1366 // not match the local IP address family.
1367 int server_ip_family = relay_port->address.ipaddr().family();
1368 int local_ip_family = ip_.family();
1369 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1370 LOG(LS_INFO) << "Server and local address families are not compatible. "
1371 << "Server address: "
1372 << relay_port->address.ipaddr().ToString()
1373 << " Local address: " << ip_.ToString();
1374 continue;
1375 }
1376
1377
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001378 // Shared socket mode must be enabled only for UDP based ports. Hence
1379 // don't pass shared socket for ports which will create TCP sockets.
1380 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1381 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1382 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001383 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001384 port = TurnPort::Create(session_->network_thread(),
1385 session_->socket_factory(),
1386 network_, udp_socket_.get(),
1387 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001388 *relay_port, config.credentials, config.priority,
1389 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001390 turn_ports_.push_back(port);
1391 // Listen to the port destroyed signal, to allow AllocationSequence to
1392 // remove entrt from it's map.
1393 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1394 } else {
1395 port = TurnPort::Create(session_->network_thread(),
1396 session_->socket_factory(),
1397 network_, ip_,
1398 session_->allocator()->min_port(),
1399 session_->allocator()->max_port(),
1400 session_->username(),
1401 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001402 *relay_port, config.credentials, config.priority,
1403 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001404 }
nisseede5da42017-01-12 05:15:36 -08001405 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001406 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001407 session_->AddAllocatedPort(port, this, true);
1408 }
1409}
1410
1411void AllocationSequence::OnReadPacket(
1412 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1413 const rtc::SocketAddress& remote_addr,
1414 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001415 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001416
1417 bool turn_port_found = false;
1418
1419 // Try to find the TurnPort that matches the remote address. Note that the
1420 // message could be a STUN binding response if the TURN server is also used as
1421 // a STUN server. We don't want to parse every message here to check if it is
1422 // a STUN binding response, so we pass the message to TurnPort regardless of
1423 // the message type. The TurnPort will just ignore the message since it will
1424 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001425 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001427 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1428 packet_time)) {
1429 return;
1430 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001431 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001432 }
1433 }
1434
1435 if (udp_port_) {
1436 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1437
1438 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1439 // the TURN server is also a STUN server.
1440 if (!turn_port_found ||
1441 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001442 RTC_DCHECK(udp_port_->SharedSocket());
1443 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1444 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001445 }
1446 }
1447}
1448
1449void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1450 if (udp_port_ == port) {
1451 udp_port_ = NULL;
1452 return;
1453 }
1454
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001455 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1456 if (it != turn_ports_.end()) {
1457 turn_ports_.erase(it);
1458 } else {
1459 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001460 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001461 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001462}
1463
1464// PortConfiguration
1465PortConfiguration::PortConfiguration(
1466 const rtc::SocketAddress& stun_address,
1467 const std::string& username,
1468 const std::string& password)
1469 : stun_address(stun_address), username(username), password(password) {
1470 if (!stun_address.IsNil())
1471 stun_servers.insert(stun_address);
1472}
1473
1474PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1475 const std::string& username,
1476 const std::string& password)
1477 : stun_servers(stun_servers),
1478 username(username),
1479 password(password) {
1480 if (!stun_servers.empty())
1481 stun_address = *(stun_servers.begin());
1482}
1483
1484ServerAddresses PortConfiguration::StunServers() {
1485 if (!stun_address.IsNil() &&
1486 stun_servers.find(stun_address) == stun_servers.end()) {
1487 stun_servers.insert(stun_address);
1488 }
deadbeefc5d0d952015-07-16 10:22:21 -07001489 // Every UDP TURN server should also be used as a STUN server.
1490 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1491 for (const rtc::SocketAddress& turn_server : turn_servers) {
1492 if (stun_servers.find(turn_server) == stun_servers.end()) {
1493 stun_servers.insert(turn_server);
1494 }
1495 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001496 return stun_servers;
1497}
1498
1499void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1500 relays.push_back(config);
1501}
1502
1503bool PortConfiguration::SupportsProtocol(
1504 const RelayServerConfig& relay, ProtocolType type) const {
1505 PortList::const_iterator relay_port;
1506 for (relay_port = relay.ports.begin();
1507 relay_port != relay.ports.end();
1508 ++relay_port) {
1509 if (relay_port->proto == type)
1510 return true;
1511 }
1512 return false;
1513}
1514
1515bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1516 ProtocolType type) const {
1517 for (size_t i = 0; i < relays.size(); ++i) {
1518 if (relays[i].type == turn_type &&
1519 SupportsProtocol(relays[i], type))
1520 return true;
1521 }
1522 return false;
1523}
1524
1525ServerAddresses PortConfiguration::GetRelayServerAddresses(
1526 RelayType turn_type, ProtocolType type) const {
1527 ServerAddresses servers;
1528 for (size_t i = 0; i < relays.size(); ++i) {
1529 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1530 servers.insert(relays[i].ports.front().address);
1531 }
1532 }
1533 return servers;
1534}
1535
1536} // namespace cricket