blob: aebe0f24ee6e2834ce73a6a3de23ad862450bd8e [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());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700702 port->set_send_retransmit_count_attribute(
703 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 PortData data(port, seq);
706 ports_.push_back(data);
707
708 port->SignalCandidateReady.connect(
709 this, &BasicPortAllocatorSession::OnCandidateReady);
710 port->SignalPortComplete.connect(this,
711 &BasicPortAllocatorSession::OnPortComplete);
712 port->SignalDestroyed.connect(this,
713 &BasicPortAllocatorSession::OnPortDestroyed);
714 port->SignalPortError.connect(
715 this, &BasicPortAllocatorSession::OnPortError);
716 LOG_J(LS_INFO, port) << "Added port to allocator";
717
718 if (prepare_address)
719 port->PrepareAddress();
720}
721
722void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
723 allocation_sequences_created_ = true;
724 // Send candidate allocation complete signal if we have no sequences.
725 MaybeSignalCandidatesAllocationDone();
726}
727
728void BasicPortAllocatorSession::OnCandidateReady(
729 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800730 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800732 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700733 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700735 // already done with gathering.
736 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700737 LOG(LS_WARNING)
738 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700739 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700740 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700741
danilchapf4e8cf02016-06-30 01:55:03 -0700742 // Mark that the port has a pairable candidate, either because we have a
743 // usable candidate from the port, or simply because the port is bound to the
744 // any address and therefore has no host candidate. This will trigger the port
745 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700746 // checks. If port has already been marked as having a pairable candidate,
747 // do nothing here.
748 // Note: We should check whether any candidates may become ready after this
749 // because there we will check whether the candidate is generated by the ready
750 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700751 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700752 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700753 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700754
755 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700756 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700757 }
758 // If the current port is not pruned yet, SignalPortReady.
759 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700760 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700761 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700762 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700763 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700764 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700765
766 ProtocolType pvalue;
767 bool candidate_protocol_enabled =
768 StringToProto(c.protocol().c_str(), &pvalue) &&
769 data->sequence()->ProtocolEnabled(pvalue);
770
771 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
772 std::vector<Candidate> candidates;
773 candidates.push_back(SanitizeRelatedAddress(c));
774 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700775 } else if (!candidate_protocol_enabled) {
776 LOG(LS_INFO)
777 << "Not yet signaling candidate because protocol is not yet enabled.";
778 } else {
779 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700780 }
781
782 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700783 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700784 MaybeSignalCandidatesAllocationDone();
785 }
786}
787
788Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
789 const std::string& network_name) const {
790 Port* best_turn_port = nullptr;
791 for (const PortData& data : ports_) {
792 if (data.port()->Network()->name() == network_name &&
793 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
794 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
795 best_turn_port = data.port();
796 }
797 }
798 return best_turn_port;
799}
800
801bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700802 // Note: We determine the same network based only on their network names. So
803 // if an IPv4 address and an IPv6 address have the same network name, they
804 // are considered the same network here.
805 const std::string& network_name = newly_pairable_turn_port->Network()->name();
806 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
807 // |port| is already in the list of ports, so the best port cannot be nullptr.
808 RTC_CHECK(best_turn_port != nullptr);
809
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700810 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700811 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700812 for (PortData& data : ports_) {
813 if (data.port()->Network()->name() == network_name &&
814 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
815 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700816 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700817 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700818 // These ports will be pruned in PrunePortsAndRemoveCandidates.
819 ports_to_prune.push_back(&data);
820 } else {
821 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700822 }
823 }
824 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700825
826 if (!ports_to_prune.empty()) {
827 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
828 << " low-priority TURN ports";
829 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700830 }
831 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000832}
833
Honghai Zhanga74363c2016-07-28 18:06:15 -0700834void BasicPortAllocatorSession::PruneAllPorts() {
835 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700836 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700837 }
838}
839
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800841 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700842 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000843 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800844 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845
846 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700847 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000848 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700849 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000850
851 // Moving to COMPLETE state.
852 data->set_complete();
853 // Send candidate allocation complete signal if this was the last port.
854 MaybeSignalCandidatesAllocationDone();
855}
856
857void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800858 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700859 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000860 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800861 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000862 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700863 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700865 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000866
867 // SignalAddressError is currently sent from StunPort/TurnPort.
868 // But this signal itself is generic.
869 data->set_error();
870 // Send candidate allocation complete signal if this was the last port.
871 MaybeSignalCandidatesAllocationDone();
872}
873
874void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
875 ProtocolType proto) {
876 std::vector<Candidate> candidates;
877 for (std::vector<PortData>::iterator it = ports_.begin();
878 it != ports_.end(); ++it) {
879 if (it->sequence() != seq)
880 continue;
881
882 const std::vector<Candidate>& potentials = it->port()->Candidates();
883 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700884 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000885 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700886 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000887 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700888 bool candidate_protocol_enabled =
889 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
890 pvalue == proto;
891 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700892 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
893 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000894 candidates.push_back(potentials[i]);
895 }
896 }
897 }
898
899 if (!candidates.empty()) {
900 SignalCandidatesReady(this, candidates);
901 }
902}
903
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700904bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700905 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000906
907 // When binding to any address, before sending packets out, the getsockname
908 // returns all 0s, but after sending packets, it'll be the NIC used to
909 // send. All 0s is not a valid ICE candidate address and should be filtered
910 // out.
911 if (c.address().IsAnyIP()) {
912 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000913 }
914
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000915 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000916 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000917 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000918 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000919 } else if (c.type() == LOCAL_PORT_TYPE) {
920 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
921 // We allow host candidates if the filter allows server-reflexive
922 // candidates and the candidate is a public IP. Because we don't generate
923 // server-reflexive candidates if they have the same IP as the host
924 // candidate (i.e. when the host candidate is a public IP), filtering to
925 // only server-reflexive candidates won't work right when the host
926 // candidates have public IPs.
927 return true;
928 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000929
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000930 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000931 }
932 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000933}
934
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700935bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
936 const Port* port) const {
937 bool candidate_signalable = CheckCandidateFilter(c);
938
939 // When device enumeration is disabled (to prevent non-default IP addresses
940 // from leaking), we ping from some local candidates even though we don't
941 // signal them. However, if host candidates are also disabled (for example, to
942 // prevent even default IP addresses from leaking), we still don't want to
943 // ping from them, even if device enumeration is disabled. Thus, we check for
944 // both device enumeration and host candidates being disabled.
945 bool network_enumeration_disabled = c.address().IsAnyIP();
946 bool can_ping_from_candidate =
947 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
948 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
949
950 return candidate_signalable ||
951 (network_enumeration_disabled && can_ping_from_candidate &&
952 !host_candidates_disabled);
953}
954
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000955void BasicPortAllocatorSession::OnPortAllocationComplete(
956 AllocationSequence* seq) {
957 // Send candidate allocation complete signal if all ports are done.
958 MaybeSignalCandidatesAllocationDone();
959}
960
961void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700962 if (CandidatesAllocationDone()) {
963 if (pooled()) {
964 LOG(LS_INFO) << "All candidates gathered for pooled session.";
965 } else {
966 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
967 << component() << ":" << generation();
968 }
969 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000970 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000971}
972
973void BasicPortAllocatorSession::OnPortDestroyed(
974 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800975 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000976 for (std::vector<PortData>::iterator iter = ports_.begin();
977 iter != ports_.end(); ++iter) {
978 if (port == iter->port()) {
979 ports_.erase(iter);
980 LOG_J(LS_INFO, port) << "Removed port from allocator ("
981 << static_cast<int>(ports_.size()) << " remaining)";
982 return;
983 }
984 }
nissec80e7412017-01-11 05:56:46 -0800985 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000986}
987
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000988BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
989 Port* port) {
990 for (std::vector<PortData>::iterator it = ports_.begin();
991 it != ports_.end(); ++it) {
992 if (it->port() == port) {
993 return &*it;
994 }
995 }
996 return NULL;
997}
998
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700999std::vector<BasicPortAllocatorSession::PortData*>
1000BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001001 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001002 std::vector<PortData*> unpruned_ports;
1003 for (PortData& port : ports_) {
1004 if (!port.pruned() &&
1005 std::find(networks.begin(), networks.end(),
1006 port.sequence()->network()) != networks.end()) {
1007 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001008 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001009 }
1010 return unpruned_ports;
1011}
1012
1013void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1014 const std::vector<PortData*>& port_data_list) {
1015 std::vector<PortInterface*> pruned_ports;
1016 std::vector<Candidate> removed_candidates;
1017 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001018 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001019 data->Prune();
1020 pruned_ports.push_back(data->port());
1021 if (data->has_pairable_candidate()) {
1022 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001023 // Mark the port as having no pairable candidates so that its candidates
1024 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001025 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001026 }
1027 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001028 if (!pruned_ports.empty()) {
1029 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001030 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001031 if (!removed_candidates.empty()) {
1032 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1033 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001034 }
1035}
1036
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001037// AllocationSequence
1038
1039AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1040 rtc::Network* network,
1041 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001042 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001043 : session_(session),
1044 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001045 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001046 config_(config),
1047 state_(kInit),
1048 flags_(flags),
1049 udp_socket_(),
1050 udp_port_(NULL),
1051 phase_(0) {
1052}
1053
Honghai Zhang5048f572016-08-23 15:47:33 -07001054void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001055 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1056 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1057 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1058 session_->allocator()->max_port()));
1059 if (udp_socket_) {
1060 udp_socket_->SignalReadPacket.connect(
1061 this, &AllocationSequence::OnReadPacket);
1062 }
1063 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1064 // are next available options to setup a communication channel.
1065 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001066}
1067
1068void AllocationSequence::Clear() {
1069 udp_port_ = NULL;
1070 turn_ports_.clear();
1071}
1072
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001073void AllocationSequence::OnNetworkFailed() {
1074 RTC_DCHECK(!network_failed_);
1075 network_failed_ = true;
1076 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001077 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001078}
1079
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001080AllocationSequence::~AllocationSequence() {
1081 session_->network_thread()->Clear(this);
1082}
1083
1084void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001085 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001086 if (network_failed_) {
1087 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001088 // it won't be equivalent to the new network.
1089 return;
1090 }
1091
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001092 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001093 // Different network setup; nothing is equivalent.
1094 return;
1095 }
1096
1097 // Else turn off the stuff that we've already got covered.
1098
1099 // Every config implicitly specifies local, so turn that off right away.
1100 *flags |= PORTALLOCATOR_DISABLE_UDP;
1101 *flags |= PORTALLOCATOR_DISABLE_TCP;
1102
1103 if (config_ && config) {
1104 if (config_->StunServers() == config->StunServers()) {
1105 // Already got this STUN servers covered.
1106 *flags |= PORTALLOCATOR_DISABLE_STUN;
1107 }
1108 if (!config_->relays.empty()) {
1109 // Already got relays covered.
1110 // NOTE: This will even skip a _different_ set of relay servers if we
1111 // were to be given one, but that never happens in our codebase. Should
1112 // probably get rid of the list in PortConfiguration and just keep a
1113 // single relay server in each one.
1114 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1115 }
1116 }
1117}
1118
1119void AllocationSequence::Start() {
1120 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001121 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001122}
1123
1124void AllocationSequence::Stop() {
1125 // If the port is completed, don't set it to stopped.
1126 if (state_ == kRunning) {
1127 state_ = kStopped;
1128 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1129 }
1130}
1131
1132void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001133 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1134 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001135
1136 const char* const PHASE_NAMES[kNumPhases] = {
1137 "Udp", "Relay", "Tcp", "SslTcp"
1138 };
1139
1140 // Perform all of the phases in the current step.
1141 LOG_J(LS_INFO, network_) << "Allocation Phase="
1142 << PHASE_NAMES[phase_];
1143
1144 switch (phase_) {
1145 case PHASE_UDP:
1146 CreateUDPPorts();
1147 CreateStunPorts();
1148 EnableProtocol(PROTO_UDP);
1149 break;
1150
1151 case PHASE_RELAY:
1152 CreateRelayPorts();
1153 break;
1154
1155 case PHASE_TCP:
1156 CreateTCPPorts();
1157 EnableProtocol(PROTO_TCP);
1158 break;
1159
1160 case PHASE_SSLTCP:
1161 state_ = kCompleted;
1162 EnableProtocol(PROTO_SSLTCP);
1163 break;
1164
1165 default:
nissec80e7412017-01-11 05:56:46 -08001166 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001167 }
1168
1169 if (state() == kRunning) {
1170 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001171 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1172 session_->allocator()->step_delay(),
1173 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001174 } else {
1175 // If all phases in AllocationSequence are completed, no allocation
1176 // steps needed further. Canceling pending signal.
1177 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1178 SignalPortAllocationComplete(this);
1179 }
1180}
1181
1182void AllocationSequence::EnableProtocol(ProtocolType proto) {
1183 if (!ProtocolEnabled(proto)) {
1184 protocols_.push_back(proto);
1185 session_->OnProtocolEnabled(this, proto);
1186 }
1187}
1188
1189bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1190 for (ProtocolList::const_iterator it = protocols_.begin();
1191 it != protocols_.end(); ++it) {
1192 if (*it == proto)
1193 return true;
1194 }
1195 return false;
1196}
1197
1198void AllocationSequence::CreateUDPPorts() {
1199 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1200 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1201 return;
1202 }
1203
1204 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1205 // is enabled completely.
1206 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001207 bool emit_local_candidate_for_anyaddress =
1208 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001209 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001210 port = UDPPort::Create(
1211 session_->network_thread(), session_->socket_factory(), network_,
1212 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001213 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001214 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001215 port = UDPPort::Create(
1216 session_->network_thread(), session_->socket_factory(), network_, ip_,
1217 session_->allocator()->min_port(), session_->allocator()->max_port(),
1218 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001219 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001220 }
1221
1222 if (port) {
1223 // If shared socket is enabled, STUN candidate will be allocated by the
1224 // UDPPort.
1225 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1226 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001227 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228
1229 // If STUN is not disabled, setting stun server address to port.
1230 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001231 if (config_ && !config_->StunServers().empty()) {
1232 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1233 << "STUN candidate generation.";
1234 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001235 }
1236 }
1237 }
1238
1239 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001240 }
1241}
1242
1243void AllocationSequence::CreateTCPPorts() {
1244 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1245 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1246 return;
1247 }
1248
1249 Port* port = TCPPort::Create(session_->network_thread(),
1250 session_->socket_factory(),
1251 network_, ip_,
1252 session_->allocator()->min_port(),
1253 session_->allocator()->max_port(),
1254 session_->username(), session_->password(),
1255 session_->allocator()->allow_tcp_listen());
1256 if (port) {
1257 session_->AddAllocatedPort(port, this, true);
1258 // Since TCPPort is not created using shared socket, |port| will not be
1259 // added to the dequeue.
1260 }
1261}
1262
1263void AllocationSequence::CreateStunPorts() {
1264 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1265 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1266 return;
1267 }
1268
1269 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1270 return;
1271 }
1272
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001273 if (!(config_ && !config_->StunServers().empty())) {
1274 LOG(LS_WARNING)
1275 << "AllocationSequence: No STUN server configured, skipping.";
1276 return;
1277 }
1278
1279 StunPort* port = StunPort::Create(session_->network_thread(),
1280 session_->socket_factory(),
1281 network_, ip_,
1282 session_->allocator()->min_port(),
1283 session_->allocator()->max_port(),
1284 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001285 config_->StunServers(),
1286 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001287 if (port) {
1288 session_->AddAllocatedPort(port, this, true);
1289 // Since StunPort is not created using shared socket, |port| will not be
1290 // added to the dequeue.
1291 }
1292}
1293
1294void AllocationSequence::CreateRelayPorts() {
1295 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1296 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1297 return;
1298 }
1299
1300 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1301 // ought to have a relay list for them here.
nisseede5da42017-01-12 05:15:36 -08001302 RTC_DCHECK(config_ && !config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001303 if (!(config_ && !config_->relays.empty())) {
1304 LOG(LS_WARNING)
1305 << "AllocationSequence: No relay server configured, skipping.";
1306 return;
1307 }
1308
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001309 for (RelayServerConfig& relay : config_->relays) {
1310 if (relay.type == RELAY_GTURN) {
1311 CreateGturnPort(relay);
1312 } else if (relay.type == RELAY_TURN) {
1313 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314 } else {
nissec80e7412017-01-11 05:56:46 -08001315 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316 }
1317 }
1318}
1319
1320void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1321 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1322 RelayPort* port = RelayPort::Create(session_->network_thread(),
1323 session_->socket_factory(),
1324 network_, ip_,
1325 session_->allocator()->min_port(),
1326 session_->allocator()->max_port(),
1327 config_->username, config_->password);
1328 if (port) {
1329 // Since RelayPort is not created using shared socket, |port| will not be
1330 // added to the dequeue.
1331 // Note: We must add the allocated port before we add addresses because
1332 // the latter will create candidates that need name and preference
1333 // settings. However, we also can't prepare the address (normally
1334 // done by AddAllocatedPort) until we have these addresses. So we
1335 // wait to do that until below.
1336 session_->AddAllocatedPort(port, this, false);
1337
1338 // Add the addresses of this protocol.
1339 PortList::const_iterator relay_port;
1340 for (relay_port = config.ports.begin();
1341 relay_port != config.ports.end();
1342 ++relay_port) {
1343 port->AddServerAddress(*relay_port);
1344 port->AddExternalAddress(*relay_port);
1345 }
1346 // Start fetching an address for this port.
1347 port->PrepareAddress();
1348 }
1349}
1350
1351void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1352 PortList::const_iterator relay_port;
1353 for (relay_port = config.ports.begin();
1354 relay_port != config.ports.end(); ++relay_port) {
1355 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001356
1357 // Skip UDP connections to relay servers if it's disallowed.
1358 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1359 relay_port->proto == PROTO_UDP) {
1360 continue;
1361 }
1362
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001363 // Do not create a port if the server address family is known and does
1364 // not match the local IP address family.
1365 int server_ip_family = relay_port->address.ipaddr().family();
1366 int local_ip_family = ip_.family();
1367 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1368 LOG(LS_INFO) << "Server and local address families are not compatible. "
1369 << "Server address: "
1370 << relay_port->address.ipaddr().ToString()
1371 << " Local address: " << ip_.ToString();
1372 continue;
1373 }
1374
1375
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001376 // Shared socket mode must be enabled only for UDP based ports. Hence
1377 // don't pass shared socket for ports which will create TCP sockets.
1378 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1379 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1380 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001381 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001382 port = TurnPort::Create(session_->network_thread(),
1383 session_->socket_factory(),
1384 network_, udp_socket_.get(),
1385 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001386 *relay_port, config.credentials, config.priority,
1387 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 turn_ports_.push_back(port);
1389 // Listen to the port destroyed signal, to allow AllocationSequence to
1390 // remove entrt from it's map.
1391 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1392 } else {
1393 port = TurnPort::Create(session_->network_thread(),
1394 session_->socket_factory(),
1395 network_, ip_,
1396 session_->allocator()->min_port(),
1397 session_->allocator()->max_port(),
1398 session_->username(),
1399 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001400 *relay_port, config.credentials, config.priority,
1401 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001402 }
nisseede5da42017-01-12 05:15:36 -08001403 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001404 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001405 session_->AddAllocatedPort(port, this, true);
1406 }
1407}
1408
1409void AllocationSequence::OnReadPacket(
1410 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1411 const rtc::SocketAddress& remote_addr,
1412 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001413 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001414
1415 bool turn_port_found = false;
1416
1417 // Try to find the TurnPort that matches the remote address. Note that the
1418 // message could be a STUN binding response if the TURN server is also used as
1419 // a STUN server. We don't want to parse every message here to check if it is
1420 // a STUN binding response, so we pass the message to TurnPort regardless of
1421 // the message type. The TurnPort will just ignore the message since it will
1422 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001423 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001424 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001425 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1426 packet_time)) {
1427 return;
1428 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001430 }
1431 }
1432
1433 if (udp_port_) {
1434 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1435
1436 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1437 // the TURN server is also a STUN server.
1438 if (!turn_port_found ||
1439 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001440 RTC_DCHECK(udp_port_->SharedSocket());
1441 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1442 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001443 }
1444 }
1445}
1446
1447void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1448 if (udp_port_ == port) {
1449 udp_port_ = NULL;
1450 return;
1451 }
1452
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001453 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1454 if (it != turn_ports_.end()) {
1455 turn_ports_.erase(it);
1456 } else {
1457 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001458 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001459 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001460}
1461
1462// PortConfiguration
1463PortConfiguration::PortConfiguration(
1464 const rtc::SocketAddress& stun_address,
1465 const std::string& username,
1466 const std::string& password)
1467 : stun_address(stun_address), username(username), password(password) {
1468 if (!stun_address.IsNil())
1469 stun_servers.insert(stun_address);
1470}
1471
1472PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1473 const std::string& username,
1474 const std::string& password)
1475 : stun_servers(stun_servers),
1476 username(username),
1477 password(password) {
1478 if (!stun_servers.empty())
1479 stun_address = *(stun_servers.begin());
1480}
1481
1482ServerAddresses PortConfiguration::StunServers() {
1483 if (!stun_address.IsNil() &&
1484 stun_servers.find(stun_address) == stun_servers.end()) {
1485 stun_servers.insert(stun_address);
1486 }
deadbeefc5d0d952015-07-16 10:22:21 -07001487 // Every UDP TURN server should also be used as a STUN server.
1488 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1489 for (const rtc::SocketAddress& turn_server : turn_servers) {
1490 if (stun_servers.find(turn_server) == stun_servers.end()) {
1491 stun_servers.insert(turn_server);
1492 }
1493 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001494 return stun_servers;
1495}
1496
1497void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1498 relays.push_back(config);
1499}
1500
1501bool PortConfiguration::SupportsProtocol(
1502 const RelayServerConfig& relay, ProtocolType type) const {
1503 PortList::const_iterator relay_port;
1504 for (relay_port = relay.ports.begin();
1505 relay_port != relay.ports.end();
1506 ++relay_port) {
1507 if (relay_port->proto == type)
1508 return true;
1509 }
1510 return false;
1511}
1512
1513bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1514 ProtocolType type) const {
1515 for (size_t i = 0; i < relays.size(); ++i) {
1516 if (relays[i].type == turn_type &&
1517 SupportsProtocol(relays[i], type))
1518 return true;
1519 }
1520 return false;
1521}
1522
1523ServerAddresses PortConfiguration::GetRelayServerAddresses(
1524 RelayType turn_type, ProtocolType type) const {
1525 ServerAddresses servers;
1526 for (size_t i = 0; i < relays.size(); ++i) {
1527 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1528 servers.insert(relays[i].ports.front().address);
1529 }
1530 }
1531 return servers;
1532}
1533
1534} // namespace cricket