blob: 83c8bf2b958b746bca15c30a818ab267a5bc9d46 [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "p2p/client/basic_port_allocator.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000012
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080013#include <algorithm>
Qingsi Wang10a0e512018-05-16 13:37:03 -070014#include <functional>
Steve Anton6c38cc72017-11-29 10:25:58 -080015#include <set>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <string>
17#include <vector>
18
Steve Antonae226f62019-01-29 12:47:38 -080019#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080020#include "p2p/base/basic_packet_socket_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "p2p/base/port.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "p2p/base/relay_port.h"
23#include "p2p/base/stun_port.h"
24#include "p2p/base/tcp_port.h"
25#include "p2p/base/turn_port.h"
26#include "p2p/base/udp_port.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/checks.h"
28#include "rtc_base/helpers.h"
29#include "rtc_base/logging.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070030#include "system_wrappers/include/metrics.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031
32using rtc::CreateRandomId;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000033
34namespace {
35
36enum {
37 MSG_CONFIG_START,
38 MSG_CONFIG_READY,
39 MSG_ALLOCATE,
40 MSG_ALLOCATION_PHASE,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000041 MSG_SEQUENCEOBJECTS_CREATED,
42 MSG_CONFIG_STOP,
43};
44
45const int PHASE_UDP = 0;
46const int PHASE_RELAY = 1;
47const int PHASE_TCP = 2;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000048
deadbeef1c5e6d02017-09-15 17:46:56 -070049const int kNumPhases = 3;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050
zhihuang696f8ca2017-06-27 15:11:24 -070051// Gets protocol priority: UDP > TCP > SSLTCP == TLS.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070052int GetProtocolPriority(cricket::ProtocolType protocol) {
53 switch (protocol) {
54 case cricket::PROTO_UDP:
55 return 2;
56 case cricket::PROTO_TCP:
57 return 1;
58 case cricket::PROTO_SSLTCP:
zhihuang696f8ca2017-06-27 15:11:24 -070059 case cricket::PROTO_TLS:
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070060 return 0;
61 default:
nisseeb4ca4e2017-01-12 02:24:27 -080062 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070063 return 0;
64 }
65}
66// Gets address family priority: IPv6 > IPv4 > Unspecified.
67int GetAddressFamilyPriority(int ip_family) {
68 switch (ip_family) {
69 case AF_INET6:
70 return 2;
71 case AF_INET:
72 return 1;
73 default:
nisseeb4ca4e2017-01-12 02:24:27 -080074 RTC_NOTREACHED();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -070075 return 0;
76 }
77}
78
79// Returns positive if a is better, negative if b is better, and 0 otherwise.
80int ComparePort(const cricket::Port* a, const cricket::Port* b) {
81 int a_protocol = GetProtocolPriority(a->GetProtocol());
82 int b_protocol = GetProtocolPriority(b->GetProtocol());
83 int cmp_protocol = a_protocol - b_protocol;
84 if (cmp_protocol != 0) {
85 return cmp_protocol;
86 }
87
88 int a_family = GetAddressFamilyPriority(a->Network()->GetBestIP().family());
89 int b_family = GetAddressFamilyPriority(b->Network()->GetBestIP().family());
90 return a_family - b_family;
91}
92
Qingsi Wang10a0e512018-05-16 13:37:03 -070093struct NetworkFilter {
94 using Predicate = std::function<bool(rtc::Network*)>;
95 NetworkFilter(Predicate pred, const std::string& description)
96 : pred(pred), description(description) {}
97 Predicate pred;
98 const std::string description;
99};
100
101using NetworkList = rtc::NetworkManager::NetworkList;
102void FilterNetworks(NetworkList* networks, NetworkFilter filter) {
103 auto start_to_remove =
104 std::remove_if(networks->begin(), networks->end(), filter.pred);
105 if (start_to_remove == networks->end()) {
106 return;
107 }
108 RTC_LOG(INFO) << "Filtered out " << filter.description << " networks:";
109 for (auto it = start_to_remove; it != networks->end(); ++it) {
110 RTC_LOG(INFO) << (*it)->ToString();
111 }
112 networks->erase(start_to_remove, networks->end());
113}
114
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115} // namespace
116
Qingsi Wang797ede82019-04-17 21:21:54 +0000117namespace cricket {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200118const uint32_t DISABLE_ALL_PHASES =
honghaizf421bdc2015-07-17 16:21:55 -0700119 PORTALLOCATOR_DISABLE_UDP | PORTALLOCATOR_DISABLE_TCP |
120 PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_RELAY;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000121
122// BasicPortAllocator
Jonas Orelandbdcee282017-10-10 14:01:40 +0200123BasicPortAllocator::BasicPortAllocator(
124 rtc::NetworkManager* network_manager,
125 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +0100126 webrtc::TurnCustomizer* customizer,
127 RelayPortFactoryInterface* relay_port_factory)
maxmorine9ef9072017-08-29 04:49:00 -0700128 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100129 InitRelayPortFactory(relay_port_factory);
130 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800131 RTC_DCHECK(network_manager_ != nullptr);
132 RTC_DCHECK(socket_factory_ != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +0200133 SetConfiguration(ServerAddresses(), std::vector<RelayServerConfig>(), 0,
134 false, customizer);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000135 Construct();
136}
137
Yves Gerey665174f2018-06-19 15:03:05 +0200138BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager)
maxmorine9ef9072017-08-29 04:49:00 -0700139 : network_manager_(network_manager), socket_factory_(nullptr) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100140 InitRelayPortFactory(nullptr);
141 RTC_DCHECK(relay_port_factory_ != nullptr);
nisseede5da42017-01-12 05:15:36 -0800142 RTC_DCHECK(network_manager_ != nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000143 Construct();
144}
145
Yves Gerey665174f2018-06-19 15:03:05 +0200146BasicPortAllocator::BasicPortAllocator(rtc::NetworkManager* network_manager,
147 rtc::PacketSocketFactory* socket_factory,
148 const ServerAddresses& stun_servers)
maxmorine9ef9072017-08-29 04:49:00 -0700149 : network_manager_(network_manager), socket_factory_(socket_factory) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100150 InitRelayPortFactory(nullptr);
151 RTC_DCHECK(relay_port_factory_ != nullptr);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000152 RTC_DCHECK(socket_factory_ != NULL);
Jonas Orelandbdcee282017-10-10 14:01:40 +0200153 SetConfiguration(stun_servers, std::vector<RelayServerConfig>(), 0, false,
154 nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000155 Construct();
156}
157
158BasicPortAllocator::BasicPortAllocator(
159 rtc::NetworkManager* network_manager,
160 const ServerAddresses& stun_servers,
161 const rtc::SocketAddress& relay_address_udp,
162 const rtc::SocketAddress& relay_address_tcp,
163 const rtc::SocketAddress& relay_address_ssl)
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000164 : network_manager_(network_manager), socket_factory_(NULL) {
Jonas Oreland202994c2017-12-18 12:10:43 +0100165 InitRelayPortFactory(nullptr);
166 RTC_DCHECK(relay_port_factory_ != nullptr);
167 RTC_DCHECK(network_manager_ != nullptr);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700168 std::vector<RelayServerConfig> turn_servers;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000169 RelayServerConfig config(RELAY_GTURN);
deadbeef653b8e02015-11-11 12:55:10 -0800170 if (!relay_address_udp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000171 config.ports.push_back(ProtocolAddress(relay_address_udp, PROTO_UDP));
deadbeef653b8e02015-11-11 12:55:10 -0800172 }
173 if (!relay_address_tcp.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000174 config.ports.push_back(ProtocolAddress(relay_address_tcp, PROTO_TCP));
deadbeef653b8e02015-11-11 12:55:10 -0800175 }
176 if (!relay_address_ssl.IsNil()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000177 config.ports.push_back(ProtocolAddress(relay_address_ssl, PROTO_SSLTCP));
deadbeef653b8e02015-11-11 12:55:10 -0800178 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179
deadbeef653b8e02015-11-11 12:55:10 -0800180 if (!config.ports.empty()) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700181 turn_servers.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800182 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000183
Jonas Orelandbdcee282017-10-10 14:01:40 +0200184 SetConfiguration(stun_servers, turn_servers, 0, false, nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000185 Construct();
186}
187
188void BasicPortAllocator::Construct() {
189 allow_tcp_listen_ = true;
190}
191
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700192void BasicPortAllocator::OnIceRegathering(PortAllocatorSession* session,
193 IceRegatheringReason reason) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700194 // If the session has not been taken by an active channel, do not report the
195 // metric.
196 for (auto& allocator_session : pooled_sessions()) {
197 if (allocator_session.get() == session) {
198 return;
199 }
200 }
201
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700202 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IceRegatheringReason",
203 static_cast<int>(reason),
204 static_cast<int>(IceRegatheringReason::MAX_VALUE));
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700205}
206
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207BasicPortAllocator::~BasicPortAllocator() {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700208 CheckRunOnValidThreadIfInitialized();
deadbeef42a42632017-03-10 15:18:00 -0800209 // Our created port allocator sessions depend on us, so destroy our remaining
210 // pooled sessions before anything else.
211 DiscardCandidatePool();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212}
213
Steve Anton7995d8c2017-10-30 16:23:38 -0700214void BasicPortAllocator::SetNetworkIgnoreMask(int network_ignore_mask) {
215 // TODO(phoglund): implement support for other types than loopback.
216 // See https://code.google.com/p/webrtc/issues/detail?id=4288.
217 // Then remove set_network_ignore_list from NetworkManager.
Qingsi Wanga2d60672018-04-11 16:57:45 -0700218 CheckRunOnValidThreadIfInitialized();
Steve Anton7995d8c2017-10-30 16:23:38 -0700219 network_ignore_mask_ = network_ignore_mask;
220}
221
deadbeefc5d0d952015-07-16 10:22:21 -0700222PortAllocatorSession* BasicPortAllocator::CreateSessionInternal(
Yves Gerey665174f2018-06-19 15:03:05 +0200223 const std::string& content_name,
224 int component,
225 const std::string& ice_ufrag,
226 const std::string& ice_pwd) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700227 CheckRunOnValidThreadAndInitialized();
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700228 PortAllocatorSession* session = new BasicPortAllocatorSession(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000229 this, content_name, component, ice_ufrag, ice_pwd);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700230 session->SignalIceRegathering.connect(this,
231 &BasicPortAllocator::OnIceRegathering);
232 return session;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000233}
234
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700235void BasicPortAllocator::AddTurnServer(const RelayServerConfig& turn_server) {
Qingsi Wanga2d60672018-04-11 16:57:45 -0700236 CheckRunOnValidThreadAndInitialized();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700237 std::vector<RelayServerConfig> new_turn_servers = turn_servers();
238 new_turn_servers.push_back(turn_server);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700239 SetConfiguration(stun_servers(), new_turn_servers, candidate_pool_size(),
Jonas Orelandbdcee282017-10-10 14:01:40 +0200240 prune_turn_ports(), turn_customizer());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700241}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000242
Jonas Oreland202994c2017-12-18 12:10:43 +0100243void BasicPortAllocator::InitRelayPortFactory(
244 RelayPortFactoryInterface* relay_port_factory) {
245 if (relay_port_factory != nullptr) {
246 relay_port_factory_ = relay_port_factory;
247 } else {
248 default_relay_port_factory_.reset(new TurnPortFactory());
249 relay_port_factory_ = default_relay_port_factory_.get();
250 }
251}
252
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253// BasicPortAllocatorSession
254BasicPortAllocatorSession::BasicPortAllocatorSession(
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700255 BasicPortAllocator* allocator,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000256 const std::string& content_name,
257 int component,
258 const std::string& ice_ufrag,
259 const std::string& ice_pwd)
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700260 : PortAllocatorSession(content_name,
261 component,
262 ice_ufrag,
263 ice_pwd,
264 allocator->flags()),
265 allocator_(allocator),
Steve Anton60de6832018-10-02 14:04:12 -0700266 network_thread_(rtc::Thread::Current()),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267 socket_factory_(allocator->socket_factory()),
268 allocation_started_(false),
269 network_manager_started_(false),
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700270 allocation_sequences_created_(false),
271 prune_turn_ports_(allocator->prune_turn_ports()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000272 allocator_->network_manager()->SignalNetworksChanged.connect(
273 this, &BasicPortAllocatorSession::OnNetworksChanged);
274 allocator_->network_manager()->StartUpdating();
275}
276
277BasicPortAllocatorSession::~BasicPortAllocatorSession() {
Steve Anton60de6832018-10-02 14:04:12 -0700278 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279 allocator_->network_manager()->StopUpdating();
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000280 if (network_thread_ != NULL)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000281 network_thread_->Clear(this);
282
Peter Boström0c4e06b2015-10-07 12:23:21 +0200283 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000284 // AllocationSequence should clear it's map entry for turn ports before
285 // ports are destroyed.
286 sequences_[i]->Clear();
287 }
288
289 std::vector<PortData>::iterator it;
290 for (it = ports_.begin(); it != ports_.end(); it++)
291 delete it->port();
292
Peter Boström0c4e06b2015-10-07 12:23:21 +0200293 for (uint32_t i = 0; i < configs_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000294 delete configs_[i];
295
Peter Boström0c4e06b2015-10-07 12:23:21 +0200296 for (uint32_t i = 0; i < sequences_.size(); ++i)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297 delete sequences_[i];
298}
299
Steve Anton7995d8c2017-10-30 16:23:38 -0700300BasicPortAllocator* BasicPortAllocatorSession::allocator() {
Steve Anton60de6832018-10-02 14:04:12 -0700301 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700302 return allocator_;
303}
304
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700305void BasicPortAllocatorSession::SetCandidateFilter(uint32_t filter) {
Steve Anton60de6832018-10-02 14:04:12 -0700306 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700307 if (filter == candidate_filter_) {
308 return;
309 }
Qingsi Wang797ede82019-04-17 21:21:54 +0000310 // We assume the filter will only change from "ALL" to something else.
311 RTC_DCHECK(candidate_filter_ == CF_ALL);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700312 candidate_filter_ = filter;
Qingsi Wang797ede82019-04-17 21:21:54 +0000313 for (PortData& port : ports_) {
314 if (!port.has_pairable_candidate()) {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700315 continue;
316 }
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700317 // Setting a filter may cause a ready port to become non-ready
318 // if it no longer has any pairable candidates.
Qingsi Wang797ede82019-04-17 21:21:54 +0000319 if (absl::c_none_of(port.port()->Candidates(),
320 [this, &port](const Candidate& candidate) {
321 return CandidatePairable(candidate, port.port());
322 })) {
323 port.set_has_pairable_candidate(false);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700324 }
325 }
326}
327
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328void BasicPortAllocatorSession::StartGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700329 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700330 state_ = SessionState::GATHERING;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331 if (!socket_factory_) {
332 owned_socket_factory_.reset(
333 new rtc::BasicPacketSocketFactory(network_thread_));
334 socket_factory_ = owned_socket_factory_.get();
335 }
336
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700337 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_START);
Honghai Zhangd78ecf72016-07-01 14:40:40 -0700338
Mirko Bonadei675513b2017-11-09 11:09:25 +0100339 RTC_LOG(LS_INFO) << "Start getting ports with prune_turn_ports "
340 << (prune_turn_ports_ ? "enabled" : "disabled");
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000341}
342
343void BasicPortAllocatorSession::StopGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700344 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz98db68f2015-09-29 07:58:17 -0700345 ClearGettingPorts();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700346 // Note: this must be called after ClearGettingPorts because both may set the
347 // session state and we should set the state to STOPPED.
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700348 state_ = SessionState::STOPPED;
honghaiz98db68f2015-09-29 07:58:17 -0700349}
350
351void BasicPortAllocatorSession::ClearGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700352 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353 network_thread_->Clear(this, MSG_ALLOCATE);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700354 for (uint32_t i = 0; i < sequences_.size(); ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355 sequences_[i]->Stop();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700356 }
deadbeefb60a8192016-08-24 15:15:00 -0700357 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_STOP);
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700358 state_ = SessionState::CLEARED;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700359}
360
Steve Anton7995d8c2017-10-30 16:23:38 -0700361bool BasicPortAllocatorSession::IsGettingPorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700362 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700363 return state_ == SessionState::GATHERING;
364}
365
366bool BasicPortAllocatorSession::IsCleared() const {
Steve Anton60de6832018-10-02 14:04:12 -0700367 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700368 return state_ == SessionState::CLEARED;
369}
370
371bool BasicPortAllocatorSession::IsStopped() const {
Steve Anton60de6832018-10-02 14:04:12 -0700372 RTC_DCHECK_RUN_ON(network_thread_);
Steve Anton7995d8c2017-10-30 16:23:38 -0700373 return state_ == SessionState::STOPPED;
374}
375
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700376std::vector<rtc::Network*> BasicPortAllocatorSession::GetFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700377 RTC_DCHECK_RUN_ON(network_thread_);
378
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700379 std::vector<rtc::Network*> networks = GetNetworks();
380
381 // A network interface may have both IPv4 and IPv6 networks. Only if
382 // neither of the networks has any connections, the network interface
383 // is considered failed and need to be regathered on.
384 std::set<std::string> networks_with_connection;
385 for (const PortData& data : ports_) {
386 Port* port = data.port();
387 if (!port->connections().empty()) {
388 networks_with_connection.insert(port->Network()->name());
389 }
390 }
391
392 networks.erase(
393 std::remove_if(networks.begin(), networks.end(),
394 [networks_with_connection](rtc::Network* network) {
395 // If a network does not have any connection, it is
396 // considered failed.
397 return networks_with_connection.find(network->name()) !=
398 networks_with_connection.end();
399 }),
400 networks.end());
401 return networks;
402}
403
404void BasicPortAllocatorSession::RegatherOnFailedNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700405 RTC_DCHECK_RUN_ON(network_thread_);
406
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700407 // Find the list of networks that have no connection.
408 std::vector<rtc::Network*> failed_networks = GetFailedNetworks();
409 if (failed_networks.empty()) {
410 return;
411 }
412
Mirko Bonadei675513b2017-11-09 11:09:25 +0100413 RTC_LOG(LS_INFO) << "Regather candidates on failed networks";
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700414
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700415 // Mark a sequence as "network failed" if its network is in the list of failed
416 // networks, so that it won't be considered as equivalent when the session
417 // regathers ports and candidates.
418 for (AllocationSequence* sequence : sequences_) {
419 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800420 absl::c_linear_search(failed_networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700421 sequence->set_network_failed();
422 }
423 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700424
425 bool disable_equivalent_phases = true;
426 Regather(failed_networks, disable_equivalent_phases,
427 IceRegatheringReason::NETWORK_FAILURE);
428}
429
430void BasicPortAllocatorSession::RegatherOnAllNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700431 RTC_DCHECK_RUN_ON(network_thread_);
432
Steve Anton300bf8e2017-07-14 10:13:10 -0700433 std::vector<rtc::Network*> networks = GetNetworks();
434 if (networks.empty()) {
435 return;
436 }
437
Mirko Bonadei675513b2017-11-09 11:09:25 +0100438 RTC_LOG(LS_INFO) << "Regather candidates on all networks";
Steve Anton300bf8e2017-07-14 10:13:10 -0700439
440 // We expect to generate candidates that are equivalent to what we have now.
441 // Force DoAllocate to generate them instead of skipping.
442 bool disable_equivalent_phases = false;
443 Regather(networks, disable_equivalent_phases,
444 IceRegatheringReason::OCCASIONAL_REFRESH);
445}
446
447void BasicPortAllocatorSession::Regather(
448 const std::vector<rtc::Network*>& networks,
449 bool disable_equivalent_phases,
450 IceRegatheringReason reason) {
Steve Anton60de6832018-10-02 14:04:12 -0700451 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700452 // Remove ports from being used locally and send signaling to remove
453 // the candidates on the remote side.
Steve Anton300bf8e2017-07-14 10:13:10 -0700454 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(networks);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700455 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size() << " ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000457 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700458 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700459
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700460 if (allocation_started_ && network_manager_started_ && !IsStopped()) {
Steve Anton300bf8e2017-07-14 10:13:10 -0700461 SignalIceRegathering(this, reason);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700462
Steve Anton300bf8e2017-07-14 10:13:10 -0700463 DoAllocate(disable_equivalent_phases);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700464 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465}
466
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800467void BasicPortAllocatorSession::SetStunKeepaliveIntervalForReadyPorts(
Danil Chapovalov00c71832018-06-15 15:58:38 +0200468 const absl::optional<int>& stun_keepalive_interval) {
Steve Anton60de6832018-10-02 14:04:12 -0700469 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800470 auto ports = ReadyPorts();
471 for (PortInterface* port : ports) {
Qingsi Wang4ff54432018-03-01 18:25:20 -0800472 // The port type and protocol can be used to identify different subclasses
473 // of Port in the current implementation. Note that a TCPPort has the type
474 // LOCAL_PORT_TYPE but uses the protocol PROTO_TCP.
475 if (port->Type() == STUN_PORT_TYPE ||
476 (port->Type() == LOCAL_PORT_TYPE && port->GetProtocol() == PROTO_UDP)) {
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800477 static_cast<UDPPort*>(port)->set_stun_keepalive_delay(
478 stun_keepalive_interval);
479 }
480 }
481}
482
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700483std::vector<PortInterface*> BasicPortAllocatorSession::ReadyPorts() const {
Steve Anton60de6832018-10-02 14:04:12 -0700484 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700485 std::vector<PortInterface*> ret;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700486 for (const PortData& data : ports_) {
487 if (data.ready()) {
488 ret.push_back(data.port());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700489 }
490 }
491 return ret;
492}
493
494std::vector<Candidate> BasicPortAllocatorSession::ReadyCandidates() const {
Steve Anton60de6832018-10-02 14:04:12 -0700495 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700496 std::vector<Candidate> candidates;
497 for (const PortData& data : ports_) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700498 if (!data.ready()) {
499 continue;
500 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700501 GetCandidatesFromPort(data, &candidates);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700502 }
503 return candidates;
504}
505
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700506void BasicPortAllocatorSession::GetCandidatesFromPort(
507 const PortData& data,
508 std::vector<Candidate>* candidates) const {
Steve Anton60de6832018-10-02 14:04:12 -0700509 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700510 RTC_CHECK(candidates != nullptr);
511 for (const Candidate& candidate : data.port()->Candidates()) {
512 if (!CheckCandidateFilter(candidate)) {
513 continue;
514 }
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700515 auto sanitized_candidate = SanitizeCandidate(candidate);
516 candidates->push_back(sanitized_candidate);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700517 }
518}
519
Jeroen de Borst72d2ddd2018-11-27 13:20:39 -0800520bool BasicPortAllocatorSession::MdnsObfuscationEnabled() const {
521 return allocator_->network_manager()->GetMdnsResponder() != nullptr;
522}
523
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700524Candidate BasicPortAllocatorSession::SanitizeCandidate(
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700525 const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -0700526 RTC_DCHECK_RUN_ON(network_thread_);
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700527 // If the candidate has a generated hostname, we need to obfuscate its IP
528 // address when signaling this candidate.
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800529 bool use_hostname_address =
530 !c.address().hostname().empty() && !c.address().IsUnresolvedIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700531 // If adapter enumeration is disabled or host candidates are disabled,
532 // clear the raddr of STUN candidates to avoid local address leakage.
533 bool filter_stun_related_address =
534 ((flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) &&
535 (flags() & PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE)) ||
Jeroen de Borst72d2ddd2018-11-27 13:20:39 -0800536 !(candidate_filter_ & CF_HOST) || MdnsObfuscationEnabled();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700537 // If the candidate filter doesn't allow reflexive addresses, empty TURN raddr
538 // to avoid reflexive address leakage.
539 bool filter_turn_related_address = !(candidate_filter_ & CF_REFLEXIVE);
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800540 bool filter_related_address =
541 ((c.type() == STUN_PORT_TYPE && filter_stun_related_address) ||
542 (c.type() == RELAY_PORT_TYPE && filter_turn_related_address));
543 return c.ToSanitizedCopy(use_hostname_address, filter_related_address);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700544}
545
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700546bool BasicPortAllocatorSession::CandidatesAllocationDone() const {
Steve Anton60de6832018-10-02 14:04:12 -0700547 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700548 // Done only if all required AllocationSequence objects
549 // are created.
550 if (!allocation_sequences_created_) {
551 return false;
552 }
553
554 // Check that all port allocation sequences are complete (not running).
Steve Antonae226f62019-01-29 12:47:38 -0800555 if (absl::c_any_of(sequences_, [](const AllocationSequence* sequence) {
556 return sequence->state() == AllocationSequence::kRunning;
557 })) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700558 return false;
559 }
560
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700561 // If all allocated ports are no longer gathering, session must have got all
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700562 // expected candidates. Session will trigger candidates allocation complete
563 // signal.
Steve Antonae226f62019-01-29 12:47:38 -0800564 return absl::c_none_of(
565 ports_, [](const PortData& port) { return port.inprogress(); });
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700566}
567
Yves Gerey665174f2018-06-19 15:03:05 +0200568void BasicPortAllocatorSession::OnMessage(rtc::Message* message) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 switch (message->message_id) {
Yves Gerey665174f2018-06-19 15:03:05 +0200570 case MSG_CONFIG_START:
Yves Gerey665174f2018-06-19 15:03:05 +0200571 GetPortConfigurations();
572 break;
573 case MSG_CONFIG_READY:
Yves Gerey665174f2018-06-19 15:03:05 +0200574 OnConfigReady(static_cast<PortConfiguration*>(message->pdata));
575 break;
576 case MSG_ALLOCATE:
Yves Gerey665174f2018-06-19 15:03:05 +0200577 OnAllocate();
578 break;
579 case MSG_SEQUENCEOBJECTS_CREATED:
Yves Gerey665174f2018-06-19 15:03:05 +0200580 OnAllocationSequenceObjectsCreated();
581 break;
582 case MSG_CONFIG_STOP:
Yves Gerey665174f2018-06-19 15:03:05 +0200583 OnConfigStop();
584 break;
585 default:
586 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587 }
588}
589
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700590void BasicPortAllocatorSession::UpdateIceParametersInternal() {
Steve Anton60de6832018-10-02 14:04:12 -0700591 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700592 for (PortData& port : ports_) {
593 port.port()->set_content_name(content_name());
594 port.port()->SetIceParameters(component(), ice_ufrag(), ice_pwd());
595 }
596}
597
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598void BasicPortAllocatorSession::GetPortConfigurations() {
Steve Anton60de6832018-10-02 14:04:12 -0700599 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +0200600 PortConfiguration* config =
601 new PortConfiguration(allocator_->stun_servers(), username(), password());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000602
deadbeef653b8e02015-11-11 12:55:10 -0800603 for (const RelayServerConfig& turn_server : allocator_->turn_servers()) {
604 config->AddRelay(turn_server);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000605 }
606 ConfigReady(config);
607}
608
609void BasicPortAllocatorSession::ConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700610 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700611 network_thread_->Post(RTC_FROM_HERE, this, MSG_CONFIG_READY, config);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612}
613
614// Adds a configuration to the list.
615void BasicPortAllocatorSession::OnConfigReady(PortConfiguration* config) {
Steve Anton60de6832018-10-02 14:04:12 -0700616 RTC_DCHECK_RUN_ON(network_thread_);
deadbeef653b8e02015-11-11 12:55:10 -0800617 if (config) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000618 configs_.push_back(config);
deadbeef653b8e02015-11-11 12:55:10 -0800619 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000620
621 AllocatePorts();
622}
623
624void BasicPortAllocatorSession::OnConfigStop() {
Steve Anton60de6832018-10-02 14:04:12 -0700625 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626
627 // If any of the allocated ports have not completed the candidates allocation,
628 // mark those as error. Since session doesn't need any new candidates
629 // at this stage of the allocation, it's safe to discard any new candidates.
630 bool send_signal = false;
Yves Gerey665174f2018-06-19 15:03:05 +0200631 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
632 ++it) {
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700633 if (it->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 // Updating port state to error, which didn't finish allocating candidates
635 // yet.
Qingsi Wang797ede82019-04-17 21:21:54 +0000636 it->set_error();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000637 send_signal = true;
638 }
639 }
640
641 // Did we stop any running sequences?
642 for (std::vector<AllocationSequence*>::iterator it = sequences_.begin();
643 it != sequences_.end() && !send_signal; ++it) {
644 if ((*it)->state() == AllocationSequence::kStopped) {
645 send_signal = true;
646 }
647 }
648
649 // If we stopped anything that was running, send a done signal now.
650 if (send_signal) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000651 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000652 }
653}
654
655void BasicPortAllocatorSession::AllocatePorts() {
Steve Anton60de6832018-10-02 14:04:12 -0700656 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700657 network_thread_->Post(RTC_FROM_HERE, this, MSG_ALLOCATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000658}
659
660void BasicPortAllocatorSession::OnAllocate() {
Steve Anton60de6832018-10-02 14:04:12 -0700661 RTC_DCHECK_RUN_ON(network_thread_);
662
Steve Anton300bf8e2017-07-14 10:13:10 -0700663 if (network_manager_started_ && !IsStopped()) {
664 bool disable_equivalent_phases = true;
665 DoAllocate(disable_equivalent_phases);
666 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000667
668 allocation_started_ = true;
669}
670
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700671std::vector<rtc::Network*> BasicPortAllocatorSession::GetNetworks() {
Steve Anton60de6832018-10-02 14:04:12 -0700672 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700673 std::vector<rtc::Network*> networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700674 rtc::NetworkManager* network_manager = allocator_->network_manager();
nisseede5da42017-01-12 05:15:36 -0800675 RTC_DCHECK(network_manager != nullptr);
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700676 // If the network permission state is BLOCKED, we just act as if the flag has
677 // been passed in.
honghaiz8c404fa2015-09-28 07:59:43 -0700678 if (network_manager->enumeration_permission() ==
guoweisea1012b2015-08-21 09:06:28 -0700679 rtc::NetworkManager::ENUMERATION_BLOCKED) {
Guo-wei Shieh47872ec2015-08-19 10:32:46 -0700680 set_flags(flags() | PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION);
681 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000682 // If the adapter enumeration is disabled, we'll just bind to any address
683 // instead of specific NIC. This is to ensure the same routing for http
684 // traffic by OS is also used here to avoid any local or public IP leakage
685 // during stun process.
686 if (flags() & PORTALLOCATOR_DISABLE_ADAPTER_ENUMERATION) {
687 network_manager->GetAnyAddressNetworks(&networks);
688 } else {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700689 network_manager->GetNetworks(&networks);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000690 // If network enumeration fails, use the ANY address as a fallback, so we
691 // can at least try gathering candidates using the default route chosen by
692 // the OS. Or, if the PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is
693 // set, we'll use ANY address candidates either way.
694 if (networks.empty() || flags() & PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS) {
695 network_manager->GetAnyAddressNetworks(&networks);
696 }
guoweis@webrtc.orgf358aea2015-02-18 18:44:01 +0000697 }
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100698 // Filter out link-local networks if needed.
699 if (flags() & PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS) {
Qingsi Wang10a0e512018-05-16 13:37:03 -0700700 NetworkFilter link_local_filter(
701 [](rtc::Network* network) { return IPIsLinkLocal(network->prefix()); },
702 "link-local");
703 FilterNetworks(&networks, link_local_filter);
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100704 }
deadbeef3427f532017-07-26 16:09:33 -0700705 // Do some more filtering, depending on the network ignore mask and "disable
706 // costly networks" flag.
Qingsi Wang10a0e512018-05-16 13:37:03 -0700707 NetworkFilter ignored_filter(
708 [this](rtc::Network* network) {
709 return allocator_->network_ignore_mask() & network->type();
710 },
711 "ignored");
712 FilterNetworks(&networks, ignored_filter);
honghaiz60347052016-05-31 18:29:12 -0700713 if (flags() & PORTALLOCATOR_DISABLE_COSTLY_NETWORKS) {
714 uint16_t lowest_cost = rtc::kNetworkCostMax;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700715 for (rtc::Network* network : networks) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000716 // Don't determine the lowest cost from a link-local network.
717 // On iOS, a device connected to the computer will get a link-local
718 // network for communicating with the computer, however this network can't
719 // be used to connect to a peer outside the network.
720 if (rtc::IPIsLinkLocal(network->GetBestIP())) {
Yuwei Huangb181f712018-01-22 17:01:28 -0800721 continue;
722 }
honghaiz60347052016-05-31 18:29:12 -0700723 lowest_cost = std::min<uint16_t>(lowest_cost, network->GetCost());
724 }
Qingsi Wang10a0e512018-05-16 13:37:03 -0700725 NetworkFilter costly_filter(
726 [lowest_cost](rtc::Network* network) {
727 return network->GetCost() > lowest_cost + rtc::kNetworkCostLow;
728 },
729 "costly");
730 FilterNetworks(&networks, costly_filter);
honghaiz60347052016-05-31 18:29:12 -0700731 }
deadbeef3427f532017-07-26 16:09:33 -0700732 // Lastly, if we have a limit for the number of IPv6 network interfaces (by
733 // default, it's 5), remove networks to ensure that limit is satisfied.
734 //
735 // TODO(deadbeef): Instead of just taking the first N arbitrary IPv6
736 // networks, we could try to choose a set that's "most likely to work". It's
737 // hard to define what that means though; it's not just "lowest cost".
738 // Alternatively, we could just focus on making our ICE pinging logic smarter
739 // such that this filtering isn't necessary in the first place.
740 int ipv6_networks = 0;
741 for (auto it = networks.begin(); it != networks.end();) {
742 if ((*it)->prefix().family() == AF_INET6) {
743 if (ipv6_networks >= allocator_->max_ipv6_networks()) {
744 it = networks.erase(it);
745 continue;
746 } else {
747 ++ipv6_networks;
748 }
749 }
750 ++it;
751 }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700752 return networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700753}
754
755// For each network, see if we have a sequence that covers it already. If not,
756// create a new sequence to create the appropriate ports.
Steve Anton300bf8e2017-07-14 10:13:10 -0700757void BasicPortAllocatorSession::DoAllocate(bool disable_equivalent) {
Steve Anton60de6832018-10-02 14:04:12 -0700758 RTC_DCHECK_RUN_ON(network_thread_);
honghaiz8c404fa2015-09-28 07:59:43 -0700759 bool done_signal_needed = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700760 std::vector<rtc::Network*> networks = GetNetworks();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000761 if (networks.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100762 RTC_LOG(LS_WARNING)
763 << "Machine has no networks; no ports will be allocated";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000764 done_signal_needed = true;
765 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100766 RTC_LOG(LS_INFO) << "Allocate ports on " << networks.size() << " networks";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700767 PortConfiguration* config = configs_.empty() ? nullptr : configs_.back();
Peter Boström0c4e06b2015-10-07 12:23:21 +0200768 for (uint32_t i = 0; i < networks.size(); ++i) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200769 uint32_t sequence_flags = flags();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000770 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
771 // If all the ports are disabled we should just fire the allocation
772 // done event and return.
773 done_signal_needed = true;
774 break;
775 }
776
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000777 if (!config || config->relays.empty()) {
778 // No relay ports specified in this config.
779 sequence_flags |= PORTALLOCATOR_DISABLE_RELAY;
780 }
781
782 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6) &&
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000783 networks[i]->GetBestIP().family() == AF_INET6) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000784 // Skip IPv6 networks unless the flag's been set.
785 continue;
786 }
787
zhihuangb09b3f92017-03-07 14:40:51 -0800788 if (!(sequence_flags & PORTALLOCATOR_ENABLE_IPV6_ON_WIFI) &&
789 networks[i]->GetBestIP().family() == AF_INET6 &&
790 networks[i]->type() == rtc::ADAPTER_TYPE_WIFI) {
791 // Skip IPv6 Wi-Fi networks unless the flag's been set.
792 continue;
793 }
794
Steve Anton300bf8e2017-07-14 10:13:10 -0700795 if (disable_equivalent) {
796 // Disable phases that would only create ports equivalent to
797 // ones that we have already made.
798 DisableEquivalentPhases(networks[i], config, &sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000799
Steve Anton300bf8e2017-07-14 10:13:10 -0700800 if ((sequence_flags & DISABLE_ALL_PHASES) == DISABLE_ALL_PHASES) {
801 // New AllocationSequence would have nothing to do, so don't make it.
802 continue;
803 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000804 }
805
806 AllocationSequence* sequence =
807 new AllocationSequence(this, networks[i], config, sequence_flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000808 sequence->SignalPortAllocationComplete.connect(
809 this, &BasicPortAllocatorSession::OnPortAllocationComplete);
Honghai Zhang5048f572016-08-23 15:47:33 -0700810 sequence->Init();
811 sequence->Start();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000812 sequences_.push_back(sequence);
Honghai Zhang5048f572016-08-23 15:47:33 -0700813 done_signal_needed = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000814 }
815 }
816 if (done_signal_needed) {
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700817 network_thread_->Post(RTC_FROM_HERE, this, MSG_SEQUENCEOBJECTS_CREATED);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000818 }
819}
820
821void BasicPortAllocatorSession::OnNetworksChanged() {
Steve Anton60de6832018-10-02 14:04:12 -0700822 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700823 std::vector<rtc::Network*> networks = GetNetworks();
824 std::vector<rtc::Network*> failed_networks;
honghaiz8c404fa2015-09-28 07:59:43 -0700825 for (AllocationSequence* sequence : sequences_) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700826 // Mark the sequence as "network failed" if its network is not in
honghaiz8c404fa2015-09-28 07:59:43 -0700827 // |networks|.
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700828 if (!sequence->network_failed() &&
Steve Antonae226f62019-01-29 12:47:38 -0800829 !absl::c_linear_search(networks, sequence->network())) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700830 sequence->OnNetworkFailed();
831 failed_networks.push_back(sequence->network());
honghaiz8c404fa2015-09-28 07:59:43 -0700832 }
833 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700834 std::vector<PortData*> ports_to_prune = GetUnprunedPorts(failed_networks);
835 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100836 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
837 << " ports because their networks were gone";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000838 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700839 }
honghaiz8c404fa2015-09-28 07:59:43 -0700840
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700841 if (allocation_started_ && !IsStopped()) {
842 if (network_manager_started_) {
843 // If the network manager has started, it must be regathering.
844 SignalIceRegathering(this, IceRegatheringReason::NETWORK_CHANGE);
845 }
Steve Anton300bf8e2017-07-14 10:13:10 -0700846 bool disable_equivalent_phases = true;
847 DoAllocate(disable_equivalent_phases);
Honghai Zhangd93f50c2016-10-05 11:47:22 -0700848 }
849
Honghai Zhang5048f572016-08-23 15:47:33 -0700850 if (!network_manager_started_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100851 RTC_LOG(LS_INFO) << "Network manager has started";
Honghai Zhang5048f572016-08-23 15:47:33 -0700852 network_manager_started_ = true;
853 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000854}
855
856void BasicPortAllocatorSession::DisableEquivalentPhases(
Peter Boström0c4e06b2015-10-07 12:23:21 +0200857 rtc::Network* network,
858 PortConfiguration* config,
859 uint32_t* flags) {
Steve Anton60de6832018-10-02 14:04:12 -0700860 RTC_DCHECK_RUN_ON(network_thread_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200861 for (uint32_t i = 0; i < sequences_.size() &&
Yves Gerey665174f2018-06-19 15:03:05 +0200862 (*flags & DISABLE_ALL_PHASES) != DISABLE_ALL_PHASES;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200863 ++i) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000864 sequences_[i]->DisableEquivalentPhases(network, config, flags);
865 }
866}
867
868void BasicPortAllocatorSession::AddAllocatedPort(Port* port,
Yves Gerey665174f2018-06-19 15:03:05 +0200869 AllocationSequence* seq,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000870 bool prepare_address) {
Steve Anton60de6832018-10-02 14:04:12 -0700871 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000872 if (!port)
873 return;
874
Mirko Bonadei675513b2017-11-09 11:09:25 +0100875 RTC_LOG(LS_INFO) << "Adding allocated port for " << content_name();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000876 port->set_content_name(content_name());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700877 port->set_component(component());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000878 port->set_generation(generation());
deadbeeff137e972017-03-23 15:45:49 -0700879 if (allocator_->proxy().type != rtc::PROXY_NONE)
880 port->set_proxy(allocator_->user_agent(), allocator_->proxy());
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700881 port->set_send_retransmit_count_attribute(
882 (flags() & PORTALLOCATOR_ENABLE_STUN_RETRANSMIT_ATTRIBUTE) != 0);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000883
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000884 PortData data(port, seq);
885 ports_.push_back(data);
886
887 port->SignalCandidateReady.connect(
888 this, &BasicPortAllocatorSession::OnCandidateReady);
889 port->SignalPortComplete.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200890 &BasicPortAllocatorSession::OnPortComplete);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000891 port->SignalDestroyed.connect(this,
Yves Gerey665174f2018-06-19 15:03:05 +0200892 &BasicPortAllocatorSession::OnPortDestroyed);
893 port->SignalPortError.connect(this, &BasicPortAllocatorSession::OnPortError);
894 RTC_LOG(LS_INFO) << port->ToString() << ": Added port to allocator";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000895
896 if (prepare_address)
897 port->PrepareAddress();
898}
899
900void BasicPortAllocatorSession::OnAllocationSequenceObjectsCreated() {
Steve Anton60de6832018-10-02 14:04:12 -0700901 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000902 allocation_sequences_created_ = true;
903 // Send candidate allocation complete signal if we have no sequences.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000904 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000905}
906
Yves Gerey665174f2018-06-19 15:03:05 +0200907void BasicPortAllocatorSession::OnCandidateReady(Port* port,
908 const Candidate& c) {
Steve Anton60de6832018-10-02 14:04:12 -0700909 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000910 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000911 RTC_DCHECK(data != NULL);
Jonas Olssond7d762d2018-03-28 09:47:51 +0200912 RTC_LOG(LS_INFO) << port->ToString()
913 << ": Gathered candidate: " << c.ToSensitiveString();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000914 // Discarding any candidate signal if port allocation status is
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700915 // already done with gathering.
916 if (!data->inprogress()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100917 RTC_LOG(LS_WARNING)
deadbeefa64edb82016-07-15 14:42:21 -0700918 << "Discarding candidate because port is already done gathering.";
danilchapf4e8cf02016-06-30 01:55:03 -0700919 return;
Honghai Zhang17aac052016-06-29 21:41:53 -0700920 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700921
danilchapf4e8cf02016-06-30 01:55:03 -0700922 // Mark that the port has a pairable candidate, either because we have a
923 // usable candidate from the port, or simply because the port is bound to the
924 // any address and therefore has no host candidate. This will trigger the port
925 // to start creating candidate pairs (connections) and issue connectivity
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700926 // checks. If port has already been marked as having a pairable candidate,
927 // do nothing here.
928 // Note: We should check whether any candidates may become ready after this
929 // because there we will check whether the candidate is generated by the ready
930 // ports, which may include this port.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700931 bool pruned = false;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700932 if (CandidatePairable(c, port) && !data->has_pairable_candidate()) {
danilchapf4e8cf02016-06-30 01:55:03 -0700933 data->set_has_pairable_candidate(true);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700934
935 if (prune_turn_ports_ && port->Type() == RELAY_PORT_TYPE) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700936 pruned = PruneTurnPorts(port);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700937 }
938 // If the current port is not pruned yet, SignalPortReady.
939 if (!data->pruned()) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000940 RTC_LOG(LS_INFO) << port->ToString() << ": Port ready.";
941 SignalPortReady(this, port);
Honghai Zhanga74363c2016-07-28 18:06:15 -0700942 port->KeepAliveUntilPruned();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700943 }
Honghai Zhang17aac052016-06-29 21:41:53 -0700944 }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700945
deadbeef1c5e6d02017-09-15 17:46:56 -0700946 if (data->ready() && CheckCandidateFilter(c)) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000947 std::vector<Candidate> candidates;
Qingsi Wangb49b8f12018-09-16 17:48:10 -0700948 candidates.push_back(SanitizeCandidate(c));
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000949 SignalCandidatesReady(this, candidates);
deadbeefa64edb82016-07-15 14:42:21 -0700950 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100951 RTC_LOG(LS_INFO) << "Discarding candidate because it doesn't match filter.";
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700952 }
953
954 // If we have pruned any port, maybe need to signal port allocation done.
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700955 if (pruned) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000956 MaybeSignalCandidatesAllocationDone();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700957 }
958}
959
960Port* BasicPortAllocatorSession::GetBestTurnPortForNetwork(
961 const std::string& network_name) const {
Steve Anton60de6832018-10-02 14:04:12 -0700962 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700963 Port* best_turn_port = nullptr;
964 for (const PortData& data : ports_) {
965 if (data.port()->Network()->name() == network_name &&
966 data.port()->Type() == RELAY_PORT_TYPE && data.ready() &&
967 (!best_turn_port || ComparePort(data.port(), best_turn_port) > 0)) {
968 best_turn_port = data.port();
969 }
970 }
971 return best_turn_port;
972}
973
974bool BasicPortAllocatorSession::PruneTurnPorts(Port* newly_pairable_turn_port) {
Steve Anton60de6832018-10-02 14:04:12 -0700975 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700976 // Note: We determine the same network based only on their network names. So
977 // if an IPv4 address and an IPv6 address have the same network name, they
978 // are considered the same network here.
979 const std::string& network_name = newly_pairable_turn_port->Network()->name();
980 Port* best_turn_port = GetBestTurnPortForNetwork(network_name);
981 // |port| is already in the list of ports, so the best port cannot be nullptr.
982 RTC_CHECK(best_turn_port != nullptr);
983
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700984 bool pruned = false;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700985 std::vector<PortData*> ports_to_prune;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700986 for (PortData& data : ports_) {
987 if (data.port()->Network()->name() == network_name &&
988 data.port()->Type() == RELAY_PORT_TYPE && !data.pruned() &&
989 ComparePort(data.port(), best_turn_port) < 0) {
Honghai Zhang8eeecab2016-07-28 13:20:15 -0700990 pruned = true;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700991 if (data.port() != newly_pairable_turn_port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +0000992 // These ports will be pruned in PrunePortsAndRemoveCandidates.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700993 ports_to_prune.push_back(&data);
994 } else {
995 data.Prune();
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700996 }
997 }
998 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700999
1000 if (!ports_to_prune.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001001 RTC_LOG(LS_INFO) << "Prune " << ports_to_prune.size()
1002 << " low-priority TURN ports";
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001003 PrunePortsAndRemoveCandidates(ports_to_prune);
Honghai Zhang8eeecab2016-07-28 13:20:15 -07001004 }
1005 return pruned;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001006}
1007
Honghai Zhanga74363c2016-07-28 18:06:15 -07001008void BasicPortAllocatorSession::PruneAllPorts() {
Steve Anton60de6832018-10-02 14:04:12 -07001009 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhanga74363c2016-07-28 18:06:15 -07001010 for (PortData& data : ports_) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001011 data.Prune();
Honghai Zhanga74363c2016-07-28 18:06:15 -07001012 }
1013}
1014
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001015void BasicPortAllocatorSession::OnPortComplete(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001016 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001017 RTC_LOG(LS_INFO) << port->ToString()
1018 << ": Port completed gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001019 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001020 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001021
1022 // Ignore any late signals.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001023 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001024 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001025 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001026
1027 // Moving to COMPLETE state.
Qingsi Wang797ede82019-04-17 21:21:54 +00001028 data->set_complete();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001029 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001030 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001031}
1032
1033void BasicPortAllocatorSession::OnPortError(Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001034 RTC_DCHECK_RUN_ON(network_thread_);
Jonas Olssond7d762d2018-03-28 09:47:51 +02001035 RTC_LOG(LS_INFO) << port->ToString()
1036 << ": Port encountered error while gathering candidates.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001037 PortData* data = FindPort(port);
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001038 RTC_DCHECK(data != NULL);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001039 // We might have already given up on this port and stopped it.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001040 if (!data->inprogress()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001041 return;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001042 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001043
1044 // SignalAddressError is currently sent from StunPort/TurnPort.
1045 // But this signal itself is generic.
Qingsi Wang797ede82019-04-17 21:21:54 +00001046 data->set_error();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001047 // Send candidate allocation complete signal if this was the last port.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001048 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001049}
1050
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001051bool BasicPortAllocatorSession::CheckCandidateFilter(const Candidate& c) const {
Steve Anton60de6832018-10-02 14:04:12 -07001052 RTC_DCHECK_RUN_ON(network_thread_);
1053
Qingsi Wang797ede82019-04-17 21:21:54 +00001054 uint32_t filter = candidate_filter_;
1055
1056 // When binding to any address, before sending packets out, the getsockname
1057 // returns all 0s, but after sending packets, it'll be the NIC used to
1058 // send. All 0s is not a valid ICE candidate address and should be filtered
1059 // out.
1060 if (c.address().IsAnyIP()) {
1061 return false;
1062 }
1063
1064 if (c.type() == RELAY_PORT_TYPE) {
1065 return ((filter & CF_RELAY) != 0);
1066 } else if (c.type() == STUN_PORT_TYPE) {
1067 return ((filter & CF_REFLEXIVE) != 0);
1068 } else if (c.type() == LOCAL_PORT_TYPE) {
1069 if ((filter & CF_REFLEXIVE) && !c.address().IsPrivateIP()) {
1070 // We allow host candidates if the filter allows server-reflexive
1071 // candidates and the candidate is a public IP. Because we don't generate
1072 // server-reflexive candidates if they have the same IP as the host
1073 // candidate (i.e. when the host candidate is a public IP), filtering to
1074 // only server-reflexive candidates won't work right when the host
1075 // candidates have public IPs.
1076 return true;
1077 }
1078
1079 return ((filter & CF_HOST) != 0);
1080 }
1081 return false;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001082}
1083
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001084bool BasicPortAllocatorSession::CandidatePairable(const Candidate& c,
1085 const Port* port) const {
Steve Anton60de6832018-10-02 14:04:12 -07001086 RTC_DCHECK_RUN_ON(network_thread_);
1087
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001088 bool candidate_signalable = CheckCandidateFilter(c);
1089
1090 // When device enumeration is disabled (to prevent non-default IP addresses
1091 // from leaking), we ping from some local candidates even though we don't
1092 // signal them. However, if host candidates are also disabled (for example, to
1093 // prevent even default IP addresses from leaking), we still don't want to
1094 // ping from them, even if device enumeration is disabled. Thus, we check for
1095 // both device enumeration and host candidates being disabled.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001096 bool network_enumeration_disabled = c.address().IsAnyIP();
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001097 bool can_ping_from_candidate =
1098 (port->SharedSocket() || c.protocol() == TCP_PROTOCOL_NAME);
1099 bool host_candidates_disabled = !(candidate_filter_ & CF_HOST);
1100
1101 return candidate_signalable ||
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001102 (network_enumeration_disabled && can_ping_from_candidate &&
Taylor Brandstetter417eebe2016-05-23 16:02:19 -07001103 !host_candidates_disabled);
1104}
1105
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001106void BasicPortAllocatorSession::OnPortAllocationComplete(
1107 AllocationSequence* seq) {
Steve Anton60de6832018-10-02 14:04:12 -07001108 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001109 // Send candidate allocation complete signal if all ports are done.
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001110 MaybeSignalCandidatesAllocationDone();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001111}
1112
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001113void BasicPortAllocatorSession::MaybeSignalCandidatesAllocationDone() {
Steve Anton60de6832018-10-02 14:04:12 -07001114 RTC_DCHECK_RUN_ON(network_thread_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001115 if (CandidatesAllocationDone()) {
1116 if (pooled()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001117 RTC_LOG(LS_INFO) << "All candidates gathered for pooled session.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001118 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001119 RTC_LOG(LS_INFO) << "All candidates gathered for " << content_name()
1120 << ":" << component() << ":" << generation();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001121 }
1122 SignalCandidatesAllocationDone(this);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001123 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001124}
1125
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001126void BasicPortAllocatorSession::OnPortDestroyed(PortInterface* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001127 RTC_DCHECK_RUN_ON(network_thread_);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001128 for (std::vector<PortData>::iterator iter = ports_.begin();
1129 iter != ports_.end(); ++iter) {
1130 if (port == iter->port()) {
1131 ports_.erase(iter);
Yves Gerey665174f2018-06-19 15:03:05 +02001132 RTC_LOG(LS_INFO) << port->ToString() << ": Removed port from allocator ("
Jonas Olssond7d762d2018-03-28 09:47:51 +02001133 << static_cast<int>(ports_.size()) << " remaining)";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001134 return;
1135 }
1136 }
nissec80e7412017-01-11 05:56:46 -08001137 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001138}
1139
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001140BasicPortAllocatorSession::PortData* BasicPortAllocatorSession::FindPort(
1141 Port* port) {
Steve Anton60de6832018-10-02 14:04:12 -07001142 RTC_DCHECK_RUN_ON(network_thread_);
Yves Gerey665174f2018-06-19 15:03:05 +02001143 for (std::vector<PortData>::iterator it = ports_.begin(); it != ports_.end();
1144 ++it) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001145 if (it->port() == port) {
1146 return &*it;
1147 }
1148 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001149 return NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001150}
1151
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001152std::vector<BasicPortAllocatorSession::PortData*>
1153BasicPortAllocatorSession::GetUnprunedPorts(
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001154 const std::vector<rtc::Network*>& networks) {
Steve Anton60de6832018-10-02 14:04:12 -07001155 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001156 std::vector<PortData*> unpruned_ports;
1157 for (PortData& port : ports_) {
1158 if (!port.pruned() &&
Steve Antonae226f62019-01-29 12:47:38 -08001159 absl::c_linear_search(networks, port.sequence()->network())) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001160 unpruned_ports.push_back(&port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001161 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001162 }
1163 return unpruned_ports;
1164}
1165
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001166void BasicPortAllocatorSession::PrunePortsAndRemoveCandidates(
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001167 const std::vector<PortData*>& port_data_list) {
Steve Anton60de6832018-10-02 14:04:12 -07001168 RTC_DCHECK_RUN_ON(network_thread_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001169 std::vector<PortInterface*> pruned_ports;
1170 std::vector<Candidate> removed_candidates;
1171 for (PortData* data : port_data_list) {
Honghai Zhanga74363c2016-07-28 18:06:15 -07001172 // Prune the port so that it may be destroyed.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001173 data->Prune();
1174 pruned_ports.push_back(data->port());
1175 if (data->has_pairable_candidate()) {
1176 GetCandidatesFromPort(*data, &removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001177 // Mark the port as having no pairable candidates so that its candidates
1178 // won't be removed multiple times.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001179 data->set_has_pairable_candidate(false);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001180 }
1181 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001182 if (!pruned_ports.empty()) {
1183 SignalPortsPruned(this, pruned_ports);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001184 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001185 if (!removed_candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001186 RTC_LOG(LS_INFO) << "Removed " << removed_candidates.size()
1187 << " candidates";
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001188 SignalCandidatesRemoved(this, removed_candidates);
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001189 }
1190}
1191
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001192// AllocationSequence
1193
1194AllocationSequence::AllocationSequence(BasicPortAllocatorSession* session,
1195 rtc::Network* network,
1196 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +02001197 uint32_t flags)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001198 : session_(session),
1199 network_(network),
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001200 config_(config),
1201 state_(kInit),
1202 flags_(flags),
1203 udp_socket_(),
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001204 udp_port_(NULL),
Yves Gerey665174f2018-06-19 15:03:05 +02001205 phase_(0) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001206
Honghai Zhang5048f572016-08-23 15:47:33 -07001207void AllocationSequence::Init() {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001208 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1209 udp_socket_.reset(session_->socket_factory()->CreateUdpSocket(
deadbeef5c3c1042017-08-04 15:01:57 -07001210 rtc::SocketAddress(network_->GetBestIP(), 0),
1211 session_->allocator()->min_port(), session_->allocator()->max_port()));
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001212 if (udp_socket_) {
Yves Gerey665174f2018-06-19 15:03:05 +02001213 udp_socket_->SignalReadPacket.connect(this,
1214 &AllocationSequence::OnReadPacket);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001215 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001216 // Continuing if |udp_socket_| is NULL, as local TCP and RelayPort using TCP
1217 // are next available options to setup a communication channel.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001218 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001219}
1220
1221void AllocationSequence::Clear() {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001222 udp_port_ = NULL;
Jonas Oreland202994c2017-12-18 12:10:43 +01001223 relay_ports_.clear();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001224}
1225
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001226void AllocationSequence::OnNetworkFailed() {
1227 RTC_DCHECK(!network_failed_);
1228 network_failed_ = true;
1229 // Stop the allocation sequence if its network failed.
honghaiz8c404fa2015-09-28 07:59:43 -07001230 Stop();
honghaiz8c404fa2015-09-28 07:59:43 -07001231}
1232
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001233AllocationSequence::~AllocationSequence() {
1234 session_->network_thread()->Clear(this);
1235}
1236
1237void AllocationSequence::DisableEquivalentPhases(rtc::Network* network,
Yves Gerey665174f2018-06-19 15:03:05 +02001238 PortConfiguration* config,
1239 uint32_t* flags) {
Honghai Zhang5622c5e2016-07-01 13:59:29 -07001240 if (network_failed_) {
1241 // If the network of this allocation sequence has ever become failed,
honghaiz8c404fa2015-09-28 07:59:43 -07001242 // it won't be equivalent to the new network.
1243 return;
1244 }
1245
deadbeef5c3c1042017-08-04 15:01:57 -07001246 if (!((network == network_) && (previous_best_ip_ == network->GetBestIP()))) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001247 // Different network setup; nothing is equivalent.
1248 return;
1249 }
1250
1251 // Else turn off the stuff that we've already got covered.
1252
deadbeef1c46a352017-09-27 11:24:05 -07001253 // Every config implicitly specifies local, so turn that off right away if we
1254 // already have a port of the corresponding type. Look for a port that
1255 // matches this AllocationSequence's network, is the right protocol, and
1256 // hasn't encountered an error.
1257 // TODO(deadbeef): This doesn't take into account that there may be another
1258 // AllocationSequence that's ABOUT to allocate a UDP port, but hasn't yet.
1259 // This can happen if, say, there's a network change event right before an
1260 // application-triggered ICE restart. Hopefully this problem will just go
1261 // away if we get rid of the gathering "phases" though, which is planned.
Steve Antonae226f62019-01-29 12:47:38 -08001262 if (absl::c_any_of(session_->ports_,
1263 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wang797ede82019-04-17 21:21:54 +00001264 return p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001265 p.port()->GetProtocol() == PROTO_UDP &&
Qingsi Wang797ede82019-04-17 21:21:54 +00001266 !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001267 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001268 *flags |= PORTALLOCATOR_DISABLE_UDP;
1269 }
Steve Antonae226f62019-01-29 12:47:38 -08001270 if (absl::c_any_of(session_->ports_,
1271 [this](const BasicPortAllocatorSession::PortData& p) {
Qingsi Wang797ede82019-04-17 21:21:54 +00001272 return p.port()->Network() == network_ &&
Steve Antonae226f62019-01-29 12:47:38 -08001273 p.port()->GetProtocol() == PROTO_TCP &&
Qingsi Wang797ede82019-04-17 21:21:54 +00001274 !p.error();
Steve Antonae226f62019-01-29 12:47:38 -08001275 })) {
deadbeef1c46a352017-09-27 11:24:05 -07001276 *flags |= PORTALLOCATOR_DISABLE_TCP;
1277 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001278
1279 if (config_ && config) {
Qingsi Wang797ede82019-04-17 21:21:54 +00001280 if (config_->StunServers() == config->StunServers()) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001281 // Already got this STUN servers covered.
1282 *flags |= PORTALLOCATOR_DISABLE_STUN;
1283 }
1284 if (!config_->relays.empty()) {
1285 // Already got relays covered.
1286 // NOTE: This will even skip a _different_ set of relay servers if we
1287 // were to be given one, but that never happens in our codebase. Should
1288 // probably get rid of the list in PortConfiguration and just keep a
1289 // single relay server in each one.
1290 *flags |= PORTALLOCATOR_DISABLE_RELAY;
1291 }
1292 }
1293}
1294
1295void AllocationSequence::Start() {
1296 state_ = kRunning;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001297 session_->network_thread()->Post(RTC_FROM_HERE, this, MSG_ALLOCATION_PHASE);
deadbeef5c3c1042017-08-04 15:01:57 -07001298 // Take a snapshot of the best IP, so that when DisableEquivalentPhases is
1299 // called next time, we enable all phases if the best IP has since changed.
1300 previous_best_ip_ = network_->GetBestIP();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001301}
1302
1303void AllocationSequence::Stop() {
1304 // If the port is completed, don't set it to stopped.
1305 if (state_ == kRunning) {
1306 state_ = kStopped;
1307 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1308 }
1309}
1310
1311void AllocationSequence::OnMessage(rtc::Message* msg) {
nisseede5da42017-01-12 05:15:36 -08001312 RTC_DCHECK(rtc::Thread::Current() == session_->network_thread());
1313 RTC_DCHECK(msg->message_id == MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001314
deadbeef1c5e6d02017-09-15 17:46:56 -07001315 const char* const PHASE_NAMES[kNumPhases] = {"Udp", "Relay", "Tcp"};
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001316
1317 // Perform all of the phases in the current step.
Jonas Olssond7d762d2018-03-28 09:47:51 +02001318 RTC_LOG(LS_INFO) << network_->ToString()
1319 << ": Allocation Phase=" << PHASE_NAMES[phase_];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001320
1321 switch (phase_) {
1322 case PHASE_UDP:
1323 CreateUDPPorts();
1324 CreateStunPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001325 break;
1326
1327 case PHASE_RELAY:
1328 CreateRelayPorts();
1329 break;
1330
1331 case PHASE_TCP:
1332 CreateTCPPorts();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001333 state_ = kCompleted;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001334 break;
1335
1336 default:
nissec80e7412017-01-11 05:56:46 -08001337 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001338 }
1339
1340 if (state() == kRunning) {
1341 ++phase_;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001342 session_->network_thread()->PostDelayed(RTC_FROM_HERE,
1343 session_->allocator()->step_delay(),
1344 this, MSG_ALLOCATION_PHASE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001345 } else {
1346 // If all phases in AllocationSequence are completed, no allocation
1347 // steps needed further. Canceling pending signal.
1348 session_->network_thread()->Clear(this, MSG_ALLOCATION_PHASE);
1349 SignalPortAllocationComplete(this);
1350 }
1351}
1352
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001353void AllocationSequence::CreateUDPPorts() {
1354 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001355 RTC_LOG(LS_VERBOSE) << "AllocationSequence: UDP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001356 return;
1357 }
1358
1359 // TODO(mallinath) - Remove UDPPort creating socket after shared socket
1360 // is enabled completely.
Steve Antona8f1e562018-10-10 11:29:44 -07001361 std::unique_ptr<UDPPort> port;
Guo-wei Shieh9af97f82015-11-10 14:47:39 -08001362 bool emit_local_candidate_for_anyaddress =
1363 !IsFlagSet(PORTALLOCATOR_DISABLE_DEFAULT_LOCAL_CANDIDATE);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001364 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) && udp_socket_) {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001365 port = UDPPort::Create(
1366 session_->network_thread(), session_->socket_factory(), network_,
1367 udp_socket_.get(), session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001368 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1369 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001370 } else {
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001371 port = UDPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001372 session_->network_thread(), session_->socket_factory(), network_,
Guo-wei Shiehfe3bc9d2015-08-20 08:48:20 -07001373 session_->allocator()->min_port(), session_->allocator()->max_port(),
1374 session_->username(), session_->password(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001375 session_->allocator()->origin(), emit_local_candidate_for_anyaddress,
1376 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001377 }
1378
1379 if (port) {
1380 // If shared socket is enabled, STUN candidate will be allocated by the
1381 // UDPPort.
1382 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
Steve Antona8f1e562018-10-10 11:29:44 -07001383 udp_port_ = port.get();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001384 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001385
1386 // If STUN is not disabled, setting stun server address to port.
1387 if (!IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001388 if (config_ && !config_->StunServers().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001389 RTC_LOG(LS_INFO)
1390 << "AllocationSequence: UDPPort will be handling the "
Jonas Olssond7d762d2018-03-28 09:47:51 +02001391 "STUN candidate generation.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001392 port->set_server_addresses(config_->StunServers());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001393 }
1394 }
1395 }
1396
Steve Antona8f1e562018-10-10 11:29:44 -07001397 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001398 }
1399}
1400
1401void AllocationSequence::CreateTCPPorts() {
1402 if (IsFlagSet(PORTALLOCATOR_DISABLE_TCP)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001403 RTC_LOG(LS_VERBOSE) << "AllocationSequence: TCP ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001404 return;
1405 }
1406
Steve Antona8f1e562018-10-10 11:29:44 -07001407 std::unique_ptr<Port> port = TCPPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001408 session_->network_thread(), session_->socket_factory(), network_,
1409 session_->allocator()->min_port(), session_->allocator()->max_port(),
1410 session_->username(), session_->password(),
1411 session_->allocator()->allow_tcp_listen());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001412 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001413 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001414 // Since TCPPort is not created using shared socket, |port| will not be
1415 // added to the dequeue.
1416 }
1417}
1418
1419void AllocationSequence::CreateStunPorts() {
1420 if (IsFlagSet(PORTALLOCATOR_DISABLE_STUN)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001421 RTC_LOG(LS_VERBOSE) << "AllocationSequence: STUN ports disabled, skipping.";
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001422 return;
1423 }
1424
1425 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET)) {
1426 return;
1427 }
1428
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001429 if (!(config_ && !config_->StunServers().empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001430 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001431 << "AllocationSequence: No STUN server configured, skipping.";
1432 return;
1433 }
1434
Steve Antona8f1e562018-10-10 11:29:44 -07001435 std::unique_ptr<StunPort> port = StunPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001436 session_->network_thread(), session_->socket_factory(), network_,
1437 session_->allocator()->min_port(), session_->allocator()->max_port(),
1438 session_->username(), session_->password(), config_->StunServers(),
Qingsi Wang4ff54432018-03-01 18:25:20 -08001439 session_->allocator()->origin(),
1440 session_->allocator()->stun_candidate_keepalive_interval());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001441 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001442 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001443 // Since StunPort is not created using shared socket, |port| will not be
1444 // added to the dequeue.
1445 }
1446}
1447
1448void AllocationSequence::CreateRelayPorts() {
1449 if (IsFlagSet(PORTALLOCATOR_DISABLE_RELAY)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001450 RTC_LOG(LS_VERBOSE)
1451 << "AllocationSequence: Relay ports disabled, skipping.";
1452 return;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001453 }
1454
1455 // If BasicPortAllocatorSession::OnAllocate left relay ports enabled then we
1456 // ought to have a relay list for them here.
kwibergee89e782017-08-09 17:22:01 -07001457 RTC_DCHECK(config_);
1458 RTC_DCHECK(!config_->relays.empty());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001459 if (!(config_ && !config_->relays.empty())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001460 RTC_LOG(LS_WARNING)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001461 << "AllocationSequence: No relay server configured, skipping.";
1462 return;
1463 }
1464
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07001465 for (RelayServerConfig& relay : config_->relays) {
1466 if (relay.type == RELAY_GTURN) {
1467 CreateGturnPort(relay);
1468 } else if (relay.type == RELAY_TURN) {
1469 CreateTurnPort(relay);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001470 } else {
nissec80e7412017-01-11 05:56:46 -08001471 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001472 }
1473 }
1474}
1475
1476void AllocationSequence::CreateGturnPort(const RelayServerConfig& config) {
1477 // TODO(mallinath) - Rename RelayPort to GTurnPort.
Steve Antona8f1e562018-10-10 11:29:44 -07001478 std::unique_ptr<RelayPort> port = RelayPort::Create(
deadbeef5c3c1042017-08-04 15:01:57 -07001479 session_->network_thread(), session_->socket_factory(), network_,
1480 session_->allocator()->min_port(), session_->allocator()->max_port(),
1481 config_->username, config_->password);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001482 if (port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001483 RelayPort* port_ptr = port.release();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001484 // Since RelayPort is not created using shared socket, |port| will not be
1485 // added to the dequeue.
1486 // Note: We must add the allocated port before we add addresses because
1487 // the latter will create candidates that need name and preference
1488 // settings. However, we also can't prepare the address (normally
1489 // done by AddAllocatedPort) until we have these addresses. So we
1490 // wait to do that until below.
Steve Antona8f1e562018-10-10 11:29:44 -07001491 session_->AddAllocatedPort(port_ptr, this, false);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001492
1493 // Add the addresses of this protocol.
1494 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001495 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001496 ++relay_port) {
Steve Antona8f1e562018-10-10 11:29:44 -07001497 port_ptr->AddServerAddress(*relay_port);
1498 port_ptr->AddExternalAddress(*relay_port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001499 }
1500 // Start fetching an address for this port.
Steve Antona8f1e562018-10-10 11:29:44 -07001501 port_ptr->PrepareAddress();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001502 }
1503}
1504
1505void AllocationSequence::CreateTurnPort(const RelayServerConfig& config) {
1506 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001507 for (relay_port = config.ports.begin(); relay_port != config.ports.end();
1508 ++relay_port) {
Guo-wei Shieh13d35f62015-08-26 15:32:56 -07001509 // Skip UDP connections to relay servers if it's disallowed.
1510 if (IsFlagSet(PORTALLOCATOR_DISABLE_UDP_RELAY) &&
1511 relay_port->proto == PROTO_UDP) {
1512 continue;
1513 }
1514
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001515 // Do not create a port if the server address family is known and does
1516 // not match the local IP address family.
1517 int server_ip_family = relay_port->address.ipaddr().family();
deadbeef5c3c1042017-08-04 15:01:57 -07001518 int local_ip_family = network_->GetBestIP().family();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001519 if (server_ip_family != AF_UNSPEC && server_ip_family != local_ip_family) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001520 RTC_LOG(LS_INFO)
1521 << "Server and local address families are not compatible. "
Yves Gerey665174f2018-06-19 15:03:05 +02001522 "Server address: "
1523 << relay_port->address.ipaddr().ToString()
Mirko Bonadei675513b2017-11-09 11:09:25 +01001524 << " Local address: " << network_->GetBestIP().ToString();
Honghai Zhang3d31bd62016-08-10 10:33:05 -07001525 continue;
1526 }
1527
Jonas Oreland202994c2017-12-18 12:10:43 +01001528 CreateRelayPortArgs args;
1529 args.network_thread = session_->network_thread();
1530 args.socket_factory = session_->socket_factory();
1531 args.network = network_;
1532 args.username = session_->username();
1533 args.password = session_->password();
1534 args.server_address = &(*relay_port);
1535 args.config = &config;
1536 args.origin = session_->allocator()->origin();
1537 args.turn_customizer = session_->allocator()->turn_customizer();
1538
1539 std::unique_ptr<cricket::Port> port;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001540 // Shared socket mode must be enabled only for UDP based ports. Hence
1541 // don't pass shared socket for ports which will create TCP sockets.
1542 // TODO(mallinath) - Enable shared socket mode for TURN ports. Disabled
1543 // due to webrtc bug https://code.google.com/p/webrtc/issues/detail?id=3537
1544 if (IsFlagSet(PORTALLOCATOR_ENABLE_SHARED_SOCKET) &&
honghaizf421bdc2015-07-17 16:21:55 -07001545 relay_port->proto == PROTO_UDP && udp_socket_) {
Jonas Oreland202994c2017-12-18 12:10:43 +01001546 port = session_->allocator()->relay_port_factory()->Create(
1547 args, udp_socket_.get());
1548
1549 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001550 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1551 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001552 continue;
1553 }
1554
1555 relay_ports_.push_back(port.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001556 // Listen to the port destroyed signal, to allow AllocationSequence to
1557 // remove entrt from it's map.
1558 port->SignalDestroyed.connect(this, &AllocationSequence::OnPortDestroyed);
1559 } else {
Jonas Oreland202994c2017-12-18 12:10:43 +01001560 port = session_->allocator()->relay_port_factory()->Create(
Yves Gerey665174f2018-06-19 15:03:05 +02001561 args, session_->allocator()->min_port(),
Jonas Oreland202994c2017-12-18 12:10:43 +01001562 session_->allocator()->max_port());
1563
1564 if (!port) {
Yves Gerey665174f2018-06-19 15:03:05 +02001565 RTC_LOG(LS_WARNING) << "Failed to create relay port with "
1566 << args.server_address->address.ToString();
Jonas Oreland202994c2017-12-18 12:10:43 +01001567 continue;
1568 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001569 }
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001570 RTC_DCHECK(port != NULL);
Jonas Oreland202994c2017-12-18 12:10:43 +01001571 session_->AddAllocatedPort(port.release(), this, true);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001572 }
1573}
1574
Yves Gerey665174f2018-06-19 15:03:05 +02001575void AllocationSequence::OnReadPacket(rtc::AsyncPacketSocket* socket,
1576 const char* data,
1577 size_t size,
1578 const rtc::SocketAddress& remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001579 const int64_t& packet_time_us) {
nisseede5da42017-01-12 05:15:36 -08001580 RTC_DCHECK(socket == udp_socket_.get());
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001581
1582 bool turn_port_found = false;
1583
1584 // Try to find the TurnPort that matches the remote address. Note that the
1585 // message could be a STUN binding response if the TURN server is also used as
1586 // a STUN server. We don't want to parse every message here to check if it is
1587 // a STUN binding response, so we pass the message to TurnPort regardless of
1588 // the message type. The TurnPort will just ignore the message since it will
1589 // not find any request by transaction ID.
Jonas Oreland202994c2017-12-18 12:10:43 +01001590 for (auto* port : relay_ports_) {
1591 if (port->CanHandleIncomingPacketsFrom(remote_addr)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001592 if (port->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001593 packet_time_us)) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001594 return;
1595 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001596 turn_port_found = true;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001597 }
1598 }
1599
1600 if (udp_port_) {
1601 const ServerAddresses& stun_servers = udp_port_->server_addresses();
1602
1603 // Pass the packet to the UdpPort if there is no matching TurnPort, or if
1604 // the TURN server is also a STUN server.
1605 if (!turn_port_found ||
1606 stun_servers.find(remote_addr) != stun_servers.end()) {
Sergey Ulanov17fa6722016-05-10 10:20:47 -07001607 RTC_DCHECK(udp_port_->SharedSocket());
1608 udp_port_->HandleIncomingPacket(socket, data, size, remote_addr,
Niels Möllere6933812018-11-05 13:01:41 +01001609 packet_time_us);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001610 }
1611 }
1612}
1613
1614void AllocationSequence::OnPortDestroyed(PortInterface* port) {
1615 if (udp_port_ == port) {
Mirko Bonadei5f4d47b2018-08-22 17:41:22 +00001616 udp_port_ = NULL;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001617 return;
1618 }
1619
Steve Antonae226f62019-01-29 12:47:38 -08001620 auto it = absl::c_find(relay_ports_, port);
Jonas Oreland202994c2017-12-18 12:10:43 +01001621 if (it != relay_ports_.end()) {
1622 relay_ports_.erase(it);
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001623 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001624 RTC_LOG(LS_ERROR) << "Unexpected OnPortDestroyed for nonexistent port.";
nissec80e7412017-01-11 05:56:46 -08001625 RTC_NOTREACHED();
jiayl@webrtc.org7e5b3802015-01-22 21:28:39 +00001626 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001627}
1628
1629// PortConfiguration
Yves Gerey665174f2018-06-19 15:03:05 +02001630PortConfiguration::PortConfiguration(const rtc::SocketAddress& stun_address,
1631 const std::string& username,
1632 const std::string& password)
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001633 : stun_address(stun_address), username(username), password(password) {
1634 if (!stun_address.IsNil())
1635 stun_servers.insert(stun_address);
1636}
1637
1638PortConfiguration::PortConfiguration(const ServerAddresses& stun_servers,
1639 const std::string& username,
1640 const std::string& password)
Yves Gerey665174f2018-06-19 15:03:05 +02001641 : stun_servers(stun_servers), username(username), password(password) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001642 if (!stun_servers.empty())
1643 stun_address = *(stun_servers.begin());
1644}
1645
Steve Anton7995d8c2017-10-30 16:23:38 -07001646PortConfiguration::~PortConfiguration() = default;
1647
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001648ServerAddresses PortConfiguration::StunServers() {
1649 if (!stun_address.IsNil() &&
1650 stun_servers.find(stun_address) == stun_servers.end()) {
1651 stun_servers.insert(stun_address);
1652 }
deadbeefc5d0d952015-07-16 10:22:21 -07001653 // Every UDP TURN server should also be used as a STUN server.
1654 ServerAddresses turn_servers = GetRelayServerAddresses(RELAY_TURN, PROTO_UDP);
1655 for (const rtc::SocketAddress& turn_server : turn_servers) {
1656 if (stun_servers.find(turn_server) == stun_servers.end()) {
1657 stun_servers.insert(turn_server);
1658 }
1659 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001660 return stun_servers;
1661}
1662
1663void PortConfiguration::AddRelay(const RelayServerConfig& config) {
1664 relays.push_back(config);
1665}
1666
Yves Gerey665174f2018-06-19 15:03:05 +02001667bool PortConfiguration::SupportsProtocol(const RelayServerConfig& relay,
1668 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001669 PortList::const_iterator relay_port;
Yves Gerey665174f2018-06-19 15:03:05 +02001670 for (relay_port = relay.ports.begin(); relay_port != relay.ports.end();
1671 ++relay_port) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001672 if (relay_port->proto == type)
1673 return true;
1674 }
1675 return false;
1676}
1677
1678bool PortConfiguration::SupportsProtocol(RelayType turn_type,
1679 ProtocolType type) const {
1680 for (size_t i = 0; i < relays.size(); ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +02001681 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type))
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001682 return true;
1683 }
1684 return false;
1685}
1686
1687ServerAddresses PortConfiguration::GetRelayServerAddresses(
Yves Gerey665174f2018-06-19 15:03:05 +02001688 RelayType turn_type,
1689 ProtocolType type) const {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001690 ServerAddresses servers;
1691 for (size_t i = 0; i < relays.size(); ++i) {
1692 if (relays[i].type == turn_type && SupportsProtocol(relays[i], type)) {
1693 servers.insert(relays[i].ports.front().address);
1694 }
1695 }
1696 return servers;
1697}
1698
1699} // namespace cricket