blob: d76ff565a654e9e8acdc68e8594997e32cb99b0c [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() {
172}
173
deadbeefc5d0d952015-07-16 10:22:21 -0700174PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000175 const std::string& content_name, int component,
176 const std::string& ice_ufrag, const std::string& ice_pwd) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700177 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700179 session->SignalIceRegathering.connect(this,
180 &BasicPortAllocator::OnIceRegathering);
181 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000182}
183
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700184void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
185 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
186 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700187 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
188 prune_turn_ports());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700189}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000190
191// BasicPortAllocatorSession
192BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700193 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194 const std::string& content_name,
195 int component,
196 const std::string& ice_ufrag,
197 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700198 : PortAllocatorSession(content_name,
199 component,
200 ice_ufrag,
201 ice_pwd,
202 allocator->flags()),
203 allocator_(allocator),
204 network_thread_(NULL),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205 socket_factory_(allocator->socket_factory()),
206 allocation_started_(false),
207 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700208 allocation_sequences_created_(false),
209 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000210 allocator_->network_manager()->SignalNetworksChanged.connect(
211 this, &BasicPortAllocatorSession::OnNetworksChanged);
212 allocator_->network_manager()->StartUpdating();
213}
214
215BasicPortAllocatorSession::~BasicPortAllocatorSession() {
216 allocator_->network_manager()->StopUpdating();
217 if (network_thread_ != NULL)
218 network_thread_->Clear(this);
219
Peter Boström0c4e06b2015-10-07 12:23:21 +0200220 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000221 // AllocationSequence should clear it's map entry for turn ports before
222 // ports are destroyed.
223 sequences_[i]->Clear();
224 }
225
226 std::vector<PortData>::iterator it;
227 for (it = ports_.begin(); it != ports_.end(); it++)
228 delete it->port();
229
Peter Boström0c4e06b2015-10-07 12:23:21 +0200230 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000231 delete configs_[i];
232
Peter Boström0c4e06b2015-10-07 12:23:21 +0200233 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000234 delete sequences_[i];
235}
236
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700237void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
238 if (filter == candidate_filter_) {
239 return;
240 }
241 // We assume the filter will only change from "ALL" to something else.
242 RTC_DCHECK(candidate_filter_ == CF_ALL);
243 candidate_filter_ = filter;
244 for (PortData& port : ports_) {
245 if (!port.has_pairable_candidate()) {
246 continue;
247 }
248 const auto& candidates = port.port()->Candidates();
249 // Setting a filter may cause a ready port to become non-ready
250 // if it no longer has any pairable candidates.
251 if (!std::any_of(candidates.begin(), candidates.end(),
252 [this, &port](const Candidate& candidate) {
253 return CandidatePairable(candidate, port.port());
254 })) {
255 port.set_has_pairable_candidate(false);
256 }
257 }
258}
259
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000260void BasicPortAllocatorSession::StartGettingPorts() {
261 network_thread_ = rtc::Thread::Current();
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700262 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000263 if (!socket_factory_) {
264 owned_socket_factory_.reset(
265 new rtc::BasicPacketSocketFactory(network_thread_));
266 socket_factory_ = owned_socket_factory_.get();
267 }
268
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700269 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700270
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700271 LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700272 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000273}
274
275void BasicPortAllocatorSession::StopGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800276 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700277 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700278 // Note: this must be called after ClearGettingPorts because both may set the
279 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700280 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700281}
282
283void BasicPortAllocatorSession::ClearGettingPorts() {
nisseede5da42017-01-12 05:15:36 -0800284 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000285 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700286 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700288 }
deadbeefb60a8192016-08-24 15:15:00 -0700289 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700290 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700291}
292
293std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
294 std::vector<rtc::Network*> networks = GetNetworks();
295
296 // A network interface may have both IPv4 and IPv6 networks. Only if
297 // neither of the networks has any connections, the network interface
298 // is considered failed and need to be regathered on.
299 std::set<std::string> networks_with_connection;
300 for (const PortData& data : ports_) {
301 Port* port = data.port();
302 if (!port->connections().empty()) {
303 networks_with_connection.insert(port->Network()->name());
304 }
305 }
306
307 networks.erase(
308 std::remove_if(networks.begin(), networks.end(),
309 [networks_with_connection](rtc::Network* network) {
310 // If a network does not have any connection, it is
311 // considered failed.
312 return networks_with_connection.find(network->name()) !=
313 networks_with_connection.end();
314 }),
315 networks.end());
316 return networks;
317}
318
319void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
320 // Find the list of networks that have no connection.
321 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
322 if (failed_networks.empty()) {
323 return;
324 }
325
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700326 LOG(LS_INFO) << "Regather candidates on failed networks";
327
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700328 // Mark a sequence as "network failed" if its network is in the list of failed
329 // networks, so that it won't be considered as equivalent when the session
330 // regathers ports and candidates.
331 for (AllocationSequence* sequence : sequences_) {
332 if (!sequence->network_failed() &&
333 std::find(failed_networks.begin(), failed_networks.end(),
334 sequence->network()) != failed_networks.end()) {
335 sequence->set_network_failed();
336 }
337 }
338 // Remove ports from being used locally and send signaling to remove
339 // the candidates on the remote side.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700340 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
341 if (!ports_to_prune.empty()) {
342 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
343 << " ports because their networks failed";
344 PrunePortsAndRemoveCandidates(ports_to_prune);
345 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700346
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700347 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
348 SignalIceRegathering(this, IceRegatheringReason::NETWORK_FAILURE);
349
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700350 DoAllocate();
351 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352}
353
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700354std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
355 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700356 for (const PortData& data : ports_) {
357 if (data.ready()) {
358 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700359 }
360 }
361 return ret;
362}
363
364std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
365 std::vector<Candidate> candidates;
366 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700367 if (!data.ready()) {
368 continue;
369 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700370 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700371 }
372 return candidates;
373}
374
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700375void BasicPortAllocatorSession::GetCandidatesFromPort(
376 const PortData& data,
377 std::vector<Candidate>* candidates) const {
378 RTC_CHECK(candidates != nullptr);
379 for (const Candidate& candidate : data.port()->Candidates()) {
380 if (!CheckCandidateFilter(candidate)) {
381 continue;
382 }
383 ProtocolType pvalue;
384 if (!StringToProto(candidate.protocol().c_str(), &pvalue) ||
385 !data.sequence()->ProtocolEnabled(pvalue)) {
386 continue;
387 }
388 candidates->push_back(SanitizeRelatedAddress(candidate));
389 }
390}
391
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700392Candidate BasicPortAllocatorSession::SanitizeRelatedAddress(
393 const Candidate& c) const {
394 Candidate copy = c;
395 // If adapter enumeration is disabled or host candidates are disabled,
396 // clear the raddr of STUN candidates to avoid local address leakage.
397 bool filter_stun_related_address =
398 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
399 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
400 !(candidate_filter_ & CF_HOST);
401 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
402 // to avoid reflexive address leakage.
403 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
404 if ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
405 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address)) {
406 copy.set_related_address(
407 rtc::EmptySocketAddressWithFamily(copy.address().family()));
408 }
409 return copy;
410}
411
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700412bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
413 // Done only if all required AllocationSequence objects
414 // are created.
415 if (!allocation_sequences_created_) {
416 return false;
417 }
418
419 // Check that all port allocation sequences are complete (not running).
420 if (std::any_of(sequences_.begin(), sequences_.end(),
421 [](const AllocationSequence* sequence) {
422 return sequence->state() == AllocationSequence::kRunning;
423 })) {
424 return false;
425 }
426
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700427 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700428 // expected candidates. Session will trigger candidates allocation complete
429 // signal.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700430 return std::none_of(ports_.begin(), ports_.end(),
431 [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700432}
433
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000434void BasicPortAllocatorSession::OnMessage(rtc::Message *message) {
435 switch (message->message_id) {
436 case MSG_CONFIG_START:
nisseede5da42017-01-12 05:15:36 -0800437 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000438 GetPortConfigurations();
439 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 case MSG_CONFIG_READY:
nisseede5da42017-01-12 05:15:36 -0800441 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
443 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 case MSG_ALLOCATE:
nisseede5da42017-01-12 05:15:36 -0800445 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446 OnAllocate();
447 break;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000448 case MSG_SEQUENCEOBJECTS_CREATED:
nisseede5da42017-01-12 05:15:36 -0800449 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 OnAllocationSequenceObjectsCreated();
451 break;
452 case MSG_CONFIG_STOP:
nisseede5da42017-01-12 05:15:36 -0800453 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000454 OnConfigStop();
455 break;
456 default:
nissec80e7412017-01-11 05:56:46 -0800457 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 }
459}
460
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700461void BasicPortAllocatorSession::UpdateIceParametersInternal() {
462 for (PortData& port : ports_) {
463 port.port()->set_content_name(content_name());
464 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
465 }
466}
467
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000468void BasicPortAllocatorSession::GetPortConfigurations() {
469 PortConfiguration* config = new PortConfiguration(allocator_->stun_servers(),
470 username(),
471 password());
472
deadbeef653b8e02015-11-11 12:55:10 -0800473 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
474 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475 }
476 ConfigReady(config);
477}
478
479void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700480 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000481}
482
483// Adds a configuration to the list.
484void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
deadbeef653b8e02015-11-11 12:55:10 -0800485 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000486 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800487 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488
489 AllocatePorts();
490}
491
492void BasicPortAllocatorSession::OnConfigStop() {
nisseede5da42017-01-12 05:15:36 -0800493 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494
495 // If any of the allocated ports have not completed the candidates allocation,
496 // mark those as error. Since session doesn't need any new candidates
497 // at this stage of the allocation, it's safe to discard any new candidates.
498 bool send_signal = false;
499 for (std::vector<PortData>::iterator it = ports_.begin();
500 it != ports_.end(); ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700501 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000502 // Updating port state to error, which didn't finish allocating candidates
503 // yet.
504 it->set_error();
505 send_signal = true;
506 }
507 }
508
509 // Did we stop any running sequences?
510 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
511 it != sequences_.end() && !send_signal; ++it) {
512 if ((*it)->state() == AllocationSequence::kStopped) {
513 send_signal = true;
514 }
515 }
516
517 // If we stopped anything that was running, send a done signal now.
518 if (send_signal) {
519 MaybeSignalCandidatesAllocationDone();
520 }
521}
522
523void BasicPortAllocatorSession::AllocatePorts() {
nisseede5da42017-01-12 05:15:36 -0800524 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700525 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000526}
527
528void BasicPortAllocatorSession::OnAllocate() {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700529 if (network_manager_started_ && !IsStopped())
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 DoAllocate();
531
532 allocation_started_ = true;
533}
534
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700535std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
536 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700537 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800538 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700539 // If the network permission state is BLOCKED, we just act as if the flag has
540 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700541 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700542 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700543 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
544 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000545 // If the adapter enumeration is disabled, we'll just bind to any address
546 // instead of specific NIC. This is to ensure the same routing for http
547 // traffic by OS is also used here to avoid any local or public IP leakage
548 // during stun process.
549 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700550 network_manager->GetAnyAddressNetworks(&networks);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000551 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700552 network_manager->GetNetworks(&networks);
deadbeefe97389c2016-12-23 01:43:45 -0800553 // If network enumeration fails, use the ANY address as a fallback, so we
554 // can at least try gathering candidates using the default route chosen by
555 // the OS.
556 if (networks.empty()) {
557 network_manager->GetAnyAddressNetworks(&networks);
558 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000559 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700560 networks.erase(std::remove_if(networks.begin(), networks.end(),
561 [this](rtc::Network* network) {
562 return allocator_->network_ignore_mask() &
563 network->type();
564 }),
565 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700566
567 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
568 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700569 for (rtc::Network* network : networks) {
honghaiz60347052016-05-31 18:29:12 -0700570 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
571 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700572 networks.erase(std::remove_if(networks.begin(), networks.end(),
573 [lowest_cost](rtc::Network* network) {
574 return network->GetCost() >
575 lowest_cost + rtc::kNetworkCostLow;
576 }),
577 networks.end());
honghaiz60347052016-05-31 18:29:12 -0700578 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700579 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700580}
581
582// For each network, see if we have a sequence that covers it already. If not,
583// create a new sequence to create the appropriate ports.
584void BasicPortAllocatorSession::DoAllocate() {
585 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700586 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 if (networks.empty()) {
588 LOG(LS_WARNING) << "Machine has no networks; no ports will be allocated";
589 done_signal_needed = true;
590 } else {
Honghai Zhang5048f572016-08-23 15:47:33 -0700591 LOG(LS_INFO) << "Allocate ports on "<< networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700592 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200593 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200594 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000595 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
596 // If all the ports are disabled we should just fire the allocation
597 // done event and return.
598 done_signal_needed = true;
599 break;
600 }
601
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602 if (!config || config->relays.empty()) {
603 // No relay ports specified in this config.
604 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
605 }
606
607 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609 // Skip IPv6 networks unless the flag's been set.
610 continue;
611 }
612
zhihuangb09b3f92017-03-07 14:40:51 -0800613 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
614 networks[i]->GetBestIP().family() == AF_INET6 &&
615 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
616 // Skip IPv6 Wi-Fi networks unless the flag's been set.
617 continue;
618 }
619
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000620 // Disable phases that would only create ports equivalent to
621 // ones that we have already made.
622 DisableEquivalentPhases(networks[i], config, &sequence_flags);
623
624 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
625 // New AllocationSequence would have nothing to do, so don't make it.
626 continue;
627 }
628
629 AllocationSequence* sequence =
630 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 sequence->SignalPortAllocationComplete.connect(
632 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700633 sequence->Init();
634 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700636 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000637 }
638 }
639 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700640 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 }
642}
643
644void BasicPortAllocatorSession::OnNetworksChanged() {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700645 std::vector<rtc::Network*> networks = GetNetworks();
646 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700647 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700648 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700649 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700650 if (!sequence->network_failed() &&
honghaiz8c404fa2015-09-28 07:59:43 -0700651 std::find(networks.begin(), networks.end(), sequence->network()) ==
652 networks.end()) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700653 sequence->OnNetworkFailed();
654 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700655 }
656 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700657 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
658 if (!ports_to_prune.empty()) {
659 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
660 << " ports because their networks were gone";
661 PrunePortsAndRemoveCandidates(ports_to_prune);
662 }
honghaiz8c404fa2015-09-28 07:59:43 -0700663
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700664 if (allocation_started_ && !IsStopped()) {
665 if (network_manager_started_) {
666 // If the network manager has started, it must be regathering.
667 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
668 }
669 DoAllocate();
670 }
671
Honghai Zhang5048f572016-08-23 15:47:33 -0700672 if (!network_manager_started_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700673 LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700674 network_manager_started_ = true;
675 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000676}
677
678void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200679 rtc::Network* network,
680 PortConfiguration* config,
681 uint32_t* flags) {
682 for (uint32_t i = 0; i < sequences_.size() &&
683 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
684 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 sequences_[i]->DisableEquivalentPhases(network, config, flags);
686 }
687}
688
689void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
690 AllocationSequence * seq,
691 bool prepare_address) {
692 if (!port)
693 return;
694
695 LOG(LS_INFO) << "Adding allocated port for " << content_name();
696 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700697 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000698 port->set_generation(generation());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700699 port->set_send_retransmit_count_attribute(
700 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000701
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702 PortData data(port, seq);
703 ports_.push_back(data);
704
705 port->SignalCandidateReady.connect(
706 this, &BasicPortAllocatorSession::OnCandidateReady);
707 port->SignalPortComplete.connect(this,
708 &BasicPortAllocatorSession::OnPortComplete);
709 port->SignalDestroyed.connect(this,
710 &BasicPortAllocatorSession::OnPortDestroyed);
711 port->SignalPortError.connect(
712 this, &BasicPortAllocatorSession::OnPortError);
713 LOG_J(LS_INFO, port) << "Added port to allocator";
714
715 if (prepare_address)
716 port->PrepareAddress();
717}
718
719void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
720 allocation_sequences_created_ = true;
721 // Send candidate allocation complete signal if we have no sequences.
722 MaybeSignalCandidatesAllocationDone();
723}
724
725void BasicPortAllocatorSession::OnCandidateReady(
726 Port* port, const Candidate& c) {
nisseede5da42017-01-12 05:15:36 -0800727 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000728 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800729 RTC_DCHECK(data != NULL);
deadbeefa64edb82016-07-15 14:42:21 -0700730 LOG_J(LS_INFO, port) << "Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700732 // already done with gathering.
733 if (!data->inprogress()) {
deadbeefa64edb82016-07-15 14:42:21 -0700734 LOG(LS_WARNING)
735 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700736 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700737 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700738
danilchapf4e8cf02016-06-30 01:55:03 -0700739 // Mark that the port has a pairable candidate, either because we have a
740 // usable candidate from the port, or simply because the port is bound to the
741 // any address and therefore has no host candidate. This will trigger the port
742 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700743 // checks. If port has already been marked as having a pairable candidate,
744 // do nothing here.
745 // Note: We should check whether any candidates may become ready after this
746 // because there we will check whether the candidate is generated by the ready
747 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700748 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700749 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700750 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700751
752 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700753 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700754 }
755 // If the current port is not pruned yet, SignalPortReady.
756 if (!data->pruned()) {
deadbeefa64edb82016-07-15 14:42:21 -0700757 LOG_J(LS_INFO, port) << "Port ready.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700758 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700759 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700760 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700761 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700762
763 ProtocolType pvalue;
764 bool candidate_protocol_enabled =
765 StringToProto(c.protocol().c_str(), &pvalue) &&
766 data->sequence()->ProtocolEnabled(pvalue);
767
768 if (data->ready() && CheckCandidateFilter(c) && candidate_protocol_enabled) {
769 std::vector<Candidate> candidates;
770 candidates.push_back(SanitizeRelatedAddress(c));
771 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700772 } else if (!candidate_protocol_enabled) {
773 LOG(LS_INFO)
774 << "Not yet signaling candidate because protocol is not yet enabled.";
775 } else {
776 LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700777 }
778
779 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700780 if (pruned) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700781 MaybeSignalCandidatesAllocationDone();
782 }
783}
784
785Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
786 const std::string& network_name) const {
787 Port* best_turn_port = nullptr;
788 for (const PortData& data : ports_) {
789 if (data.port()->Network()->name() == network_name &&
790 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
791 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
792 best_turn_port = data.port();
793 }
794 }
795 return best_turn_port;
796}
797
798bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700799 // Note: We determine the same network based only on their network names. So
800 // if an IPv4 address and an IPv6 address have the same network name, they
801 // are considered the same network here.
802 const std::string& network_name = newly_pairable_turn_port->Network()->name();
803 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
804 // |port| is already in the list of ports, so the best port cannot be nullptr.
805 RTC_CHECK(best_turn_port != nullptr);
806
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700807 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700808 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700809 for (PortData& data : ports_) {
810 if (data.port()->Network()->name() == network_name &&
811 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
812 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700813 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700814 if (data.port() != newly_pairable_turn_port) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700815 // These ports will be pruned in PrunePortsAndRemoveCandidates.
816 ports_to_prune.push_back(&data);
817 } else {
818 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700819 }
820 }
821 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700822
823 if (!ports_to_prune.empty()) {
824 LOG(LS_INFO) << "Prune " << ports_to_prune.size()
825 << " low-priority TURN ports";
826 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700827 }
828 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000829}
830
Honghai Zhanga74363c2016-07-28 18:06:15 -0700831void BasicPortAllocatorSession::PruneAllPorts() {
832 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700833 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -0700834 }
835}
836
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000837void BasicPortAllocatorSession::OnPortComplete(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800838 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700839 LOG_J(LS_INFO, port) << "Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000840 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800841 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000842
843 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700844 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000845 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700846 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000847
848 // Moving to COMPLETE state.
849 data->set_complete();
850 // Send candidate allocation complete signal if this was the last port.
851 MaybeSignalCandidatesAllocationDone();
852}
853
854void BasicPortAllocatorSession::OnPortError(Port* port) {
nisseede5da42017-01-12 05:15:36 -0800855 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
deadbeefa64edb82016-07-15 14:42:21 -0700856 LOG_J(LS_INFO, port) << "Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000857 PortData* data = FindPort(port);
nisseede5da42017-01-12 05:15:36 -0800858 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000859 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700860 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000861 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700862 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000863
864 // SignalAddressError is currently sent from StunPort/TurnPort.
865 // But this signal itself is generic.
866 data->set_error();
867 // Send candidate allocation complete signal if this was the last port.
868 MaybeSignalCandidatesAllocationDone();
869}
870
871void BasicPortAllocatorSession::OnProtocolEnabled(AllocationSequence* seq,
872 ProtocolType proto) {
873 std::vector<Candidate> candidates;
874 for (std::vector<PortData>::iterator it = ports_.begin();
875 it != ports_.end(); ++it) {
876 if (it->sequence() != seq)
877 continue;
878
879 const std::vector<Candidate>& potentials = it->port()->Candidates();
880 for (size_t i = 0; i < potentials.size(); ++i) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700881 if (!CheckCandidateFilter(potentials[i])) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000882 continue;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700883 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 ProtocolType pvalue;
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700885 bool candidate_protocol_enabled =
886 StringToProto(potentials[i].protocol().c_str(), &pvalue) &&
887 pvalue == proto;
888 if (candidate_protocol_enabled) {
deadbeefa64edb82016-07-15 14:42:21 -0700889 LOG(LS_INFO) << "Signaling candidate because protocol was enabled: "
890 << potentials[i].ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 candidates.push_back(potentials[i]);
892 }
893 }
894 }
895
896 if (!candidates.empty()) {
897 SignalCandidatesReady(this, candidates);
898 }
899}
900
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700901bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700902 uint32_t filter = candidate_filter_;
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000903
904 // When binding to any address, before sending packets out, the getsockname
905 // returns all 0s, but after sending packets, it'll be the NIC used to
906 // send. All 0s is not a valid ICE candidate address and should be filtered
907 // out.
908 if (c.address().IsAnyIP()) {
909 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910 }
911
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000912 if (c.type() == RELAY_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000913 return ((filter & CF_RELAY) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000914 } else if (c.type() == STUN_PORT_TYPE) {
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000915 return ((filter & CF_REFLEXIVE) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000916 } else if (c.type() == LOCAL_PORT_TYPE) {
917 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
918 // We allow host candidates if the filter allows server-reflexive
919 // candidates and the candidate is a public IP. Because we don't generate
920 // server-reflexive candidates if they have the same IP as the host
921 // candidate (i.e. when the host candidate is a public IP), filtering to
922 // only server-reflexive candidates won't work right when the host
923 // candidates have public IPs.
924 return true;
925 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000926
guoweis@webrtc.org931e0cf2015-02-18 19:09:42 +0000927 return ((filter & CF_HOST) != 0);
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000928 }
929 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000930}
931
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700932bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
933 const Port* port) const {
934 bool candidate_signalable = CheckCandidateFilter(c);
935
936 // When device enumeration is disabled (to prevent non-default IP addresses
937 // from leaking), we ping from some local candidates even though we don't
938 // signal them. However, if host candidates are also disabled (for example, to
939 // prevent even default IP addresses from leaking), we still don't want to
940 // ping from them, even if device enumeration is disabled. Thus, we check for
941 // both device enumeration and host candidates being disabled.
942 bool network_enumeration_disabled = c.address().IsAnyIP();
943 bool can_ping_from_candidate =
944 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
945 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
946
947 return candidate_signalable ||
948 (network_enumeration_disabled && can_ping_from_candidate &&
949 !host_candidates_disabled);
950}
951
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000952void BasicPortAllocatorSession::OnPortAllocationComplete(
953 AllocationSequence* seq) {
954 // Send candidate allocation complete signal if all ports are done.
955 MaybeSignalCandidatesAllocationDone();
956}
957
958void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700959 if (CandidatesAllocationDone()) {
960 if (pooled()) {
961 LOG(LS_INFO) << "All candidates gathered for pooled session.";
962 } else {
963 LOG(LS_INFO) << "All candidates gathered for " << content_name() << ":"
964 << component() << ":" << generation();
965 }
966 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000967 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000968}
969
970void BasicPortAllocatorSession::OnPortDestroyed(
971 PortInterface* port) {
nisseede5da42017-01-12 05:15:36 -0800972 RTC_DCHECK(rtc::Thread::Current() == network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000973 for (std::vector<PortData>::iterator iter = ports_.begin();
974 iter != ports_.end(); ++iter) {
975 if (port == iter->port()) {
976 ports_.erase(iter);
977 LOG_J(LS_INFO, port) << "Removed port from allocator ("
978 << static_cast<int>(ports_.size()) << " remaining)";
979 return;
980 }
981 }
nissec80e7412017-01-11 05:56:46 -0800982 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000983}
984
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000985BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
986 Port* port) {
987 for (std::vector<PortData>::iterator it = ports_.begin();
988 it != ports_.end(); ++it) {
989 if (it->port() == port) {
990 return &*it;
991 }
992 }
993 return NULL;
994}
995
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700996std::vector<BasicPortAllocatorSession::PortData*>
997BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700998 const std::vector<rtc::Network*>& networks) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700999 std::vector<PortData*> unpruned_ports;
1000 for (PortData& port : ports_) {
1001 if (!port.pruned() &&
1002 std::find(networks.begin(), networks.end(),
1003 port.sequence()->network()) != networks.end()) {
1004 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001005 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001006 }
1007 return unpruned_ports;
1008}
1009
1010void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
1011 const std::vector<PortData*>& port_data_list) {
1012 std::vector<PortInterface*> pruned_ports;
1013 std::vector<Candidate> removed_candidates;
1014 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001015 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001016 data->Prune();
1017 pruned_ports.push_back(data->port());
1018 if (data->has_pairable_candidate()) {
1019 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001020 // Mark the port as having no pairable candidates so that its candidates
1021 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001022 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001023 }
1024 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001025 if (!pruned_ports.empty()) {
1026 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001027 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001028 if (!removed_candidates.empty()) {
1029 LOG(LS_INFO) << "Removed " << removed_candidates.size() << " candidates";
1030 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001031 }
1032}
1033
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001034// AllocationSequence
1035
1036AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1037 rtc::Network* network,
1038 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001039 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001040 : session_(session),
1041 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001042 ip_(network->GetBestIP()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001043 config_(config),
1044 state_(kInit),
1045 flags_(flags),
1046 udp_socket_(),
1047 udp_port_(NULL),
1048 phase_(0) {
1049}
1050
Honghai Zhang5048f572016-08-23 15:47:33 -07001051void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001052 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1053 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
1054 rtc::SocketAddress(ip_, 0), session_->allocator()->min_port(),
1055 session_->allocator()->max_port()));
1056 if (udp_socket_) {
1057 udp_socket_->SignalReadPacket.connect(
1058 this, &AllocationSequence::OnReadPacket);
1059 }
1060 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1061 // are next available options to setup a communication channel.
1062 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001063}
1064
1065void AllocationSequence::Clear() {
1066 udp_port_ = NULL;
1067 turn_ports_.clear();
1068}
1069
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001070void AllocationSequence::OnNetworkFailed() {
1071 RTC_DCHECK(!network_failed_);
1072 network_failed_ = true;
1073 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001074 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001075}
1076
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001077AllocationSequence::~AllocationSequence() {
1078 session_->network_thread()->Clear(this);
1079}
1080
1081void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001082 PortConfiguration* config, uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001083 if (network_failed_) {
1084 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001085 // it won't be equivalent to the new network.
1086 return;
1087 }
1088
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001089 if (!((network == network_) && (ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001090 // Different network setup; nothing is equivalent.
1091 return;
1092 }
1093
1094 // Else turn off the stuff that we've already got covered.
1095
1096 // Every config implicitly specifies local, so turn that off right away.
1097 *flags |= PORTALLOCATOR_DISABLE_UDP;
1098 *flags |= PORTALLOCATOR_DISABLE_TCP;
1099
1100 if (config_ && config) {
1101 if (config_->StunServers() == config->StunServers()) {
1102 // Already got this STUN servers covered.
1103 *flags |= PORTALLOCATOR_DISABLE_STUN;
1104 }
1105 if (!config_->relays.empty()) {
1106 // Already got relays covered.
1107 // NOTE: This will even skip a _different_ set of relay servers if we
1108 // were to be given one, but that never happens in our codebase. Should
1109 // probably get rid of the list in PortConfiguration and just keep a
1110 // single relay server in each one.
1111 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1112 }
1113 }
1114}
1115
1116void AllocationSequence::Start() {
1117 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001118 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001119}
1120
1121void AllocationSequence::Stop() {
1122 // If the port is completed, don't set it to stopped.
1123 if (state_ == kRunning) {
1124 state_ = kStopped;
1125 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1126 }
1127}
1128
1129void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001130 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1131 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001132
1133 const char* const PHASE_NAMES[kNumPhases] = {
1134 "Udp", "Relay", "Tcp", "SslTcp"
1135 };
1136
1137 // Perform all of the phases in the current step.
1138 LOG_J(LS_INFO, network_) << "Allocation Phase="
1139 << PHASE_NAMES[phase_];
1140
1141 switch (phase_) {
1142 case PHASE_UDP:
1143 CreateUDPPorts();
1144 CreateStunPorts();
1145 EnableProtocol(PROTO_UDP);
1146 break;
1147
1148 case PHASE_RELAY:
1149 CreateRelayPorts();
1150 break;
1151
1152 case PHASE_TCP:
1153 CreateTCPPorts();
1154 EnableProtocol(PROTO_TCP);
1155 break;
1156
1157 case PHASE_SSLTCP:
1158 state_ = kCompleted;
1159 EnableProtocol(PROTO_SSLTCP);
1160 break;
1161
1162 default:
nissec80e7412017-01-11 05:56:46 -08001163 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001164 }
1165
1166 if (state() == kRunning) {
1167 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001168 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1169 session_->allocator()->step_delay(),
1170 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001171 } else {
1172 // If all phases in AllocationSequence are completed, no allocation
1173 // steps needed further. Canceling pending signal.
1174 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1175 SignalPortAllocationComplete(this);
1176 }
1177}
1178
1179void AllocationSequence::EnableProtocol(ProtocolType proto) {
1180 if (!ProtocolEnabled(proto)) {
1181 protocols_.push_back(proto);
1182 session_->OnProtocolEnabled(this, proto);
1183 }
1184}
1185
1186bool AllocationSequence::ProtocolEnabled(ProtocolType proto) const {
1187 for (ProtocolList::const_iterator it = protocols_.begin();
1188 it != protocols_.end(); ++it) {
1189 if (*it == proto)
1190 return true;
1191 }
1192 return false;
1193}
1194
1195void AllocationSequence::CreateUDPPorts() {
1196 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
1197 LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
1198 return;
1199 }
1200
1201 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1202 // is enabled completely.
1203 UDPPort* port = NULL;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001204 bool emit_local_candidate_for_anyaddress =
1205 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001206 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001207 port = UDPPort::Create(
1208 session_->network_thread(), session_->socket_factory(), network_,
1209 udp_socket_.get(), session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001210 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001211 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001212 port = UDPPort::Create(
1213 session_->network_thread(), session_->socket_factory(), network_, ip_,
1214 session_->allocator()->min_port(), session_->allocator()->max_port(),
1215 session_->username(), session_->password(),
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001216 session_->allocator()->origin(), emit_local_candidate_for_anyaddress);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001217 }
1218
1219 if (port) {
1220 // If shared socket is enabled, STUN candidate will be allocated by the
1221 // UDPPort.
1222 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1223 udp_port_ = port;
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001224 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001225
1226 // If STUN is not disabled, setting stun server address to port.
1227 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001228 if (config_ && !config_->StunServers().empty()) {
1229 LOG(LS_INFO) << "AllocationSequence: UDPPort will be handling the "
1230 << "STUN candidate generation.";
1231 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001232 }
1233 }
1234 }
1235
1236 session_->AddAllocatedPort(port, this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001237 }
1238}
1239
1240void AllocationSequence::CreateTCPPorts() {
1241 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
1242 LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
1243 return;
1244 }
1245
1246 Port* port = TCPPort::Create(session_->network_thread(),
1247 session_->socket_factory(),
1248 network_, ip_,
1249 session_->allocator()->min_port(),
1250 session_->allocator()->max_port(),
1251 session_->username(), session_->password(),
1252 session_->allocator()->allow_tcp_listen());
1253 if (port) {
1254 session_->AddAllocatedPort(port, this, true);
1255 // Since TCPPort is not created using shared socket, |port| will not be
1256 // added to the dequeue.
1257 }
1258}
1259
1260void AllocationSequence::CreateStunPorts() {
1261 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
1262 LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
1263 return;
1264 }
1265
1266 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1267 return;
1268 }
1269
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001270 if (!(config_ && !config_->StunServers().empty())) {
1271 LOG(LS_WARNING)
1272 << "AllocationSequence: No STUN server configured, skipping.";
1273 return;
1274 }
1275
1276 StunPort* port = StunPort::Create(session_->network_thread(),
1277 session_->socket_factory(),
1278 network_, ip_,
1279 session_->allocator()->min_port(),
1280 session_->allocator()->max_port(),
1281 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001282 config_->StunServers(),
1283 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001284 if (port) {
1285 session_->AddAllocatedPort(port, this, true);
1286 // Since StunPort is not created using shared socket, |port| will not be
1287 // added to the dequeue.
1288 }
1289}
1290
1291void AllocationSequence::CreateRelayPorts() {
1292 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
1293 LOG(LS_VERBOSE) << "AllocationSequence: Relay ports disabled, skipping.";
1294 return;
1295 }
1296
1297 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1298 // ought to have a relay list for them here.
nisseede5da42017-01-12 05:15:36 -08001299 RTC_DCHECK(config_ && !config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001300 if (!(config_ && !config_->relays.empty())) {
1301 LOG(LS_WARNING)
1302 << "AllocationSequence: No relay server configured, skipping.";
1303 return;
1304 }
1305
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001306 for (RelayServerConfig& relay : config_->relays) {
1307 if (relay.type == RELAY_GTURN) {
1308 CreateGturnPort(relay);
1309 } else if (relay.type == RELAY_TURN) {
1310 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001311 } else {
nissec80e7412017-01-11 05:56:46 -08001312 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001313 }
1314 }
1315}
1316
1317void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1318 // TODO(mallinath) - Rename RelayPort to GTurnPort.
1319 RelayPort* port = RelayPort::Create(session_->network_thread(),
1320 session_->socket_factory(),
1321 network_, ip_,
1322 session_->allocator()->min_port(),
1323 session_->allocator()->max_port(),
1324 config_->username, config_->password);
1325 if (port) {
1326 // Since RelayPort is not created using shared socket, |port| will not be
1327 // added to the dequeue.
1328 // Note: We must add the allocated port before we add addresses because
1329 // the latter will create candidates that need name and preference
1330 // settings. However, we also can't prepare the address (normally
1331 // done by AddAllocatedPort) until we have these addresses. So we
1332 // wait to do that until below.
1333 session_->AddAllocatedPort(port, this, false);
1334
1335 // Add the addresses of this protocol.
1336 PortList::const_iterator relay_port;
1337 for (relay_port = config.ports.begin();
1338 relay_port != config.ports.end();
1339 ++relay_port) {
1340 port->AddServerAddress(*relay_port);
1341 port->AddExternalAddress(*relay_port);
1342 }
1343 // Start fetching an address for this port.
1344 port->PrepareAddress();
1345 }
1346}
1347
1348void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1349 PortList::const_iterator relay_port;
1350 for (relay_port = config.ports.begin();
1351 relay_port != config.ports.end(); ++relay_port) {
1352 TurnPort* port = NULL;
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001353
1354 // Skip UDP connections to relay servers if it's disallowed.
1355 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1356 relay_port->proto == PROTO_UDP) {
1357 continue;
1358 }
1359
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001360 // Do not create a port if the server address family is known and does
1361 // not match the local IP address family.
1362 int server_ip_family = relay_port->address.ipaddr().family();
1363 int local_ip_family = ip_.family();
1364 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
1365 LOG(LS_INFO) << "Server and local address families are not compatible. "
1366 << "Server address: "
1367 << relay_port->address.ipaddr().ToString()
1368 << " Local address: " << ip_.ToString();
1369 continue;
1370 }
1371
1372
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001373 // Shared socket mode must be enabled only for UDP based ports. Hence
1374 // don't pass shared socket for ports which will create TCP sockets.
1375 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1376 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1377 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001378 relay_port->proto == PROTO_UDP && udp_socket_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001379 port = TurnPort::Create(session_->network_thread(),
1380 session_->socket_factory(),
1381 network_, udp_socket_.get(),
1382 session_->username(), session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001383 *relay_port, config.credentials, config.priority,
1384 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385 turn_ports_.push_back(port);
1386 // Listen to the port destroyed signal, to allow AllocationSequence to
1387 // remove entrt from it's map.
1388 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1389 } else {
1390 port = TurnPort::Create(session_->network_thread(),
1391 session_->socket_factory(),
1392 network_, ip_,
1393 session_->allocator()->min_port(),
1394 session_->allocator()->max_port(),
1395 session_->username(),
1396 session_->password(),
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +00001397 *relay_port, config.credentials, config.priority,
1398 session_->allocator()->origin());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001399 }
nisseede5da42017-01-12 05:15:36 -08001400 RTC_DCHECK(port != NULL);
hnsl04833622017-01-09 08:35:45 -08001401 port->SetTlsCertPolicy(config.tls_cert_policy);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001402 session_->AddAllocatedPort(port, this, true);
1403 }
1404}
1405
1406void AllocationSequence::OnReadPacket(
1407 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
1408 const rtc::SocketAddress& remote_addr,
1409 const rtc::PacketTime& packet_time) {
nisseede5da42017-01-12 05:15:36 -08001410 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001411
1412 bool turn_port_found = false;
1413
1414 // Try to find the TurnPort that matches the remote address. Note that the
1415 // message could be a STUN binding response if the TURN server is also used as
1416 // a STUN server. We don't want to parse every message here to check if it is
1417 // a STUN binding response, so we pass the message to TurnPort regardless of
1418 // the message type. The TurnPort will just ignore the message since it will
1419 // not find any request by transaction ID.
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001420 for (TurnPort* port : turn_ports_) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001421 if (port->server_address().address == remote_addr) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001422 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
1423 packet_time)) {
1424 return;
1425 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001426 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001427 }
1428 }
1429
1430 if (udp_port_) {
1431 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1432
1433 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1434 // the TURN server is also a STUN server.
1435 if (!turn_port_found ||
1436 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001437 RTC_DCHECK(udp_port_->SharedSocket());
1438 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
1439 packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001440 }
1441 }
1442}
1443
1444void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1445 if (udp_port_ == port) {
1446 udp_port_ = NULL;
1447 return;
1448 }
1449
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001450 auto it = std::find(turn_ports_.begin(), turn_ports_.end(), port);
1451 if (it != turn_ports_.end()) {
1452 turn_ports_.erase(it);
1453 } else {
1454 LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001455 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001456 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001457}
1458
1459// PortConfiguration
1460PortConfiguration::PortConfiguration(
1461 const rtc::SocketAddress& stun_address,
1462 const std::string& username,
1463 const std::string& password)
1464 : stun_address(stun_address), username(username), password(password) {
1465 if (!stun_address.IsNil())
1466 stun_servers.insert(stun_address);
1467}
1468
1469PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1470 const std::string& username,
1471 const std::string& password)
1472 : stun_servers(stun_servers),
1473 username(username),
1474 password(password) {
1475 if (!stun_servers.empty())
1476 stun_address = *(stun_servers.begin());
1477}
1478
1479ServerAddresses PortConfiguration::StunServers() {
1480 if (!stun_address.IsNil() &&
1481 stun_servers.find(stun_address) == stun_servers.end()) {
1482 stun_servers.insert(stun_address);
1483 }
deadbeefc5d0d952015-07-16 10:22:21 -07001484 // Every UDP TURN server should also be used as a STUN server.
1485 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1486 for (const rtc::SocketAddress& turn_server : turn_servers) {
1487 if (stun_servers.find(turn_server) == stun_servers.end()) {
1488 stun_servers.insert(turn_server);
1489 }
1490 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001491 return stun_servers;
1492}
1493
1494void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1495 relays.push_back(config);
1496}
1497
1498bool PortConfiguration::SupportsProtocol(
1499 const RelayServerConfig& relay, ProtocolType type) const {
1500 PortList::const_iterator relay_port;
1501 for (relay_port = relay.ports.begin();
1502 relay_port != relay.ports.end();
1503 ++relay_port) {
1504 if (relay_port->proto == type)
1505 return true;
1506 }
1507 return false;
1508}
1509
1510bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1511 ProtocolType type) const {
1512 for (size_t i = 0; i < relays.size(); ++i) {
1513 if (relays[i].type == turn_type &&
1514 SupportsProtocol(relays[i], type))
1515 return true;
1516 }
1517 return false;
1518}
1519
1520ServerAddresses PortConfiguration::GetRelayServerAddresses(
1521 RelayType turn_type, ProtocolType type) const {
1522 ServerAddresses servers;
1523 for (size_t i = 0; i < relays.size(); ++i) {
1524 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1525 servers.insert(relays[i].ports.front().address);
1526 }
1527 }
1528 return servers;
1529}
1530
1531} // namespace cricket