blob: fb74ba5d74f3f6d137d853e513d55ed633c0bbf5 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef P2P_CLIENT_BASICPORTALLOCATOR_H_
12#define P2P_CLIENT_BASICPORTALLOCATOR_H_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000013
kwiberg3ec46792016-04-27 07:22:53 -070014#include <memory>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000015#include <string>
16#include <vector>
17
Jonas Orelandbdcee282017-10-10 14:01:40 +020018#include "api/turncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "p2p/base/portallocator.h"
Jonas Oreland202994c2017-12-18 12:10:43 +010020#include "p2p/client/turnportfactory.h"
21#include "p2p/client/relayportfactoryinterface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/checks.h"
23#include "rtc_base/messagequeue.h"
24#include "rtc_base/network.h"
25#include "rtc_base/thread.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000026
27namespace cricket {
28
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000029class BasicPortAllocator : public PortAllocator {
30 public:
Jonas Oreland202994c2017-12-18 12:10:43 +010031 // note: The (optional) relay_port_factory is owned by caller
32 // and must have a life time that exceeds that of BasicPortAllocator.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000033 BasicPortAllocator(rtc::NetworkManager* network_manager,
Jonas Orelandbdcee282017-10-10 14:01:40 +020034 rtc::PacketSocketFactory* socket_factory,
Jonas Oreland202994c2017-12-18 12:10:43 +010035 webrtc::TurnCustomizer* customizer = nullptr,
36 RelayPortFactoryInterface* relay_port_factory = nullptr);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037 explicit BasicPortAllocator(rtc::NetworkManager* network_manager);
38 BasicPortAllocator(rtc::NetworkManager* network_manager,
39 rtc::PacketSocketFactory* socket_factory,
40 const ServerAddresses& stun_servers);
41 BasicPortAllocator(rtc::NetworkManager* network_manager,
42 const ServerAddresses& stun_servers,
Jonas Oreland202994c2017-12-18 12:10:43 +010043 const rtc::SocketAddress& relay_address_udp,
44 const rtc::SocketAddress& relay_address_tcp,
45 const rtc::SocketAddress& relay_address_ssl);
Steve Anton7995d8c2017-10-30 16:23:38 -070046 ~BasicPortAllocator() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000047
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080048 // Set to kDefaultNetworkIgnoreMask by default.
Steve Anton7995d8c2017-10-30 16:23:38 -070049 void SetNetworkIgnoreMask(int network_ignore_mask) override;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080050 int network_ignore_mask() const { return network_ignore_mask_; }
51
Honghai Zhang5622c5e2016-07-01 13:59:29 -070052 rtc::NetworkManager* network_manager() const { return network_manager_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000053
54 // If socket_factory() is set to NULL each PortAllocatorSession
55 // creates its own socket factory.
56 rtc::PacketSocketFactory* socket_factory() { return socket_factory_; }
57
deadbeef653b8e02015-11-11 12:55:10 -080058 PortAllocatorSession* CreateSessionInternal(
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000059 const std::string& content_name,
60 int component,
61 const std::string& ice_ufrag,
deadbeef653b8e02015-11-11 12:55:10 -080062 const std::string& ice_pwd) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000063
Taylor Brandstettera1c30352016-05-13 08:15:11 -070064 // Convenience method that adds a TURN server to the configuration.
65 void AddTurnServer(const RelayServerConfig& turn_server);
66
Jonas Oreland202994c2017-12-18 12:10:43 +010067 RelayPortFactoryInterface* relay_port_factory() {
68 return relay_port_factory_;
69 }
70
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071 private:
72 void Construct();
73
Honghai Zhangd93f50c2016-10-05 11:47:22 -070074 void OnIceRegathering(PortAllocatorSession* session,
75 IceRegatheringReason reason);
76
Jonas Oreland202994c2017-12-18 12:10:43 +010077 // This function makes sure that relay_port_factory_ is set properly.
78 void InitRelayPortFactory(RelayPortFactoryInterface* relay_port_factory);
79
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000080 rtc::NetworkManager* network_manager_;
81 rtc::PacketSocketFactory* socket_factory_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000082 bool allow_tcp_listen_;
Taylor Brandstetter0c7e9f52015-12-29 14:14:52 -080083 int network_ignore_mask_ = rtc::kDefaultNetworkIgnoreMask;
Jonas Oreland202994c2017-12-18 12:10:43 +010084
85 // This is the factory being used.
86 RelayPortFactoryInterface* relay_port_factory_;
87
88 // This instance is created if caller does pass a factory.
89 std::unique_ptr<RelayPortFactoryInterface> default_relay_port_factory_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000090};
91
92struct PortConfiguration;
93class AllocationSequence;
94
Honghai Zhangd8f6fc42016-07-01 17:31:12 -070095enum class SessionState {
96 GATHERING, // Actively allocating ports and gathering candidates.
97 CLEARED, // Current allocation process has been stopped but may start
98 // new ones.
99 STOPPED // This session has completely stopped, no new allocation
100 // process will be started.
101};
102
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000103class BasicPortAllocatorSession : public PortAllocatorSession,
104 public rtc::MessageHandler {
105 public:
106 BasicPortAllocatorSession(BasicPortAllocator* allocator,
107 const std::string& content_name,
108 int component,
109 const std::string& ice_ufrag,
110 const std::string& ice_pwd);
Steve Anton7995d8c2017-10-30 16:23:38 -0700111 ~BasicPortAllocatorSession() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000112
Steve Anton7995d8c2017-10-30 16:23:38 -0700113 virtual BasicPortAllocator* allocator();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000114 rtc::Thread* network_thread() { return network_thread_; }
115 rtc::PacketSocketFactory* socket_factory() { return socket_factory_; }
116
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700117 void SetCandidateFilter(uint32_t filter) override;
deadbeef653b8e02015-11-11 12:55:10 -0800118 void StartGettingPorts() override;
119 void StopGettingPorts() override;
120 void ClearGettingPorts() override;
Steve Anton7995d8c2017-10-30 16:23:38 -0700121 bool IsGettingPorts() override;
122 bool IsCleared() const override;
123 bool IsStopped() const override;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700124 // These will all be cricket::Ports.
125 std::vector<PortInterface*> ReadyPorts() const override;
126 std::vector<Candidate> ReadyCandidates() const override;
127 bool CandidatesAllocationDone() const override;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700128 void RegatherOnFailedNetworks() override;
Steve Anton300bf8e2017-07-14 10:13:10 -0700129 void RegatherOnAllNetworks() override;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800130 void SetStunKeepaliveIntervalForReadyPorts(
131 const rtc::Optional<int>& stun_keepalive_interval) override;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700132 void PruneAllPorts() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133
134 protected:
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700135 void UpdateIceParametersInternal() override;
136
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000137 // Starts the process of getting the port configurations.
138 virtual void GetPortConfigurations();
139
140 // Adds a port configuration that is now ready. Once we have one for each
141 // network (or a timeout occurs), we will start allocating ports.
142 virtual void ConfigReady(PortConfiguration* config);
143
144 // MessageHandler. Can be overriden if message IDs do not conflict.
deadbeef653b8e02015-11-11 12:55:10 -0800145 void OnMessage(rtc::Message* message) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146
147 private:
148 class PortData {
149 public:
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700150 PortData() {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000151 PortData(Port* port, AllocationSequence* seq)
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700152 : port_(port), sequence_(seq) {}
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000153
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700154 Port* port() const { return port_; }
155 AllocationSequence* sequence() const { return sequence_; }
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700156 bool has_pairable_candidate() const { return has_pairable_candidate_; }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700157 bool complete() const { return state_ == STATE_COMPLETE; }
158 bool error() const { return state_ == STATE_ERROR; }
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700159 bool pruned() const { return state_ == STATE_PRUNED; }
160 bool inprogress() const { return state_ == STATE_INPROGRESS; }
161 // Returns true if this port is ready to be used.
162 bool ready() const {
163 return has_pairable_candidate_ && state_ != STATE_ERROR &&
164 state_ != STATE_PRUNED;
165 }
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700166 // Sets the state to "PRUNED" and prunes the Port.
167 void Prune() {
168 state_ = STATE_PRUNED;
169 if (port()) {
170 port()->Prune();
171 }
172 }
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700173 void set_has_pairable_candidate(bool has_pairable_candidate) {
174 if (has_pairable_candidate) {
nisseede5da42017-01-12 05:15:36 -0800175 RTC_DCHECK(state_ == STATE_INPROGRESS);
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700176 }
177 has_pairable_candidate_ = has_pairable_candidate;
178 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000179 void set_complete() {
180 state_ = STATE_COMPLETE;
181 }
182 void set_error() {
nisseede5da42017-01-12 05:15:36 -0800183 RTC_DCHECK(state_ == STATE_INPROGRESS);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 state_ = STATE_ERROR;
185 }
186
187 private:
188 enum State {
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700189 STATE_INPROGRESS, // Still gathering candidates.
190 STATE_COMPLETE, // All candidates allocated and ready for process.
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700191 STATE_ERROR, // Error in gathering candidates.
192 STATE_PRUNED // Pruned by higher priority ports on the same network
193 // interface. Only TURN ports may be pruned.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000194 };
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700195 Port* port_ = nullptr;
196 AllocationSequence* sequence_ = nullptr;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700197 bool has_pairable_candidate_ = false;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700198 State state_ = STATE_INPROGRESS;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000199 };
200
201 void OnConfigReady(PortConfiguration* config);
202 void OnConfigStop();
203 void AllocatePorts();
204 void OnAllocate();
Steve Anton300bf8e2017-07-14 10:13:10 -0700205 void DoAllocate(bool disable_equivalent_phases);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 void OnNetworksChanged();
207 void OnAllocationSequenceObjectsCreated();
208 void DisableEquivalentPhases(rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200209 PortConfiguration* config,
210 uint32_t* flags);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 void AddAllocatedPort(Port* port, AllocationSequence* seq,
212 bool prepare_address);
213 void OnCandidateReady(Port* port, const Candidate& c);
214 void OnPortComplete(Port* port);
215 void OnPortError(Port* port);
216 void OnProtocolEnabled(AllocationSequence* seq, ProtocolType proto);
217 void OnPortDestroyed(PortInterface* port);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000218 void MaybeSignalCandidatesAllocationDone();
219 void OnPortAllocationComplete(AllocationSequence* seq);
220 PortData* FindPort(Port* port);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700221 std::vector<rtc::Network*> GetNetworks();
222 std::vector<rtc::Network*> GetFailedNetworks();
Steve Anton300bf8e2017-07-14 10:13:10 -0700223 void Regather(const std::vector<rtc::Network*>& networks,
224 bool disable_equivalent_phases,
225 IceRegatheringReason reason);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000226
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700227 bool CheckCandidateFilter(const Candidate& c) const;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700228 bool CandidatePairable(const Candidate& c, const Port* port) const;
229 // Clear the related address according to the flags and candidate filter
230 // in order to avoid leaking any information.
231 Candidate SanitizeRelatedAddress(const Candidate& c) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000232
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700233 std::vector<PortData*> GetUnprunedPorts(
234 const std::vector<rtc::Network*>& networks);
235 // Prunes ports and signal the remote side to remove the candidates that
236 // were previously signaled from these ports.
237 void PrunePortsAndRemoveCandidates(
238 const std::vector<PortData*>& port_data_list);
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700239 // Gets filtered and sanitized candidates generated from a port and
240 // append to |candidates|.
241 void GetCandidatesFromPort(const PortData& data,
242 std::vector<Candidate>* candidates) const;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700243 Port* GetBestTurnPortForNetwork(const std::string& network_name) const;
244 // Returns true if at least one TURN port is pruned.
245 bool PruneTurnPorts(Port* newly_pairable_turn_port);
246
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000247 BasicPortAllocator* allocator_;
248 rtc::Thread* network_thread_;
kwiberg3ec46792016-04-27 07:22:53 -0700249 std::unique_ptr<rtc::PacketSocketFactory> owned_socket_factory_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000250 rtc::PacketSocketFactory* socket_factory_;
251 bool allocation_started_;
252 bool network_manager_started_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253 bool allocation_sequences_created_;
254 std::vector<PortConfiguration*> configs_;
255 std::vector<AllocationSequence*> sequences_;
256 std::vector<PortData> ports_;
Taylor Brandstetter417eebe2016-05-23 16:02:19 -0700257 uint32_t candidate_filter_ = CF_ALL;
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -0700258 // Whether to prune low-priority ports, taken from the port allocator.
259 bool prune_turn_ports_;
Honghai Zhangd8f6fc42016-07-01 17:31:12 -0700260 SessionState state_ = SessionState::CLEARED;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000261
262 friend class AllocationSequence;
263};
264
265// Records configuration information useful in creating ports.
deadbeef653b8e02015-11-11 12:55:10 -0800266// TODO(deadbeef): Rename "relay" to "turn_server" in this struct.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000267struct PortConfiguration : public rtc::MessageData {
268 // TODO(jiayl): remove |stun_address| when Chrome is updated.
269 rtc::SocketAddress stun_address;
270 ServerAddresses stun_servers;
271 std::string username;
272 std::string password;
273
274 typedef std::vector<RelayServerConfig> RelayList;
275 RelayList relays;
276
277 // TODO(jiayl): remove this ctor when Chrome is updated.
278 PortConfiguration(const rtc::SocketAddress& stun_address,
279 const std::string& username,
280 const std::string& password);
281
282 PortConfiguration(const ServerAddresses& stun_servers,
283 const std::string& username,
284 const std::string& password);
285
Steve Anton7995d8c2017-10-30 16:23:38 -0700286 ~PortConfiguration() override;
287
deadbeefc5d0d952015-07-16 10:22:21 -0700288 // Returns addresses of both the explicitly configured STUN servers,
289 // and TURN servers that should be used as STUN servers.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000290 ServerAddresses StunServers();
291
292 // Adds another relay server, with the given ports and modifier, to the list.
293 void AddRelay(const RelayServerConfig& config);
294
295 // Determines whether the given relay server supports the given protocol.
296 bool SupportsProtocol(const RelayServerConfig& relay,
297 ProtocolType type) const;
298 bool SupportsProtocol(RelayType turn_type, ProtocolType type) const;
299 // Helper method returns the server addresses for the matching RelayType and
300 // Protocol type.
301 ServerAddresses GetRelayServerAddresses(
302 RelayType turn_type, ProtocolType type) const;
303};
304
honghaizf421bdc2015-07-17 16:21:55 -0700305class UDPPort;
306class TurnPort;
307
308// Performs the allocation of ports, in a sequenced (timed) manner, for a given
309// network and IP address.
310class AllocationSequence : public rtc::MessageHandler,
311 public sigslot::has_slots<> {
312 public:
313 enum State {
314 kInit, // Initial state.
315 kRunning, // Started allocating ports.
316 kStopped, // Stopped from running.
317 kCompleted, // All ports are allocated.
318
319 // kInit --> kRunning --> {kCompleted|kStopped}
320 };
321 AllocationSequence(BasicPortAllocatorSession* session,
322 rtc::Network* network,
323 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200324 uint32_t flags);
Steve Anton7995d8c2017-10-30 16:23:38 -0700325 ~AllocationSequence() override;
Honghai Zhang5048f572016-08-23 15:47:33 -0700326 void Init();
honghaizf421bdc2015-07-17 16:21:55 -0700327 void Clear();
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700328 void OnNetworkFailed();
honghaizf421bdc2015-07-17 16:21:55 -0700329
330 State state() const { return state_; }
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700331 rtc::Network* network() const { return network_; }
332
333 bool network_failed() const { return network_failed_; }
334 void set_network_failed() { network_failed_ = true; }
honghaizf421bdc2015-07-17 16:21:55 -0700335
336 // Disables the phases for a new sequence that this one already covers for an
337 // equivalent network setup.
338 void DisableEquivalentPhases(rtc::Network* network,
339 PortConfiguration* config,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200340 uint32_t* flags);
honghaizf421bdc2015-07-17 16:21:55 -0700341
342 // Starts and stops the sequence. When started, it will continue allocating
343 // new ports on its own timed schedule.
344 void Start();
345 void Stop();
346
347 // MessageHandler
Steve Anton7995d8c2017-10-30 16:23:38 -0700348 void OnMessage(rtc::Message* msg) override;
honghaizf421bdc2015-07-17 16:21:55 -0700349
honghaizf421bdc2015-07-17 16:21:55 -0700350 // Signal from AllocationSequence, when it's done with allocating ports.
351 // This signal is useful, when port allocation fails which doesn't result
352 // in any candidates. Using this signal BasicPortAllocatorSession can send
353 // its candidate discovery conclusion signal. Without this signal,
354 // BasicPortAllocatorSession doesn't have any event to trigger signal. This
355 // can also be achieved by starting timer in BPAS.
356 sigslot::signal1<AllocationSequence*> SignalPortAllocationComplete;
357
358 protected:
359 // For testing.
360 void CreateTurnPort(const RelayServerConfig& config);
361
362 private:
363 typedef std::vector<ProtocolType> ProtocolList;
364
Peter Boström0c4e06b2015-10-07 12:23:21 +0200365 bool IsFlagSet(uint32_t flag) { return ((flags_ & flag) != 0); }
honghaizf421bdc2015-07-17 16:21:55 -0700366 void CreateUDPPorts();
367 void CreateTCPPorts();
368 void CreateStunPorts();
369 void CreateRelayPorts();
370 void CreateGturnPort(const RelayServerConfig& config);
371
372 void OnReadPacket(rtc::AsyncPacketSocket* socket,
373 const char* data,
374 size_t size,
375 const rtc::SocketAddress& remote_addr,
376 const rtc::PacketTime& packet_time);
377
378 void OnPortDestroyed(PortInterface* port);
379
380 BasicPortAllocatorSession* session_;
Honghai Zhang5622c5e2016-07-01 13:59:29 -0700381 bool network_failed_ = false;
honghaizf421bdc2015-07-17 16:21:55 -0700382 rtc::Network* network_;
deadbeef5c3c1042017-08-04 15:01:57 -0700383 // Compared with the new best IP in DisableEquivalentPhases.
384 rtc::IPAddress previous_best_ip_;
honghaizf421bdc2015-07-17 16:21:55 -0700385 PortConfiguration* config_;
386 State state_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200387 uint32_t flags_;
honghaizf421bdc2015-07-17 16:21:55 -0700388 ProtocolList protocols_;
kwiberg3ec46792016-04-27 07:22:53 -0700389 std::unique_ptr<rtc::AsyncPacketSocket> udp_socket_;
honghaizf421bdc2015-07-17 16:21:55 -0700390 // There will be only one udp port per AllocationSequence.
391 UDPPort* udp_port_;
Jonas Oreland202994c2017-12-18 12:10:43 +0100392 std::vector<Port*> relay_ports_;
honghaizf421bdc2015-07-17 16:21:55 -0700393 int phase_;
394};
395
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396} // namespace cricket
397
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200398#endif // P2P_CLIENT_BASICPORTALLOCATOR_H_