blob: f3c4ed167c1df061df00777a0bb1009c4cf343df [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"
deadbeef49f34fd2016-12-06 16:22:06 -080022#include "webrtc/p2p/base/jseptransport.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000023#include "webrtc/p2p/base/packetsocketfactory.h"
24#include "webrtc/p2p/base/portinterface.h"
25#include "webrtc/p2p/base/stun.h"
26#include "webrtc/p2p/base/stunrequest.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000027#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[];
hnslb68cc752016-12-13 10:33:41 -080048extern const char TLS_PROTOCOL_NAME[];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000049
50// RFC 6544, TCP candidate encoding rules.
51extern const int DISCARD_PORT;
52extern const char TCPTYPE_ACTIVE_STR[];
53extern const char TCPTYPE_PASSIVE_STR[];
54extern const char TCPTYPE_SIMOPEN_STR[];
55
Honghai Zhang2b342bf2015-09-30 09:51:58 -070056// The minimum time we will wait before destroying a connection after creating
57// it.
honghaiz34b11eb2016-03-16 08:55:44 -070058static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070059
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080060// A connection will be declared dead if it has not received anything for this
61// long.
honghaiz34b11eb2016-03-16 08:55:44 -070062static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080063
Peter Thatcher04ac81f2015-09-21 11:48:28 -070064// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070065static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000066
67// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070068static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000069
70// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070071static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072
73// This is the length of time that we wait for a ping response to come back.
honghaiz34b11eb2016-03-16 08:55:44 -070074static const int CONNECTION_RESPONSE_TIMEOUT = 5 * 1000; // 5 seconds
75
76// The number of pings that must fail to respond before we become unwritable.
77static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000078
79enum RelayType {
80 RELAY_GTURN, // Legacy google relay service.
81 RELAY_TURN // Standard (TURN) relay service.
82};
83
84enum IcePriorityValue {
hnsl277b2502016-12-13 05:17:23 -080085 ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
86 ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
87 ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
Taylor Brandstetter62351c92016-08-11 16:05:07 -070088 ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000089 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
90 ICE_TYPE_PREFERENCE_SRFLX = 100,
91 ICE_TYPE_PREFERENCE_PRFLX = 110,
92 ICE_TYPE_PREFERENCE_HOST = 126
93};
94
hbos06495bc2017-01-02 08:08:18 -080095// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
96enum class IceCandidatePairState {
97 WAITING = 0, // Check has not been performed, Waiting pair on CL.
98 IN_PROGRESS, // Check has been sent, transaction is in progress.
99 SUCCEEDED, // Check already done, produced a successful result.
100 FAILED, // Check for this connection failed.
101 // According to spec there should also be a frozen state, but nothing is ever
102 // frozen because we have not implemented ICE freezing logic.
103};
104
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000105const char* ProtoToString(ProtocolType proto);
106bool StringToProto(const char* value, ProtocolType* proto);
107
108struct ProtocolAddress {
109 rtc::SocketAddress address;
110 ProtocolType proto;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000111
112 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
hnsl277b2502016-12-13 05:17:23 -0800113 : address(a), proto(p) {}
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700114
115 bool operator==(const ProtocolAddress& o) const {
hnsl277b2502016-12-13 05:17:23 -0800116 return address == o.address && proto == o.proto;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700117 }
118 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000119};
120
121typedef std::set<rtc::SocketAddress> ServerAddresses;
122
123// Represents a local communication mechanism that can be used to create
124// connections to similar mechanisms of the other client. Subclasses of this
125// one add support for specific mechanisms like local UDP ports.
126class Port : public PortInterface, public rtc::MessageHandler,
127 public sigslot::has_slots<> {
128 public:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700129 // INIT: The state when a port is just created.
130 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
131 // connection is using it.
132 // PRUNED: It will be destroyed if no connection is using it for a period of
133 // 30 seconds.
134 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000135 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700136 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000137 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000138 rtc::Network* network,
139 const rtc::IPAddress& ip,
140 const std::string& username_fragment,
141 const std::string& password);
142 Port(rtc::Thread* thread,
143 const std::string& type,
144 rtc::PacketSocketFactory* factory,
145 rtc::Network* network,
146 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200147 uint16_t min_port,
148 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000149 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000150 const std::string& password);
151 virtual ~Port();
152
153 virtual const std::string& Type() const { return type_; }
154 virtual rtc::Network* Network() const { return network_; }
155
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 // Methods to set/get ICE role and tiebreaker values.
157 IceRole GetIceRole() const { return ice_role_; }
158 void SetIceRole(IceRole role) { ice_role_ = role; }
159
Peter Boström0c4e06b2015-10-07 12:23:21 +0200160 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
161 uint64_t IceTiebreaker() const { return tiebreaker_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162
163 virtual bool SharedSocket() const { return shared_socket_; }
164 void ResetSharedSocket() { shared_socket_ = false; }
165
Honghai Zhanga74363c2016-07-28 18:06:15 -0700166 // Should not destroy the port even if no connection is using it. Called when
167 // a port is ready to use.
168 void KeepAliveUntilPruned();
169 // Allows a port to be destroyed if no connection is using it.
170 void Prune();
171
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000172 // The thread on which this port performs its I/O.
173 rtc::Thread* thread() { return thread_; }
174
175 // The factory used to create the sockets of this port.
176 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
177 void set_socket_factory(rtc::PacketSocketFactory* factory) {
178 factory_ = factory;
179 }
180
181 // For debugging purposes.
182 const std::string& content_name() const { return content_name_; }
183 void set_content_name(const std::string& content_name) {
184 content_name_ = content_name;
185 }
186
187 int component() const { return component_; }
188 void set_component(int component) { component_ = component; }
189
190 bool send_retransmit_count_attribute() const {
191 return send_retransmit_count_attribute_;
192 }
193 void set_send_retransmit_count_attribute(bool enable) {
194 send_retransmit_count_attribute_ = enable;
195 }
196
197 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-22 17:14:15 -0700198 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200199 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000200
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000201 const std::string username_fragment() const;
202 const std::string& password() const { return password_; }
203
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700204 // May be called when this port was initially created by a pooled
205 // PortAllocatorSession, and is now being assigned to an ICE transport.
206 // Updates the information for candidates as well.
207 void SetIceParameters(int component,
208 const std::string& username_fragment,
209 const std::string& password);
210
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000211 // Fired when candidates are discovered by the port. When all candidates
212 // are discovered that belong to port SignalAddressReady is fired.
213 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
214
215 // Provides all of the above information in one handy object.
216 virtual const std::vector<Candidate>& Candidates() const {
217 return candidates_;
218 }
219
220 // SignalPortComplete is sent when port completes the task of candidates
221 // allocation.
222 sigslot::signal1<Port*> SignalPortComplete;
223 // This signal sent when port fails to allocate candidates and this port
224 // can't be used in establishing the connections. When port is in shared mode
225 // and port fails to allocate one of the candidates, port shouldn't send
226 // this signal as other candidates might be usefull in establishing the
227 // connection.
228 sigslot::signal1<Port*> SignalPortError;
229
230 // Returns a map containing all of the connections of this port, keyed by the
231 // remote address.
232 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
233 const AddressMap& connections() { return connections_; }
234
235 // Returns the connection to the given address or NULL if none exists.
236 virtual Connection* GetConnection(
237 const rtc::SocketAddress& remote_addr);
238
239 // Called each time a connection is created.
240 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
241
242 // In a shared socket mode each port which shares the socket will decide
243 // to accept the packet based on the |remote_addr|. Currently only UDP
244 // port implemented this method.
245 // TODO(mallinath) - Make it pure virtual.
246 virtual bool HandleIncomingPacket(
247 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
248 const rtc::SocketAddress& remote_addr,
249 const rtc::PacketTime& packet_time) {
250 ASSERT(false);
251 return false;
252 }
253
254 // Sends a response message (normal or error) to the given request. One of
255 // these methods should be called as a response to SignalUnknownAddress.
256 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
257 virtual void SendBindingResponse(StunMessage* request,
258 const rtc::SocketAddress& addr);
259 virtual void SendBindingErrorResponse(
260 StunMessage* request, const rtc::SocketAddress& addr,
261 int error_code, const std::string& reason);
262
263 void set_proxy(const std::string& user_agent,
264 const rtc::ProxyInfo& proxy) {
265 user_agent_ = user_agent;
266 proxy_ = proxy;
267 }
268 const std::string& user_agent() { return user_agent_; }
269 const rtc::ProxyInfo& proxy() { return proxy_; }
270
271 virtual void EnablePortPackets();
272
273 // Called if the port has no connections and is no longer useful.
274 void Destroy();
275
276 virtual void OnMessage(rtc::Message *pmsg);
277
278 // Debugging description of this port
279 virtual std::string ToString() const;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000280 const rtc::IPAddress& ip() const { return ip_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200281 uint16_t min_port() { return min_port_; }
282 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000283
284 // Timeout shortening function to speed up unit tests.
285 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
286
287 // This method will return local and remote username fragements from the
288 // stun username attribute if present.
289 bool ParseStunUsername(const StunMessage* stun_msg,
290 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700291 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000292 void CreateStunUsername(const std::string& remote_username,
293 std::string* stun_username_attr_str) const;
294
295 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
296 IceMessage* stun_msg,
297 const std::string& remote_ufrag);
298
stefanc1aeaf02015-10-15 07:26:07 -0700299 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100300 // This is made pure virtual to notify subclasses of Port that they MUST
301 // listen to AsyncPacketSocket::SignalSentPacket and then call
302 // PortInterface::OnSentPacket.
303 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
304 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700305
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000306 // Called when the socket is currently able to send.
307 void OnReadyToSend();
308
309 // Called when the Connection discovers a local peer reflexive candidate.
310 // Returns the index of the new local candidate.
311 size_t AddPrflxCandidate(const Candidate& local);
312
honghaiza0c44ea2016-03-23 16:07:48 -0700313 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000314
315 protected:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700316 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000317
Honghai Zhang351d77b2016-05-20 15:08:29 -0700318 virtual void UpdateNetworkCost();
319
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000320 void set_type(const std::string& type) { type_ = type; }
321
322 void AddAddress(const rtc::SocketAddress& address,
323 const rtc::SocketAddress& base_address,
324 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700325 const std::string& protocol,
326 const std::string& relay_protocol,
327 const std::string& tcptype,
328 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200329 uint32_t type_preference,
330 uint32_t relay_preference,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700331 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000332
honghaiz36f50e82016-06-01 15:57:03 -0700333 // Adds the given connection to the map keyed by the remote candidate address.
334 // If an existing connection has the same address, the existing one will be
335 // replaced and destroyed.
336 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000337
338 // Called when a packet is received from an unknown address that is not
339 // currently a connection. If this is an authenticated STUN binding request,
340 // then we will signal the client.
341 void OnReadPacket(const char* data, size_t size,
342 const rtc::SocketAddress& addr,
343 ProtocolType proto);
344
345 // If the given data comprises a complete and correct STUN message then the
346 // return value is true, otherwise false. If the message username corresponds
347 // with this port's username fragment, msg will contain the parsed STUN
348 // message. Otherwise, the function may send a STUN response internally.
349 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700350 bool GetStunMessage(const char* data,
351 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700353 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700354 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355
356 // Checks if the address in addr is compatible with the port's ip.
357 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
358
359 // Returns default DSCP value.
360 rtc::DiffServCodePoint DefaultDscpValue() const {
361 // No change from what MediaChannel set.
362 return rtc::DSCP_NO_CHANGE;
363 }
364
honghaiz36f50e82016-06-01 15:57:03 -0700365 // Extra work to be done in subclasses when a connection is destroyed.
366 virtual void HandleConnectionDestroyed(Connection* conn) {}
367
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000368 private:
369 void Construct();
370 // Called when one of our connections deletes itself.
371 void OnConnectionDestroyed(Connection* conn);
372
Honghai Zhang351d77b2016-05-20 15:08:29 -0700373 void OnNetworkTypeChanged(const rtc::Network* network);
374
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000375 rtc::Thread* thread_;
376 rtc::PacketSocketFactory* factory_;
377 std::string type_;
378 bool send_retransmit_count_attribute_;
379 rtc::Network* network_;
380 rtc::IPAddress ip_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200381 uint16_t min_port_;
382 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000383 std::string content_name_;
384 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200385 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000386 // In order to establish a connection to this Port (so that real data can be
387 // sent through), the other side must send us a STUN binding request that is
388 // authenticated with this username_fragment and password.
389 // PortAllocatorSession will provide these username_fragment and password.
390 //
391 // Note: we should always use username_fragment() instead of using
392 // |ice_username_fragment_| directly. For the details see the comment on
393 // username_fragment().
394 std::string ice_username_fragment_;
395 std::string password_;
396 std::vector<Candidate> candidates_;
397 AddressMap connections_;
398 int timeout_delay_;
399 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000400 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200401 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 bool shared_socket_;
403 // Information to use when going through a proxy.
404 std::string user_agent_;
405 rtc::ProxyInfo proxy_;
406
honghaize1a0c942016-02-16 14:54:56 -0800407 // A virtual cost perceived by the user, usually based on the network type
408 // (WiFi. vs. Cellular). It takes precedence over the priority when
409 // comparing two connections.
honghaiza0c44ea2016-03-23 16:07:48 -0700410 uint16_t network_cost_;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700411 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700412 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 14:54:56 -0800413
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000414 friend class Connection;
415};
416
417// Represents a communication link between a port on the local client and a
418// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700419class Connection : public CandidatePairInterface,
420 public rtc::MessageHandler,
421 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700423 struct SentPing {
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700424 SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
425 : id(id), sent_time(sent_time), nomination(nomination) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700426
427 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700428 int64_t sent_time;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700429 uint32_t nomination;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700430 };
431
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000432 virtual ~Connection();
433
434 // The local port where this connection sends and receives packets.
435 Port* port() { return port_; }
436 const Port* port() const { return port_; }
437
Honghai Zhangcc411c02016-03-29 17:27:21 -0700438 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000439 // Returns the description of the local port
440 virtual const Candidate& local_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000441 // Returns the description of the remote port to which we communicate.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700442 virtual const Candidate& remote_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000443
444 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200445 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000447 enum WriteState {
448 STATE_WRITABLE = 0, // we have received ping responses recently
449 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
450 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
451 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
452 };
453
454 WriteState write_state() const { return write_state_; }
455 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700456 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457
458 // Determines whether the connection has finished connecting. This can only
459 // be false for TCP connections.
460 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700461 bool weak() const { return !(writable() && receiving() && connected()); }
462 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700463 return write_state_ != STATE_WRITE_TIMEOUT;
464 }
honghaiz059e1832016-06-24 11:03:55 -0700465
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700466 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700467 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700468
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000469 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700470 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471
hbos06495bc2017-01-02 08:08:18 -0800472 // Gets the |ConnectionInfo| stats, where |best_connection| has not been
473 // populated (default value false).
zhihuang5ecf16c2016-06-01 17:09:15 -0700474 ConnectionInfo stats();
475
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476 sigslot::signal1<Connection*> SignalStateChange;
477
478 // Sent when the connection has decided that it is no longer of value. It
479 // will delete itself immediately after this call.
480 sigslot::signal1<Connection*> SignalDestroyed;
481
482 // The connection can send and receive packets asynchronously. This matches
483 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
484 // covers.
485 virtual int Send(const void* data, size_t size,
486 const rtc::PacketOptions& options) = 0;
487
488 // Error if Send() returns < 0
489 virtual int GetError() = 0;
490
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700491 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
492 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000493
494 sigslot::signal1<Connection*> SignalReadyToSend;
495
496 // Called when a packet is received on this connection.
497 void OnReadPacket(const char* data, size_t size,
498 const rtc::PacketTime& packet_time);
499
500 // Called when the socket is currently able to send.
501 void OnReadyToSend();
502
503 // Called when a connection is determined to be no longer useful to us. We
504 // still keep it around in case the other side wants to use it. But we can
505 // safely stop pinging on it and we can allow it to time out if the other
506 // side stops using it as well.
507 bool pruned() const { return pruned_; }
508 void Prune();
509
510 bool use_candidate_attr() const { return use_candidate_attr_; }
511 void set_use_candidate_attr(bool enable);
512
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700513 void set_nomination(uint32_t value) { nomination_ = value; }
514
515 uint32_t remote_nomination() const { return remote_nomination_; }
516 bool nominated() const { return remote_nomination_ > 0; }
517 // Public for unit tests.
518 void set_remote_nomination(uint32_t remote_nomination) {
519 remote_nomination_ = remote_nomination;
520 }
521 // Public for unit tests.
522 uint32_t acked_nomination() const { return acked_nomination_; }
honghaiz5a3acd82015-08-20 15:53:17 -0700523
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000524 void set_remote_ice_mode(IceMode mode) {
525 remote_ice_mode_ = mode;
526 }
527
bertholdherrmann0812030662016-10-18 14:00:02 -0700528 void set_receiving_timeout(int receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700529 receiving_timeout_ = receiving_timeout_ms;
530 }
531
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000532 // Makes the connection go away.
533 void Destroy();
534
deadbeef376e1232015-11-25 09:00:08 -0800535 // Makes the connection go away, in a failed state.
536 void FailAndDestroy();
537
honghaiz079a7a12016-06-22 16:26:29 -0700538 // Prunes the connection and sets its state to STATE_FAILED,
539 // It will not be used or send pings although it can still receive packets.
540 void FailAndPrune();
541
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000542 // Checks that the state of this connection is up-to-date. The argument is
543 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700544 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000545
546 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700547 int64_t last_ping_sent() const { return last_ping_sent_; }
548 void Ping(int64_t now);
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700549 void ReceivedPingResponse(int rtt, const std::string& request_id);
honghaiz34b11eb2016-03-16 08:55:44 -0700550 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800551 return last_ping_response_received_;
552 }
Honghai Zhangfd16da22016-08-17 16:12:46 -0700553 // Used to check if any STUN ping response has been received.
554 int rtt_samples() const { return rtt_samples_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000555
556 // Called whenever a valid ping is received on this connection. This is
557 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700558 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800560 // Handles the binding request; sends a response if this is a valid request.
561 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000562
Honghai Zhang572b0942016-06-23 12:26:57 -0700563 int64_t last_data_received() const { return last_data_received_; }
564
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000565 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000566 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567 std::string ToString() const;
568 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700569 // Prints pings_since_last_response_ into a string.
570 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000571
572 bool reported() const { return reported_; }
573 void set_reported(bool reported) { reported_ = reported;}
574
honghaiz5a3acd82015-08-20 15:53:17 -0700575 // This signal will be fired if this connection is nominated by the
576 // controlling side.
577 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700578
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000579 // Invoked when Connection receives STUN error response with 487 code.
580 void HandleRoleConflictFromPeer();
581
hbos06495bc2017-01-02 08:08:18 -0800582 IceCandidatePairState state() const { return state_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000583
honghaiz524ecc22016-05-25 12:48:31 -0700584 int num_pings_sent() const { return num_pings_sent_; }
585
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000586 IceMode remote_ice_mode() const { return remote_ice_mode_; }
587
honghaize1a0c942016-02-16 14:54:56 -0800588 uint32_t ComputeNetworkCost() const;
589
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700590 // Update the ICE password and/or generation of the remote candidate if the
591 // ufrag in |params| matches the candidate's ufrag, and the
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700592 // candidate's password and/or ufrag has not been set.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700593 void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
594 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000595
596 // If |remote_candidate_| is peer reflexive and is equivalent to
597 // |new_candidate| except the type, update |remote_candidate_| to
598 // |new_candidate|.
599 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
600
Peter Thatcher54360512015-07-08 11:08:35 -0700601 // Returns the last received time of any data, stun request, or stun
602 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700603 int64_t last_received() const;
honghaiz9ad0db52016-07-14 19:30:28 -0700604 // Returns the last time when the connection changed its receiving state.
605 int64_t receiving_unchanged_since() const {
606 return receiving_unchanged_since_;
607 }
Peter Thatcher54360512015-07-08 11:08:35 -0700608
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700609 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700610
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700612 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
613
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614 // Constructs a new connection to the given remote port.
615 Connection(Port* port, size_t index, const Candidate& candidate);
616
617 // Called back when StunRequestManager has a stun packet to send
618 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
619
620 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700621 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
622 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000623 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
624 StunMessage* response);
625 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700626 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000627
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700628 bool rtt_converged() const;
zhihuang435264a2016-06-21 11:28:38 -0700629
630 // If the response is not received within 2 * RTT, the response is assumed to
631 // be missing.
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700632 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700633
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000634 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000635 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-14 19:30:28 -0700636 void UpdateReceiving(int64_t now);
hbos06495bc2017-01-02 08:08:18 -0800637 void set_state(IceCandidatePairState state);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000638 void set_connected(bool value);
639
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700640 uint32_t nomination() const { return nomination_; }
641
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000642 void OnMessage(rtc::Message *pmsg);
643
644 Port* port_;
645 size_t local_candidate_index_;
646 Candidate remote_candidate_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700647
648 ConnectionInfo stats_;
649 rtc::RateTracker recv_rate_tracker_;
650 rtc::RateTracker send_rate_tracker_;
651
652 private:
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700653 // Update the local candidate based on the mapped address attribute.
654 // If the local candidate changed, fires SignalStateChange.
655 void MaybeUpdateLocalCandidate(ConnectionRequest* request,
656 StunMessage* response);
657
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000658 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700659 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 bool connected_;
661 bool pruned_;
662 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700663 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664 // But when peer is ice-lite, this flag "must" be initialized to false and
665 // turn on when connection becomes "best connection".
666 bool use_candidate_attr_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700667 // Used by the controlling side to indicate that this connection will be
668 // selected for transmission if the peer supports ICE-renomination when this
669 // value is positive. A larger-value indicates that a connection is nominated
670 // later and should be selected by the controlled side with higher precedence.
671 // A zero-value indicates not nominating this connection.
672 uint32_t nomination_ = 0;
673 // The last nomination that has been acknowledged.
674 uint32_t acked_nomination_ = 0;
675 // Used by the controlled side to remember the nomination value received from
676 // the controlling side. When the peer does not support ICE re-nomination,
677 // its value will be 1 if the connection has been nominated.
678 uint32_t remote_nomination_ = 0;
679
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000680 IceMode remote_ice_mode_;
681 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700682 int rtt_;
zhihuang435264a2016-06-21 11:28:38 -0700683 int rtt_samples_ = 0;
honghaiz34b11eb2016-03-16 08:55:44 -0700684 int64_t last_ping_sent_; // last time we sent a ping to the other side
685 int64_t last_ping_received_; // last time we received a ping from the other
686 // side
687 int64_t last_data_received_;
688 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-14 19:30:28 -0700689 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700690 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000692 bool reported_;
hbos06495bc2017-01-02 08:08:18 -0800693 IceCandidatePairState state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700694 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700695 int receiving_timeout_;
696 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 12:48:31 -0700697 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000698
699 friend class Port;
700 friend class ConnectionRequest;
701};
702
deadbeef376e1232015-11-25 09:00:08 -0800703// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000704class ProxyConnection : public Connection {
705 public:
deadbeef376e1232015-11-25 09:00:08 -0800706 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000707
deadbeef376e1232015-11-25 09:00:08 -0800708 int Send(const void* data,
709 size_t size,
710 const rtc::PacketOptions& options) override;
711 int GetError() override { return error_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000712
713 private:
deadbeef376e1232015-11-25 09:00:08 -0800714 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000715};
716
717} // namespace cricket
718
719#endif // WEBRTC_P2P_BASE_PORT_H_