blob: c66e590b47503652cec9b6e966c5429b9f5d0b92 [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_BASE_PORT_H_
12#define P2P_BASE_PORT_H_
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000013
14#include <map>
kwiberg3ec46792016-04-27 07:22:53 -070015#include <memory>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <set>
17#include <string>
18#include <vector>
19
Patrik Höglunde2d6a062017-10-05 14:53:33 +020020#include "api/candidate.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/optional.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "p2p/base/candidatepairinterface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "p2p/base/packetlossestimator.h"
24#include "p2p/base/packetsocketfactory.h"
25#include "p2p/base/portinterface.h"
26#include "p2p/base/stun.h"
27#include "p2p/base/stunrequest.h"
28#include "rtc_base/asyncpacketsocket.h"
29#include "rtc_base/checks.h"
Zhi Huang942bc2e2017-11-13 13:26:07 -080030#include "rtc_base/nethelper.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/network.h"
32#include "rtc_base/proxyinfo.h"
33#include "rtc_base/ratetracker.h"
34#include "rtc_base/sigslot.h"
35#include "rtc_base/socketaddress.h"
36#include "rtc_base/thread.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037
38namespace cricket {
39
40class Connection;
41class ConnectionRequest;
42
43extern const char LOCAL_PORT_TYPE[];
44extern const char STUN_PORT_TYPE[];
45extern const char PRFLX_PORT_TYPE[];
46extern const char RELAY_PORT_TYPE[];
47
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000048// RFC 6544, TCP candidate encoding rules.
49extern const int DISCARD_PORT;
50extern const char TCPTYPE_ACTIVE_STR[];
51extern const char TCPTYPE_PASSIVE_STR[];
52extern const char TCPTYPE_SIMOPEN_STR[];
53
Honghai Zhang2b342bf2015-09-30 09:51:58 -070054// The minimum time we will wait before destroying a connection after creating
55// it.
honghaiz34b11eb2016-03-16 08:55:44 -070056static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070057
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080058// A connection will be declared dead if it has not received anything for this
59// long.
honghaiz34b11eb2016-03-16 08:55:44 -070060static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080061
Peter Thatcher04ac81f2015-09-21 11:48:28 -070062// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070063static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000064
65// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070066static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070069static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000070
71// This is the length of time that we wait for a ping response to come back.
skvlad51072462017-02-02 11:50:14 -080072// There is no harm to keep this value high other than a small amount
73// of increased memory. But in some networks (2G),
74// we observe up to 60s RTTs.
75static const int CONNECTION_RESPONSE_TIMEOUT = 60 * 1000; // 60 seconds
honghaiz34b11eb2016-03-16 08:55:44 -070076
77// The number of pings that must fail to respond before we become unwritable.
78static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000079
80enum RelayType {
81 RELAY_GTURN, // Legacy google relay service.
82 RELAY_TURN // Standard (TURN) relay service.
83};
84
85enum IcePriorityValue {
hnsl277b2502016-12-13 05:17:23 -080086 ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
87 ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
88 ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
Taylor Brandstetter62351c92016-08-11 16:05:07 -070089 ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000090 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
91 ICE_TYPE_PREFERENCE_SRFLX = 100,
92 ICE_TYPE_PREFERENCE_PRFLX = 110,
93 ICE_TYPE_PREFERENCE_HOST = 126
94};
95
hbos06495bc2017-01-02 08:08:18 -080096// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
97enum class IceCandidatePairState {
98 WAITING = 0, // Check has not been performed, Waiting pair on CL.
99 IN_PROGRESS, // Check has been sent, transaction is in progress.
100 SUCCEEDED, // Check already done, produced a successful result.
101 FAILED, // Check for this connection failed.
102 // According to spec there should also be a frozen state, but nothing is ever
103 // frozen because we have not implemented ICE freezing logic.
104};
105
Taylor Brandstetter4770fd92017-12-15 13:34:53 -0800106// Stats that we can return about the connections for a transport channel.
107// TODO(hta): Rename to ConnectionStats
108struct ConnectionInfo {
109 ConnectionInfo();
110 ConnectionInfo(const ConnectionInfo&);
111 ~ConnectionInfo();
112
113 bool best_connection; // Is this the best connection we have?
114 bool writable; // Has this connection received a STUN response?
115 bool receiving; // Has this connection received anything?
116 bool timeout; // Has this connection timed out?
117 bool new_connection; // Is this a newly created connection?
118 size_t rtt; // The STUN RTT for this connection.
119 size_t sent_total_bytes; // Total bytes sent on this connection.
120 size_t sent_bytes_second; // Bps over the last measurement interval.
121 size_t sent_discarded_packets; // Number of outgoing packets discarded due to
122 // socket errors.
123 size_t sent_total_packets; // Number of total outgoing packets attempted for
124 // sending.
125 size_t sent_ping_requests_total; // Number of STUN ping request sent.
126 size_t sent_ping_requests_before_first_response; // Number of STUN ping
127 // sent before receiving the first response.
128 size_t sent_ping_responses; // Number of STUN ping response sent.
129
130 size_t recv_total_bytes; // Total bytes received on this connection.
131 size_t recv_bytes_second; // Bps over the last measurement interval.
132 size_t recv_ping_requests; // Number of STUN ping request received.
133 size_t recv_ping_responses; // Number of STUN ping response received.
134 Candidate local_candidate; // The local candidate for this connection.
135 Candidate remote_candidate; // The remote candidate for this connection.
136 void* key; // A static value that identifies this conn.
137 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-state
138 IceCandidatePairState state;
139 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-priority
140 uint64_t priority;
141 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-nominated
142 bool nominated;
143 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
144 uint64_t total_round_trip_time_ms;
145 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
146 rtc::Optional<uint32_t> current_round_trip_time_ms;
147};
148
149// Information about all the connections of a channel.
150typedef std::vector<ConnectionInfo> ConnectionInfos;
151
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152const char* ProtoToString(ProtocolType proto);
153bool StringToProto(const char* value, ProtocolType* proto);
154
155struct ProtocolAddress {
156 rtc::SocketAddress address;
157 ProtocolType proto;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000158
159 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
hnsl277b2502016-12-13 05:17:23 -0800160 : address(a), proto(p) {}
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700161
162 bool operator==(const ProtocolAddress& o) const {
hnsl277b2502016-12-13 05:17:23 -0800163 return address == o.address && proto == o.proto;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700164 }
165 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000166};
167
168typedef std::set<rtc::SocketAddress> ServerAddresses;
169
170// Represents a local communication mechanism that can be used to create
171// connections to similar mechanisms of the other client. Subclasses of this
172// one add support for specific mechanisms like local UDP ports.
173class Port : public PortInterface, public rtc::MessageHandler,
174 public sigslot::has_slots<> {
175 public:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700176 // INIT: The state when a port is just created.
177 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
178 // connection is using it.
179 // PRUNED: It will be destroyed if no connection is using it for a period of
180 // 30 seconds.
181 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000182 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700183 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000184 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000185 rtc::Network* network,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000186 const std::string& username_fragment,
187 const std::string& password);
deadbeef5c3c1042017-08-04 15:01:57 -0700188 // TODO(deadbeef): Delete this constructor once clients are moved off of it.
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000189 Port(rtc::Thread* thread,
190 const std::string& type,
191 rtc::PacketSocketFactory* factory,
192 rtc::Network* network,
193 const rtc::IPAddress& ip,
deadbeef5c3c1042017-08-04 15:01:57 -0700194 const std::string& username_fragment,
Steve Antonf2737d22017-10-31 16:27:34 -0700195 const std::string& password);
deadbeef5c3c1042017-08-04 15:01:57 -0700196 Port(rtc::Thread* thread,
197 const std::string& type,
198 rtc::PacketSocketFactory* factory,
199 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200200 uint16_t min_port,
201 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000202 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000203 const std::string& password);
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700204 ~Port() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700206 const std::string& Type() const override;
207 rtc::Network* Network() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000208
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000209 // Methods to set/get ICE role and tiebreaker values.
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700210 IceRole GetIceRole() const override;
211 void SetIceRole(IceRole role) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000212
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700213 void SetIceTiebreaker(uint64_t tiebreaker) override;
214 uint64_t IceTiebreaker() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700216 bool SharedSocket() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217 void ResetSharedSocket() { shared_socket_ = false; }
218
Honghai Zhanga74363c2016-07-28 18:06:15 -0700219 // Should not destroy the port even if no connection is using it. Called when
220 // a port is ready to use.
221 void KeepAliveUntilPruned();
222 // Allows a port to be destroyed if no connection is using it.
223 void Prune();
224
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000225 // The thread on which this port performs its I/O.
226 rtc::Thread* thread() { return thread_; }
227
228 // The factory used to create the sockets of this port.
229 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
230 void set_socket_factory(rtc::PacketSocketFactory* factory) {
231 factory_ = factory;
232 }
233
234 // For debugging purposes.
235 const std::string& content_name() const { return content_name_; }
236 void set_content_name(const std::string& content_name) {
237 content_name_ = content_name;
238 }
239
240 int component() const { return component_; }
241 void set_component(int component) { component_ = component; }
242
243 bool send_retransmit_count_attribute() const {
244 return send_retransmit_count_attribute_;
245 }
246 void set_send_retransmit_count_attribute(bool enable) {
247 send_retransmit_count_attribute_ = enable;
248 }
249
250 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-22 17:14:15 -0700251 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200252 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000253
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000254 const std::string username_fragment() const;
255 const std::string& password() const { return password_; }
256
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700257 // May be called when this port was initially created by a pooled
258 // PortAllocatorSession, and is now being assigned to an ICE transport.
259 // Updates the information for candidates as well.
260 void SetIceParameters(int component,
261 const std::string& username_fragment,
262 const std::string& password);
263
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000264 // Fired when candidates are discovered by the port. When all candidates
265 // are discovered that belong to port SignalAddressReady is fired.
266 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
267
268 // Provides all of the above information in one handy object.
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700269 const std::vector<Candidate>& Candidates() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000270
271 // SignalPortComplete is sent when port completes the task of candidates
272 // allocation.
273 sigslot::signal1<Port*> SignalPortComplete;
274 // This signal sent when port fails to allocate candidates and this port
275 // can't be used in establishing the connections. When port is in shared mode
276 // and port fails to allocate one of the candidates, port shouldn't send
277 // this signal as other candidates might be usefull in establishing the
278 // connection.
279 sigslot::signal1<Port*> SignalPortError;
280
281 // Returns a map containing all of the connections of this port, keyed by the
282 // remote address.
283 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
284 const AddressMap& connections() { return connections_; }
285
286 // Returns the connection to the given address or NULL if none exists.
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700287 Connection* GetConnection(const rtc::SocketAddress& remote_addr) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288
289 // Called each time a connection is created.
290 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
291
292 // In a shared socket mode each port which shares the socket will decide
293 // to accept the packet based on the |remote_addr|. Currently only UDP
294 // port implemented this method.
295 // TODO(mallinath) - Make it pure virtual.
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700296 virtual bool HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
297 const char* data,
298 size_t size,
299 const rtc::SocketAddress& remote_addr,
300 const rtc::PacketTime& packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000301
302 // Sends a response message (normal or error) to the given request. One of
303 // these methods should be called as a response to SignalUnknownAddress.
304 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700305 void SendBindingResponse(StunMessage* request,
306 const rtc::SocketAddress& addr) override;
307 void SendBindingErrorResponse(StunMessage* request,
308 const rtc::SocketAddress& addr,
309 int error_code,
310 const std::string& reason) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311
312 void set_proxy(const std::string& user_agent,
313 const rtc::ProxyInfo& proxy) {
314 user_agent_ = user_agent;
315 proxy_ = proxy;
316 }
317 const std::string& user_agent() { return user_agent_; }
318 const rtc::ProxyInfo& proxy() { return proxy_; }
319
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700320 void EnablePortPackets() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321
322 // Called if the port has no connections and is no longer useful.
323 void Destroy();
324
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700325 void OnMessage(rtc::Message* pmsg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326
327 // Debugging description of this port
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700328 std::string ToString() const override;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200329 uint16_t min_port() { return min_port_; }
330 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000331
332 // Timeout shortening function to speed up unit tests.
333 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
334
335 // This method will return local and remote username fragements from the
336 // stun username attribute if present.
337 bool ParseStunUsername(const StunMessage* stun_msg,
338 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700339 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340 void CreateStunUsername(const std::string& remote_username,
341 std::string* stun_username_attr_str) const;
342
343 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
344 IceMessage* stun_msg,
345 const std::string& remote_ufrag);
346
stefanc1aeaf02015-10-15 07:26:07 -0700347 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100348 // This is made pure virtual to notify subclasses of Port that they MUST
349 // listen to AsyncPacketSocket::SignalSentPacket and then call
350 // PortInterface::OnSentPacket.
351 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
352 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700353
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000354 // Called when the socket is currently able to send.
355 void OnReadyToSend();
356
357 // Called when the Connection discovers a local peer reflexive candidate.
358 // Returns the index of the new local candidate.
359 size_t AddPrflxCandidate(const Candidate& local);
360
honghaiza0c44ea2016-03-23 16:07:48 -0700361 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000362
363 protected:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700364 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000365
Honghai Zhang351d77b2016-05-20 15:08:29 -0700366 virtual void UpdateNetworkCost();
367
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 void set_type(const std::string& type) { type_ = type; }
369
Peter Boström2758c662017-02-13 20:33:27 -0500370 // Deprecated. Use the AddAddress() method below with "url" instead.
371 // TODO(zhihuang): Remove this after downstream applications stop using it.
372 void AddAddress(const rtc::SocketAddress& address,
373 const rtc::SocketAddress& base_address,
374 const rtc::SocketAddress& related_address,
375 const std::string& protocol,
376 const std::string& relay_protocol,
377 const std::string& tcptype,
378 const std::string& type,
379 uint32_t type_preference,
380 uint32_t relay_preference,
381 bool final);
382
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000383 void AddAddress(const rtc::SocketAddress& address,
384 const rtc::SocketAddress& base_address,
385 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700386 const std::string& protocol,
387 const std::string& relay_protocol,
388 const std::string& tcptype,
389 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200390 uint32_t type_preference,
391 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800392 const std::string& url,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700393 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394
honghaiz36f50e82016-06-01 15:57:03 -0700395 // Adds the given connection to the map keyed by the remote candidate address.
396 // If an existing connection has the same address, the existing one will be
397 // replaced and destroyed.
398 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000399
400 // Called when a packet is received from an unknown address that is not
401 // currently a connection. If this is an authenticated STUN binding request,
402 // then we will signal the client.
403 void OnReadPacket(const char* data, size_t size,
404 const rtc::SocketAddress& addr,
405 ProtocolType proto);
406
407 // If the given data comprises a complete and correct STUN message then the
408 // return value is true, otherwise false. If the message username corresponds
409 // with this port's username fragment, msg will contain the parsed STUN
410 // message. Otherwise, the function may send a STUN response internally.
411 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700412 bool GetStunMessage(const char* data,
413 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700415 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700416 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000417
418 // Checks if the address in addr is compatible with the port's ip.
419 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
420
421 // Returns default DSCP value.
422 rtc::DiffServCodePoint DefaultDscpValue() const {
423 // No change from what MediaChannel set.
424 return rtc::DSCP_NO_CHANGE;
425 }
426
honghaiz36f50e82016-06-01 15:57:03 -0700427 // Extra work to be done in subclasses when a connection is destroyed.
428 virtual void HandleConnectionDestroyed(Connection* conn) {}
429
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000430 private:
431 void Construct();
432 // Called when one of our connections deletes itself.
433 void OnConnectionDestroyed(Connection* conn);
434
Honghai Zhang351d77b2016-05-20 15:08:29 -0700435 void OnNetworkTypeChanged(const rtc::Network* network);
436
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000437 rtc::Thread* thread_;
438 rtc::PacketSocketFactory* factory_;
439 std::string type_;
440 bool send_retransmit_count_attribute_;
441 rtc::Network* network_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200442 uint16_t min_port_;
443 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 std::string content_name_;
445 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200446 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000447 // In order to establish a connection to this Port (so that real data can be
448 // sent through), the other side must send us a STUN binding request that is
449 // authenticated with this username_fragment and password.
450 // PortAllocatorSession will provide these username_fragment and password.
451 //
452 // Note: we should always use username_fragment() instead of using
453 // |ice_username_fragment_| directly. For the details see the comment on
454 // username_fragment().
455 std::string ice_username_fragment_;
456 std::string password_;
457 std::vector<Candidate> candidates_;
458 AddressMap connections_;
459 int timeout_delay_;
460 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200462 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463 bool shared_socket_;
464 // Information to use when going through a proxy.
465 std::string user_agent_;
466 rtc::ProxyInfo proxy_;
467
honghaize1a0c942016-02-16 14:54:56 -0800468 // A virtual cost perceived by the user, usually based on the network type
469 // (WiFi. vs. Cellular). It takes precedence over the priority when
470 // comparing two connections.
Kári Tristan Helgason47d3a012017-10-24 15:28:51 +0200471 int16_t network_cost_;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700472 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700473 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 14:54:56 -0800474
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475 friend class Connection;
476};
477
478// Represents a communication link between a port on the local client and a
479// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700480class Connection : public CandidatePairInterface,
481 public rtc::MessageHandler,
482 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000483 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700484 struct SentPing {
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700485 SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
486 : id(id), sent_time(sent_time), nomination(nomination) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700487
488 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700489 int64_t sent_time;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700490 uint32_t nomination;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700491 };
492
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700493 ~Connection() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494
495 // The local port where this connection sends and receives packets.
496 Port* port() { return port_; }
497 const Port* port() const { return port_; }
498
Honghai Zhangcc411c02016-03-29 17:27:21 -0700499 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000500 // Returns the description of the local port
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700501 const Candidate& local_candidate() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000502 // Returns the description of the remote port to which we communicate.
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700503 const Candidate& remote_candidate() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000504
505 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200506 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000507
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000508 enum WriteState {
509 STATE_WRITABLE = 0, // we have received ping responses recently
510 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
511 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
512 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
513 };
514
515 WriteState write_state() const { return write_state_; }
516 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700517 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000518
519 // Determines whether the connection has finished connecting. This can only
520 // be false for TCP connections.
521 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700522 bool weak() const { return !(writable() && receiving() && connected()); }
523 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700524 return write_state_ != STATE_WRITE_TIMEOUT;
525 }
honghaiz059e1832016-06-24 11:03:55 -0700526
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700527 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700528 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700529
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700531 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532
hbos06495bc2017-01-02 08:08:18 -0800533 // Gets the |ConnectionInfo| stats, where |best_connection| has not been
534 // populated (default value false).
zhihuang5ecf16c2016-06-01 17:09:15 -0700535 ConnectionInfo stats();
536
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000537 sigslot::signal1<Connection*> SignalStateChange;
538
539 // Sent when the connection has decided that it is no longer of value. It
540 // will delete itself immediately after this call.
541 sigslot::signal1<Connection*> SignalDestroyed;
542
543 // The connection can send and receive packets asynchronously. This matches
544 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
545 // covers.
546 virtual int Send(const void* data, size_t size,
547 const rtc::PacketOptions& options) = 0;
548
549 // Error if Send() returns < 0
550 virtual int GetError() = 0;
551
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700552 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
553 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554
555 sigslot::signal1<Connection*> SignalReadyToSend;
556
557 // Called when a packet is received on this connection.
558 void OnReadPacket(const char* data, size_t size,
559 const rtc::PacketTime& packet_time);
560
561 // Called when the socket is currently able to send.
562 void OnReadyToSend();
563
564 // Called when a connection is determined to be no longer useful to us. We
565 // still keep it around in case the other side wants to use it. But we can
566 // safely stop pinging on it and we can allow it to time out if the other
567 // side stops using it as well.
568 bool pruned() const { return pruned_; }
569 void Prune();
570
571 bool use_candidate_attr() const { return use_candidate_attr_; }
572 void set_use_candidate_attr(bool enable);
573
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700574 void set_nomination(uint32_t value) { nomination_ = value; }
575
576 uint32_t remote_nomination() const { return remote_nomination_; }
hbos92eaec62017-02-27 01:38:08 -0800577 // One or several pairs may be nominated based on if Regular or Aggressive
578 // Nomination is used. https://tools.ietf.org/html/rfc5245#section-8
579 // |nominated| is defined both for the controlling or controlled agent based
580 // on if a nomination has been pinged or acknowledged. The controlled agent
581 // gets its |remote_nomination_| set when pinged by the controlling agent with
582 // a nomination value. The controlling agent gets its |acked_nomination_| set
583 // when receiving a response to a nominating ping.
584 bool nominated() const { return acked_nomination_ || remote_nomination_; }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700585 // Public for unit tests.
586 void set_remote_nomination(uint32_t remote_nomination) {
587 remote_nomination_ = remote_nomination;
588 }
589 // Public for unit tests.
590 uint32_t acked_nomination() const { return acked_nomination_; }
honghaiz5a3acd82015-08-20 15:53:17 -0700591
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 void set_remote_ice_mode(IceMode mode) {
593 remote_ice_mode_ = mode;
594 }
595
bertholdherrmann0812030662016-10-18 14:00:02 -0700596 void set_receiving_timeout(int receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700597 receiving_timeout_ = receiving_timeout_ms;
598 }
599
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000600 // Makes the connection go away.
601 void Destroy();
602
deadbeef376e1232015-11-25 09:00:08 -0800603 // Makes the connection go away, in a failed state.
604 void FailAndDestroy();
605
honghaiz079a7a12016-06-22 16:26:29 -0700606 // Prunes the connection and sets its state to STATE_FAILED,
607 // It will not be used or send pings although it can still receive packets.
608 void FailAndPrune();
609
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000610 // Checks that the state of this connection is up-to-date. The argument is
611 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700612 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613
614 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700615 int64_t last_ping_sent() const { return last_ping_sent_; }
616 void Ping(int64_t now);
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700617 void ReceivedPingResponse(int rtt, const std::string& request_id);
honghaiz34b11eb2016-03-16 08:55:44 -0700618 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800619 return last_ping_response_received_;
620 }
Honghai Zhangfd16da22016-08-17 16:12:46 -0700621 // Used to check if any STUN ping response has been received.
622 int rtt_samples() const { return rtt_samples_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623
624 // Called whenever a valid ping is received on this connection. This is
625 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700626 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000627 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800628 // Handles the binding request; sends a response if this is a valid request.
629 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000630
Honghai Zhang572b0942016-06-23 12:26:57 -0700631 int64_t last_data_received() const { return last_data_received_; }
632
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000633 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000634 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 std::string ToString() const;
636 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700637 // Prints pings_since_last_response_ into a string.
638 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639
640 bool reported() const { return reported_; }
641 void set_reported(bool reported) { reported_ = reported;}
642
honghaiz5a3acd82015-08-20 15:53:17 -0700643 // This signal will be fired if this connection is nominated by the
644 // controlling side.
645 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700646
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000647 // Invoked when Connection receives STUN error response with 487 code.
648 void HandleRoleConflictFromPeer();
649
hbos06495bc2017-01-02 08:08:18 -0800650 IceCandidatePairState state() const { return state_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651
honghaiz524ecc22016-05-25 12:48:31 -0700652 int num_pings_sent() const { return num_pings_sent_; }
653
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000654 IceMode remote_ice_mode() const { return remote_ice_mode_; }
655
honghaize1a0c942016-02-16 14:54:56 -0800656 uint32_t ComputeNetworkCost() const;
657
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700658 // Update the ICE password and/or generation of the remote candidate if the
659 // ufrag in |params| matches the candidate's ufrag, and the
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700660 // candidate's password and/or ufrag has not been set.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700661 void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
662 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000663
664 // If |remote_candidate_| is peer reflexive and is equivalent to
665 // |new_candidate| except the type, update |remote_candidate_| to
666 // |new_candidate|.
667 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
668
Peter Thatcher54360512015-07-08 11:08:35 -0700669 // Returns the last received time of any data, stun request, or stun
670 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700671 int64_t last_received() const;
honghaiz9ad0db52016-07-14 19:30:28 -0700672 // Returns the last time when the connection changed its receiving state.
673 int64_t receiving_unchanged_since() const {
674 return receiving_unchanged_since_;
675 }
Peter Thatcher54360512015-07-08 11:08:35 -0700676
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700677 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700678
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000679 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700680 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
681
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000682 // Constructs a new connection to the given remote port.
683 Connection(Port* port, size_t index, const Candidate& candidate);
684
685 // Called back when StunRequestManager has a stun packet to send
686 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
687
688 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700689 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
690 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
692 StunMessage* response);
693 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700694 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700696 bool rtt_converged() const;
zhihuang435264a2016-06-21 11:28:38 -0700697
698 // If the response is not received within 2 * RTT, the response is assumed to
699 // be missing.
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700700 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700701
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000702 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000703 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-14 19:30:28 -0700704 void UpdateReceiving(int64_t now);
hbos06495bc2017-01-02 08:08:18 -0800705 void set_state(IceCandidatePairState state);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000706 void set_connected(bool value);
707
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700708 uint32_t nomination() const { return nomination_; }
709
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700710 void OnMessage(rtc::Message* pmsg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000711
712 Port* port_;
713 size_t local_candidate_index_;
714 Candidate remote_candidate_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700715
716 ConnectionInfo stats_;
717 rtc::RateTracker recv_rate_tracker_;
718 rtc::RateTracker send_rate_tracker_;
719
720 private:
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700721 // Update the local candidate based on the mapped address attribute.
722 // If the local candidate changed, fires SignalStateChange.
723 void MaybeUpdateLocalCandidate(ConnectionRequest* request,
724 StunMessage* response);
725
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000726 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700727 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000728 bool connected_;
729 bool pruned_;
730 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700731 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000732 // But when peer is ice-lite, this flag "must" be initialized to false and
733 // turn on when connection becomes "best connection".
734 bool use_candidate_attr_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700735 // Used by the controlling side to indicate that this connection will be
736 // selected for transmission if the peer supports ICE-renomination when this
737 // value is positive. A larger-value indicates that a connection is nominated
738 // later and should be selected by the controlled side with higher precedence.
739 // A zero-value indicates not nominating this connection.
740 uint32_t nomination_ = 0;
741 // The last nomination that has been acknowledged.
742 uint32_t acked_nomination_ = 0;
743 // Used by the controlled side to remember the nomination value received from
744 // the controlling side. When the peer does not support ICE re-nomination,
745 // its value will be 1 if the connection has been nominated.
746 uint32_t remote_nomination_ = 0;
747
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748 IceMode remote_ice_mode_;
749 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700750 int rtt_;
zhihuang435264a2016-06-21 11:28:38 -0700751 int rtt_samples_ = 0;
hbosbf8d3e52017-02-28 06:34:47 -0800752 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
753 uint64_t total_round_trip_time_ms_ = 0;
754 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
755 rtc::Optional<uint32_t> current_round_trip_time_ms_;
honghaiz34b11eb2016-03-16 08:55:44 -0700756 int64_t last_ping_sent_; // last time we sent a ping to the other side
757 int64_t last_ping_received_; // last time we received a ping from the other
758 // side
759 int64_t last_data_received_;
760 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-14 19:30:28 -0700761 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700762 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000763
zsteinabbacbf2017-03-20 10:53:12 -0700764 PacketLossEstimator packet_loss_estimator_;
765
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000766 bool reported_;
hbos06495bc2017-01-02 08:08:18 -0800767 IceCandidatePairState state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700768 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700769 int receiving_timeout_;
770 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 12:48:31 -0700771 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000772
773 friend class Port;
774 friend class ConnectionRequest;
775};
776
deadbeef376e1232015-11-25 09:00:08 -0800777// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000778class ProxyConnection : public Connection {
779 public:
deadbeef376e1232015-11-25 09:00:08 -0800780 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000781
deadbeef376e1232015-11-25 09:00:08 -0800782 int Send(const void* data,
783 size_t size,
784 const rtc::PacketOptions& options) override;
Steve Anton1cf1b7d2017-10-30 10:00:15 -0700785 int GetError() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000786
787 private:
deadbeef376e1232015-11-25 09:00:08 -0800788 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000789};
790
791} // namespace cricket
792
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200793#endif // P2P_BASE_PORT_H_