blob: 081e81af1d0c32db9a88510181745dd4ce18b673 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_P2P_BASE_PORT_H_
12#define WEBRTC_P2P_BASE_PORT_H_
13
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
20#include "webrtc/p2p/base/candidate.h"
Honghai Zhangcc411c02016-03-29 17:27:21 -070021#include "webrtc/p2p/base/candidatepairinterface.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000022#include "webrtc/p2p/base/packetsocketfactory.h"
23#include "webrtc/p2p/base/portinterface.h"
24#include "webrtc/p2p/base/stun.h"
25#include "webrtc/p2p/base/stunrequest.h"
26#include "webrtc/p2p/base/transport.h"
27#include "webrtc/base/asyncpacketsocket.h"
28#include "webrtc/base/network.h"
29#include "webrtc/base/proxyinfo.h"
30#include "webrtc/base/ratetracker.h"
31#include "webrtc/base/sigslot.h"
32#include "webrtc/base/socketaddress.h"
33#include "webrtc/base/thread.h"
34
35namespace cricket {
36
37class Connection;
38class ConnectionRequest;
39
40extern const char LOCAL_PORT_TYPE[];
41extern const char STUN_PORT_TYPE[];
42extern const char PRFLX_PORT_TYPE[];
43extern const char RELAY_PORT_TYPE[];
44
45extern const char UDP_PROTOCOL_NAME[];
46extern const char TCP_PROTOCOL_NAME[];
47extern const char SSLTCP_PROTOCOL_NAME[];
48
49// RFC 6544, TCP candidate encoding rules.
50extern const int DISCARD_PORT;
51extern const char TCPTYPE_ACTIVE_STR[];
52extern const char TCPTYPE_PASSIVE_STR[];
53extern const char TCPTYPE_SIMOPEN_STR[];
54
Honghai Zhang2b342bf2015-09-30 09:51:58 -070055// The minimum time we will wait before destroying a connection after creating
56// it.
honghaiz34b11eb2016-03-16 08:55:44 -070057static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070058
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080059// A connection will be declared dead if it has not received anything for this
60// long.
honghaiz34b11eb2016-03-16 08:55:44 -070061static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080062
Peter Thatcher04ac81f2015-09-21 11:48:28 -070063// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070064static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000065
66// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070067static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070070static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071
72// This is the length of time that we wait for a ping response to come back.
honghaiz34b11eb2016-03-16 08:55:44 -070073static const int CONNECTION_RESPONSE_TIMEOUT = 5 * 1000; // 5 seconds
74
75// The number of pings that must fail to respond before we become unwritable.
76static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000077
78enum RelayType {
79 RELAY_GTURN, // Legacy google relay service.
80 RELAY_TURN // Standard (TURN) relay service.
81};
82
83enum IcePriorityValue {
84 // The reason we are choosing Relay preference 2 is because, we can run
85 // Relay from client to server on UDP/TCP/TLS. To distinguish the transport
86 // protocol, we prefer UDP over TCP over TLS.
87 // For UDP ICE_TYPE_PREFERENCE_RELAY will be 2.
88 // For TCP ICE_TYPE_PREFERENCE_RELAY will be 1.
89 // For TLS ICE_TYPE_PREFERENCE_RELAY will be 0.
90 // Check turnport.cc for setting these values.
91 ICE_TYPE_PREFERENCE_RELAY = 2,
92 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
93 ICE_TYPE_PREFERENCE_SRFLX = 100,
94 ICE_TYPE_PREFERENCE_PRFLX = 110,
95 ICE_TYPE_PREFERENCE_HOST = 126
96};
97
98const char* ProtoToString(ProtocolType proto);
99bool StringToProto(const char* value, ProtocolType* proto);
100
101struct ProtocolAddress {
102 rtc::SocketAddress address;
103 ProtocolType proto;
104 bool secure;
105
106 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
107 : address(a), proto(p), secure(false) { }
108 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p, bool sec)
109 : address(a), proto(p), secure(sec) { }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700110
111 bool operator==(const ProtocolAddress& o) const {
112 return address == o.address && proto == o.proto && secure == o.secure;
113 }
114 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115};
116
117typedef std::set<rtc::SocketAddress> ServerAddresses;
118
119// Represents a local communication mechanism that can be used to create
120// connections to similar mechanisms of the other client. Subclasses of this
121// one add support for specific mechanisms like local UDP ports.
122class Port : public PortInterface, public rtc::MessageHandler,
123 public sigslot::has_slots<> {
124 public:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700125 // INIT: The state when a port is just created.
126 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
127 // connection is using it.
128 // PRUNED: It will be destroyed if no connection is using it for a period of
129 // 30 seconds.
130 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000131 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700132 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000133 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000134 rtc::Network* network,
135 const rtc::IPAddress& ip,
136 const std::string& username_fragment,
137 const std::string& password);
138 Port(rtc::Thread* thread,
139 const std::string& type,
140 rtc::PacketSocketFactory* factory,
141 rtc::Network* network,
142 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200143 uint16_t min_port,
144 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000145 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146 const std::string& password);
147 virtual ~Port();
148
149 virtual const std::string& Type() const { return type_; }
150 virtual rtc::Network* Network() const { return network_; }
151
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000152 // Methods to set/get ICE role and tiebreaker values.
153 IceRole GetIceRole() const { return ice_role_; }
154 void SetIceRole(IceRole role) { ice_role_ = role; }
155
Peter Boström0c4e06b2015-10-07 12:23:21 +0200156 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
157 uint64_t IceTiebreaker() const { return tiebreaker_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000158
159 virtual bool SharedSocket() const { return shared_socket_; }
160 void ResetSharedSocket() { shared_socket_ = false; }
161
Honghai Zhanga74363c2016-07-28 18:06:15 -0700162 // Should not destroy the port even if no connection is using it. Called when
163 // a port is ready to use.
164 void KeepAliveUntilPruned();
165 // Allows a port to be destroyed if no connection is using it.
166 void Prune();
167
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168 // The thread on which this port performs its I/O.
169 rtc::Thread* thread() { return thread_; }
170
171 // The factory used to create the sockets of this port.
172 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
173 void set_socket_factory(rtc::PacketSocketFactory* factory) {
174 factory_ = factory;
175 }
176
177 // For debugging purposes.
178 const std::string& content_name() const { return content_name_; }
179 void set_content_name(const std::string& content_name) {
180 content_name_ = content_name;
181 }
182
183 int component() const { return component_; }
184 void set_component(int component) { component_ = component; }
185
186 bool send_retransmit_count_attribute() const {
187 return send_retransmit_count_attribute_;
188 }
189 void set_send_retransmit_count_attribute(bool enable) {
190 send_retransmit_count_attribute_ = enable;
191 }
192
193 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-22 17:14:15 -0700194 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200195 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000196
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000197 const std::string username_fragment() const;
198 const std::string& password() const { return password_; }
199
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700200 // May be called when this port was initially created by a pooled
201 // PortAllocatorSession, and is now being assigned to an ICE transport.
202 // Updates the information for candidates as well.
203 void SetIceParameters(int component,
204 const std::string& username_fragment,
205 const std::string& password);
206
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207 // Fired when candidates are discovered by the port. When all candidates
208 // are discovered that belong to port SignalAddressReady is fired.
209 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
210
211 // Provides all of the above information in one handy object.
212 virtual const std::vector<Candidate>& Candidates() const {
213 return candidates_;
214 }
215
216 // SignalPortComplete is sent when port completes the task of candidates
217 // allocation.
218 sigslot::signal1<Port*> SignalPortComplete;
219 // This signal sent when port fails to allocate candidates and this port
220 // can't be used in establishing the connections. When port is in shared mode
221 // and port fails to allocate one of the candidates, port shouldn't send
222 // this signal as other candidates might be usefull in establishing the
223 // connection.
224 sigslot::signal1<Port*> SignalPortError;
225
226 // Returns a map containing all of the connections of this port, keyed by the
227 // remote address.
228 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
229 const AddressMap& connections() { return connections_; }
230
231 // Returns the connection to the given address or NULL if none exists.
232 virtual Connection* GetConnection(
233 const rtc::SocketAddress& remote_addr);
234
235 // Called each time a connection is created.
236 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
237
238 // In a shared socket mode each port which shares the socket will decide
239 // to accept the packet based on the |remote_addr|. Currently only UDP
240 // port implemented this method.
241 // TODO(mallinath) - Make it pure virtual.
242 virtual bool HandleIncomingPacket(
243 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
244 const rtc::SocketAddress& remote_addr,
245 const rtc::PacketTime& packet_time) {
246 ASSERT(false);
247 return false;
248 }
249
250 // Sends a response message (normal or error) to the given request. One of
251 // these methods should be called as a response to SignalUnknownAddress.
252 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
253 virtual void SendBindingResponse(StunMessage* request,
254 const rtc::SocketAddress& addr);
255 virtual void SendBindingErrorResponse(
256 StunMessage* request, const rtc::SocketAddress& addr,
257 int error_code, const std::string& reason);
258
259 void set_proxy(const std::string& user_agent,
260 const rtc::ProxyInfo& proxy) {
261 user_agent_ = user_agent;
262 proxy_ = proxy;
263 }
264 const std::string& user_agent() { return user_agent_; }
265 const rtc::ProxyInfo& proxy() { return proxy_; }
266
267 virtual void EnablePortPackets();
268
269 // Called if the port has no connections and is no longer useful.
270 void Destroy();
271
272 virtual void OnMessage(rtc::Message *pmsg);
273
274 // Debugging description of this port
275 virtual std::string ToString() const;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000276 const rtc::IPAddress& ip() const { return ip_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200277 uint16_t min_port() { return min_port_; }
278 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000279
280 // Timeout shortening function to speed up unit tests.
281 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
282
283 // This method will return local and remote username fragements from the
284 // stun username attribute if present.
285 bool ParseStunUsername(const StunMessage* stun_msg,
286 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700287 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288 void CreateStunUsername(const std::string& remote_username,
289 std::string* stun_username_attr_str) const;
290
291 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
292 IceMessage* stun_msg,
293 const std::string& remote_ufrag);
294
stefanc1aeaf02015-10-15 07:26:07 -0700295 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100296 // This is made pure virtual to notify subclasses of Port that they MUST
297 // listen to AsyncPacketSocket::SignalSentPacket and then call
298 // PortInterface::OnSentPacket.
299 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
300 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700301
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302 // Called when the socket is currently able to send.
303 void OnReadyToSend();
304
305 // Called when the Connection discovers a local peer reflexive candidate.
306 // Returns the index of the new local candidate.
307 size_t AddPrflxCandidate(const Candidate& local);
308
honghaiza0c44ea2016-03-23 16:07:48 -0700309 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310
311 protected:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700312 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000313
Honghai Zhang351d77b2016-05-20 15:08:29 -0700314 virtual void UpdateNetworkCost();
315
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000316 void set_type(const std::string& type) { type_ = type; }
317
318 void AddAddress(const rtc::SocketAddress& address,
319 const rtc::SocketAddress& base_address,
320 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700321 const std::string& protocol,
322 const std::string& relay_protocol,
323 const std::string& tcptype,
324 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200325 uint32_t type_preference,
326 uint32_t relay_preference,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700327 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000328
honghaiz36f50e82016-06-01 15:57:03 -0700329 // Adds the given connection to the map keyed by the remote candidate address.
330 // If an existing connection has the same address, the existing one will be
331 // replaced and destroyed.
332 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000333
334 // Called when a packet is received from an unknown address that is not
335 // currently a connection. If this is an authenticated STUN binding request,
336 // then we will signal the client.
337 void OnReadPacket(const char* data, size_t size,
338 const rtc::SocketAddress& addr,
339 ProtocolType proto);
340
341 // If the given data comprises a complete and correct STUN message then the
342 // return value is true, otherwise false. If the message username corresponds
343 // with this port's username fragment, msg will contain the parsed STUN
344 // message. Otherwise, the function may send a STUN response internally.
345 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700346 bool GetStunMessage(const char* data,
347 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000348 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700349 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700350 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351
352 // Checks if the address in addr is compatible with the port's ip.
353 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
354
355 // Returns default DSCP value.
356 rtc::DiffServCodePoint DefaultDscpValue() const {
357 // No change from what MediaChannel set.
358 return rtc::DSCP_NO_CHANGE;
359 }
360
honghaiz36f50e82016-06-01 15:57:03 -0700361 // Extra work to be done in subclasses when a connection is destroyed.
362 virtual void HandleConnectionDestroyed(Connection* conn) {}
363
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364 private:
365 void Construct();
366 // Called when one of our connections deletes itself.
367 void OnConnectionDestroyed(Connection* conn);
368
Honghai Zhang351d77b2016-05-20 15:08:29 -0700369 void OnNetworkTypeChanged(const rtc::Network* network);
370
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000371 rtc::Thread* thread_;
372 rtc::PacketSocketFactory* factory_;
373 std::string type_;
374 bool send_retransmit_count_attribute_;
375 rtc::Network* network_;
376 rtc::IPAddress ip_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200377 uint16_t min_port_;
378 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000379 std::string content_name_;
380 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200381 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000382 // In order to establish a connection to this Port (so that real data can be
383 // sent through), the other side must send us a STUN binding request that is
384 // authenticated with this username_fragment and password.
385 // PortAllocatorSession will provide these username_fragment and password.
386 //
387 // Note: we should always use username_fragment() instead of using
388 // |ice_username_fragment_| directly. For the details see the comment on
389 // username_fragment().
390 std::string ice_username_fragment_;
391 std::string password_;
392 std::vector<Candidate> candidates_;
393 AddressMap connections_;
394 int timeout_delay_;
395 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000396 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200397 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000398 bool shared_socket_;
399 // Information to use when going through a proxy.
400 std::string user_agent_;
401 rtc::ProxyInfo proxy_;
402
honghaize1a0c942016-02-16 14:54:56 -0800403 // A virtual cost perceived by the user, usually based on the network type
404 // (WiFi. vs. Cellular). It takes precedence over the priority when
405 // comparing two connections.
honghaiza0c44ea2016-03-23 16:07:48 -0700406 uint16_t network_cost_;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700407 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700408 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 14:54:56 -0800409
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 friend class Connection;
411};
412
413// Represents a communication link between a port on the local client and a
414// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700415class Connection : public CandidatePairInterface,
416 public rtc::MessageHandler,
417 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700419 struct SentPing {
honghaiz34b11eb2016-03-16 08:55:44 -0700420 SentPing(const std::string id, int64_t sent_time)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200421 : id(id), sent_time(sent_time) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700422
423 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700424 int64_t sent_time;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700425 };
426
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000427 // States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
428 enum State {
429 STATE_WAITING = 0, // Check has not been performed, Waiting pair on CL.
430 STATE_INPROGRESS, // Check has been sent, transaction is in progress.
431 STATE_SUCCEEDED, // Check already done, produced a successful result.
432 STATE_FAILED // Check for this connection failed.
433 };
434
435 virtual ~Connection();
436
437 // The local port where this connection sends and receives packets.
438 Port* port() { return port_; }
439 const Port* port() const { return port_; }
440
Honghai Zhangcc411c02016-03-29 17:27:21 -0700441 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 // Returns the description of the local port
443 virtual const Candidate& local_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 // Returns the description of the remote port to which we communicate.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700445 virtual const Candidate& remote_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446
447 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200448 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 enum WriteState {
451 STATE_WRITABLE = 0, // we have received ping responses recently
452 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
453 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
454 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
455 };
456
457 WriteState write_state() const { return write_state_; }
458 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700459 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460
461 // Determines whether the connection has finished connecting. This can only
462 // be false for TCP connections.
463 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700464 bool weak() const { return !(writable() && receiving() && connected()); }
465 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700466 return write_state_ != STATE_WRITE_TIMEOUT;
467 }
honghaiz059e1832016-06-24 11:03:55 -0700468
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700469 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700470 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700471
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000472 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700473 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000474
zhihuang5ecf16c2016-06-01 17:09:15 -0700475 ConnectionInfo stats();
476
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477 sigslot::signal1<Connection*> SignalStateChange;
478
479 // Sent when the connection has decided that it is no longer of value. It
480 // will delete itself immediately after this call.
481 sigslot::signal1<Connection*> SignalDestroyed;
482
483 // The connection can send and receive packets asynchronously. This matches
484 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
485 // covers.
486 virtual int Send(const void* data, size_t size,
487 const rtc::PacketOptions& options) = 0;
488
489 // Error if Send() returns < 0
490 virtual int GetError() = 0;
491
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700492 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
493 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494
495 sigslot::signal1<Connection*> SignalReadyToSend;
496
497 // Called when a packet is received on this connection.
498 void OnReadPacket(const char* data, size_t size,
499 const rtc::PacketTime& packet_time);
500
501 // Called when the socket is currently able to send.
502 void OnReadyToSend();
503
504 // Called when a connection is determined to be no longer useful to us. We
505 // still keep it around in case the other side wants to use it. But we can
506 // safely stop pinging on it and we can allow it to time out if the other
507 // side stops using it as well.
508 bool pruned() const { return pruned_; }
509 void Prune();
510
511 bool use_candidate_attr() const { return use_candidate_attr_; }
512 void set_use_candidate_attr(bool enable);
513
honghaiz5a3acd82015-08-20 15:53:17 -0700514 bool nominated() const { return nominated_; }
515 void set_nominated(bool nominated) { nominated_ = nominated; }
516
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000517 void set_remote_ice_mode(IceMode mode) {
518 remote_ice_mode_ = mode;
519 }
520
honghaiz34b11eb2016-03-16 08:55:44 -0700521 void set_receiving_timeout(int64_t receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700522 receiving_timeout_ = receiving_timeout_ms;
523 }
524
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000525 // Makes the connection go away.
526 void Destroy();
527
deadbeef376e1232015-11-25 09:00:08 -0800528 // Makes the connection go away, in a failed state.
529 void FailAndDestroy();
530
honghaiz079a7a12016-06-22 16:26:29 -0700531 // Prunes the connection and sets its state to STATE_FAILED,
532 // It will not be used or send pings although it can still receive packets.
533 void FailAndPrune();
534
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000535 // Checks that the state of this connection is up-to-date. The argument is
536 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700537 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000538
539 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700540 int64_t last_ping_sent() const { return last_ping_sent_; }
541 void Ping(int64_t now);
zhihuang435264a2016-06-21 11:28:38 -0700542 void ReceivedPingResponse(int rtt);
honghaiz34b11eb2016-03-16 08:55:44 -0700543 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800544 return last_ping_response_received_;
545 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000546
547 // Called whenever a valid ping is received on this connection. This is
548 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700549 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000550 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800551 // Handles the binding request; sends a response if this is a valid request.
552 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000553
Honghai Zhang572b0942016-06-23 12:26:57 -0700554 int64_t last_data_received() const { return last_data_received_; }
555
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000556 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000557 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000558 std::string ToString() const;
559 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700560 // Prints pings_since_last_response_ into a string.
561 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000562
563 bool reported() const { return reported_; }
564 void set_reported(bool reported) { reported_ = reported;}
565
honghaiz5a3acd82015-08-20 15:53:17 -0700566 // This signal will be fired if this connection is nominated by the
567 // controlling side.
568 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700569
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000570 // Invoked when Connection receives STUN error response with 487 code.
571 void HandleRoleConflictFromPeer();
572
573 State state() const { return state_; }
574
honghaiz524ecc22016-05-25 12:48:31 -0700575 int num_pings_sent() const { return num_pings_sent_; }
576
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000577 IceMode remote_ice_mode() const { return remote_ice_mode_; }
578
honghaize1a0c942016-02-16 14:54:56 -0800579 uint32_t ComputeNetworkCost() const;
580
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700581 // Update the ICE password and/or generation of the remote candidate if a
582 // ufrag in |remote_ice_parameters| matches the candidate's ufrag, and the
583 // candidate's password and/or ufrag has not been set.
584 // |remote_ice_parameters| should be a list of known ICE parameters ordered
585 // by generation.
586 void MaybeSetRemoteIceCredentialsAndGeneration(const std::string& ice_ufrag,
587 const std::string& ice_pwd,
588 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000589
590 // If |remote_candidate_| is peer reflexive and is equivalent to
591 // |new_candidate| except the type, update |remote_candidate_| to
592 // |new_candidate|.
593 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
594
Peter Thatcher54360512015-07-08 11:08:35 -0700595 // Returns the last received time of any data, stun request, or stun
596 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700597 int64_t last_received() const;
honghaiz9ad0db52016-07-14 19:30:28 -0700598 // Returns the last time when the connection changed its receiving state.
599 int64_t receiving_unchanged_since() const {
600 return receiving_unchanged_since_;
601 }
Peter Thatcher54360512015-07-08 11:08:35 -0700602
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700603 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700604
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000605 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700606 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
607
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608 // Constructs a new connection to the given remote port.
609 Connection(Port* port, size_t index, const Candidate& candidate);
610
611 // Called back when StunRequestManager has a stun packet to send
612 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
613
614 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700615 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
616 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000617 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
618 StunMessage* response);
619 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700620 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000621
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700622 bool rtt_converged() const;
zhihuang435264a2016-06-21 11:28:38 -0700623
624 // If the response is not received within 2 * RTT, the response is assumed to
625 // be missing.
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700626 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700627
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000628 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000629 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-14 19:30:28 -0700630 void UpdateReceiving(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000631 void set_state(State state);
632 void set_connected(bool value);
633
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 void OnMessage(rtc::Message *pmsg);
635
636 Port* port_;
637 size_t local_candidate_index_;
638 Candidate remote_candidate_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700640 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 bool connected_;
642 bool pruned_;
643 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700644 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645 // But when peer is ice-lite, this flag "must" be initialized to false and
646 // turn on when connection becomes "best connection".
647 bool use_candidate_attr_;
honghaiz5a3acd82015-08-20 15:53:17 -0700648 // Whether this connection has been nominated by the controlling side via
649 // the use_candidate attribute.
650 bool nominated_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000651 IceMode remote_ice_mode_;
652 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700653 int rtt_;
zhihuang435264a2016-06-21 11:28:38 -0700654 int rtt_samples_ = 0;
honghaiz34b11eb2016-03-16 08:55:44 -0700655 int64_t last_ping_sent_; // last time we sent a ping to the other side
656 int64_t last_ping_received_; // last time we received a ping from the other
657 // side
658 int64_t last_data_received_;
659 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-14 19:30:28 -0700660 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700661 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662
663 rtc::RateTracker recv_rate_tracker_;
664 rtc::RateTracker send_rate_tracker_;
zhihuang5ecf16c2016-06-01 17:09:15 -0700665
666 ConnectionInfo stats_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000667
668 private:
669 void MaybeAddPrflxCandidate(ConnectionRequest* request,
670 StunMessage* response);
671
672 bool reported_;
673 State state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700674 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700675 int receiving_timeout_;
676 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 12:48:31 -0700677 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000678
679 friend class Port;
680 friend class ConnectionRequest;
681};
682
deadbeef376e1232015-11-25 09:00:08 -0800683// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684class ProxyConnection : public Connection {
685 public:
deadbeef376e1232015-11-25 09:00:08 -0800686 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000687
deadbeef376e1232015-11-25 09:00:08 -0800688 int Send(const void* data,
689 size_t size,
690 const rtc::PacketOptions& options) override;
691 int GetError() override { return error_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000692
693 private:
deadbeef376e1232015-11-25 09:00:08 -0800694 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000695};
696
697} // namespace cricket
698
699#endif // WEBRTC_P2P_BASE_PORT_H_