blob: 4d156567766746405c54cc94d4911effbc4dd2a6 [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"
nissec80e7412017-01-11 05:56:46 -080028#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000029#include "webrtc/base/network.h"
hbosbf8d3e52017-02-28 06:34:47 -080030#include "webrtc/base/optional.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000031#include "webrtc/base/proxyinfo.h"
32#include "webrtc/base/ratetracker.h"
33#include "webrtc/base/sigslot.h"
34#include "webrtc/base/socketaddress.h"
35#include "webrtc/base/thread.h"
36
37namespace cricket {
38
39class Connection;
40class ConnectionRequest;
41
42extern const char LOCAL_PORT_TYPE[];
43extern const char STUN_PORT_TYPE[];
44extern const char PRFLX_PORT_TYPE[];
45extern const char RELAY_PORT_TYPE[];
46
47extern const char UDP_PROTOCOL_NAME[];
48extern const char TCP_PROTOCOL_NAME[];
49extern const char SSLTCP_PROTOCOL_NAME[];
hnslb68cc752016-12-13 10:33:41 -080050extern const char TLS_PROTOCOL_NAME[];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000051
52// RFC 6544, TCP candidate encoding rules.
53extern const int DISCARD_PORT;
54extern const char TCPTYPE_ACTIVE_STR[];
55extern const char TCPTYPE_PASSIVE_STR[];
56extern const char TCPTYPE_SIMOPEN_STR[];
57
Honghai Zhang2b342bf2015-09-30 09:51:58 -070058// The minimum time we will wait before destroying a connection after creating
59// it.
honghaiz34b11eb2016-03-16 08:55:44 -070060static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070061
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080062// A connection will be declared dead if it has not received anything for this
63// long.
honghaiz34b11eb2016-03-16 08:55:44 -070064static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080065
Peter Thatcher04ac81f2015-09-21 11:48:28 -070066// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070067static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070070static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071
72// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070073static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000074
75// This is the length of time that we wait for a ping response to come back.
skvlad51072462017-02-02 11:50:14 -080076// There is no harm to keep this value high other than a small amount
77// of increased memory. But in some networks (2G),
78// we observe up to 60s RTTs.
79static const int CONNECTION_RESPONSE_TIMEOUT = 60 * 1000; // 60 seconds
honghaiz34b11eb2016-03-16 08:55:44 -070080
81// The number of pings that must fail to respond before we become unwritable.
82static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000083
84enum RelayType {
85 RELAY_GTURN, // Legacy google relay service.
86 RELAY_TURN // Standard (TURN) relay service.
87};
88
89enum IcePriorityValue {
hnsl277b2502016-12-13 05:17:23 -080090 ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
91 ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
92 ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
Taylor Brandstetter62351c92016-08-11 16:05:07 -070093 ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000094 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
95 ICE_TYPE_PREFERENCE_SRFLX = 100,
96 ICE_TYPE_PREFERENCE_PRFLX = 110,
97 ICE_TYPE_PREFERENCE_HOST = 126
98};
99
hbos06495bc2017-01-02 08:08:18 -0800100// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
101enum class IceCandidatePairState {
102 WAITING = 0, // Check has not been performed, Waiting pair on CL.
103 IN_PROGRESS, // Check has been sent, transaction is in progress.
104 SUCCEEDED, // Check already done, produced a successful result.
105 FAILED, // Check for this connection failed.
106 // According to spec there should also be a frozen state, but nothing is ever
107 // frozen because we have not implemented ICE freezing logic.
108};
109
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000110const char* ProtoToString(ProtocolType proto);
111bool StringToProto(const char* value, ProtocolType* proto);
112
113struct ProtocolAddress {
114 rtc::SocketAddress address;
115 ProtocolType proto;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000116
117 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
hnsl277b2502016-12-13 05:17:23 -0800118 : address(a), proto(p) {}
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700119
120 bool operator==(const ProtocolAddress& o) const {
hnsl277b2502016-12-13 05:17:23 -0800121 return address == o.address && proto == o.proto;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700122 }
123 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000124};
125
126typedef std::set<rtc::SocketAddress> ServerAddresses;
127
128// Represents a local communication mechanism that can be used to create
129// connections to similar mechanisms of the other client. Subclasses of this
130// one add support for specific mechanisms like local UDP ports.
131class Port : public PortInterface, public rtc::MessageHandler,
132 public sigslot::has_slots<> {
133 public:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700134 // INIT: The state when a port is just created.
135 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
136 // connection is using it.
137 // PRUNED: It will be destroyed if no connection is using it for a period of
138 // 30 seconds.
139 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000140 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700141 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000142 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000143 rtc::Network* network,
144 const rtc::IPAddress& ip,
145 const std::string& username_fragment,
146 const std::string& password);
147 Port(rtc::Thread* thread,
148 const std::string& type,
149 rtc::PacketSocketFactory* factory,
150 rtc::Network* network,
151 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200152 uint16_t min_port,
153 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000154 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000155 const std::string& password);
156 virtual ~Port();
157
158 virtual const std::string& Type() const { return type_; }
159 virtual rtc::Network* Network() const { return network_; }
160
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000161 // Methods to set/get ICE role and tiebreaker values.
162 IceRole GetIceRole() const { return ice_role_; }
163 void SetIceRole(IceRole role) { ice_role_ = role; }
164
Peter Boström0c4e06b2015-10-07 12:23:21 +0200165 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
166 uint64_t IceTiebreaker() const { return tiebreaker_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000167
168 virtual bool SharedSocket() const { return shared_socket_; }
169 void ResetSharedSocket() { shared_socket_ = false; }
170
Honghai Zhanga74363c2016-07-28 18:06:15 -0700171 // Should not destroy the port even if no connection is using it. Called when
172 // a port is ready to use.
173 void KeepAliveUntilPruned();
174 // Allows a port to be destroyed if no connection is using it.
175 void Prune();
176
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000177 // The thread on which this port performs its I/O.
178 rtc::Thread* thread() { return thread_; }
179
180 // The factory used to create the sockets of this port.
181 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
182 void set_socket_factory(rtc::PacketSocketFactory* factory) {
183 factory_ = factory;
184 }
185
186 // For debugging purposes.
187 const std::string& content_name() const { return content_name_; }
188 void set_content_name(const std::string& content_name) {
189 content_name_ = content_name;
190 }
191
192 int component() const { return component_; }
193 void set_component(int component) { component_ = component; }
194
195 bool send_retransmit_count_attribute() const {
196 return send_retransmit_count_attribute_;
197 }
198 void set_send_retransmit_count_attribute(bool enable) {
199 send_retransmit_count_attribute_ = enable;
200 }
201
202 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-22 17:14:15 -0700203 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200204 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206 const std::string username_fragment() const;
207 const std::string& password() const { return password_; }
208
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700209 // May be called when this port was initially created by a pooled
210 // PortAllocatorSession, and is now being assigned to an ICE transport.
211 // Updates the information for candidates as well.
212 void SetIceParameters(int component,
213 const std::string& username_fragment,
214 const std::string& password);
215
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000216 // Fired when candidates are discovered by the port. When all candidates
217 // are discovered that belong to port SignalAddressReady is fired.
218 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
219
220 // Provides all of the above information in one handy object.
221 virtual const std::vector<Candidate>& Candidates() const {
222 return candidates_;
223 }
224
225 // SignalPortComplete is sent when port completes the task of candidates
226 // allocation.
227 sigslot::signal1<Port*> SignalPortComplete;
228 // This signal sent when port fails to allocate candidates and this port
229 // can't be used in establishing the connections. When port is in shared mode
230 // and port fails to allocate one of the candidates, port shouldn't send
231 // this signal as other candidates might be usefull in establishing the
232 // connection.
233 sigslot::signal1<Port*> SignalPortError;
234
235 // Returns a map containing all of the connections of this port, keyed by the
236 // remote address.
237 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
238 const AddressMap& connections() { return connections_; }
239
240 // Returns the connection to the given address or NULL if none exists.
241 virtual Connection* GetConnection(
242 const rtc::SocketAddress& remote_addr);
243
244 // Called each time a connection is created.
245 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
246
247 // In a shared socket mode each port which shares the socket will decide
248 // to accept the packet based on the |remote_addr|. Currently only UDP
249 // port implemented this method.
250 // TODO(mallinath) - Make it pure virtual.
251 virtual bool HandleIncomingPacket(
252 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
253 const rtc::SocketAddress& remote_addr,
254 const rtc::PacketTime& packet_time) {
nissec80e7412017-01-11 05:56:46 -0800255 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000256 return false;
257 }
258
259 // Sends a response message (normal or error) to the given request. One of
260 // these methods should be called as a response to SignalUnknownAddress.
261 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
262 virtual void SendBindingResponse(StunMessage* request,
263 const rtc::SocketAddress& addr);
264 virtual void SendBindingErrorResponse(
265 StunMessage* request, const rtc::SocketAddress& addr,
266 int error_code, const std::string& reason);
267
268 void set_proxy(const std::string& user_agent,
269 const rtc::ProxyInfo& proxy) {
270 user_agent_ = user_agent;
271 proxy_ = proxy;
272 }
273 const std::string& user_agent() { return user_agent_; }
274 const rtc::ProxyInfo& proxy() { return proxy_; }
275
276 virtual void EnablePortPackets();
277
278 // Called if the port has no connections and is no longer useful.
279 void Destroy();
280
281 virtual void OnMessage(rtc::Message *pmsg);
282
283 // Debugging description of this port
284 virtual std::string ToString() const;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000285 const rtc::IPAddress& ip() const { return ip_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200286 uint16_t min_port() { return min_port_; }
287 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000288
289 // Timeout shortening function to speed up unit tests.
290 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
291
292 // This method will return local and remote username fragements from the
293 // stun username attribute if present.
294 bool ParseStunUsername(const StunMessage* stun_msg,
295 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700296 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000297 void CreateStunUsername(const std::string& remote_username,
298 std::string* stun_username_attr_str) const;
299
300 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
301 IceMessage* stun_msg,
302 const std::string& remote_ufrag);
303
stefanc1aeaf02015-10-15 07:26:07 -0700304 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100305 // This is made pure virtual to notify subclasses of Port that they MUST
306 // listen to AsyncPacketSocket::SignalSentPacket and then call
307 // PortInterface::OnSentPacket.
308 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
309 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700310
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000311 // Called when the socket is currently able to send.
312 void OnReadyToSend();
313
314 // Called when the Connection discovers a local peer reflexive candidate.
315 // Returns the index of the new local candidate.
316 size_t AddPrflxCandidate(const Candidate& local);
317
honghaiza0c44ea2016-03-23 16:07:48 -0700318 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000319
320 protected:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700321 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000322
Honghai Zhang351d77b2016-05-20 15:08:29 -0700323 virtual void UpdateNetworkCost();
324
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000325 void set_type(const std::string& type) { type_ = type; }
326
Peter Boström2758c662017-02-13 20:33:27 -0500327 // Deprecated. Use the AddAddress() method below with "url" instead.
328 // TODO(zhihuang): Remove this after downstream applications stop using it.
329 void AddAddress(const rtc::SocketAddress& address,
330 const rtc::SocketAddress& base_address,
331 const rtc::SocketAddress& related_address,
332 const std::string& protocol,
333 const std::string& relay_protocol,
334 const std::string& tcptype,
335 const std::string& type,
336 uint32_t type_preference,
337 uint32_t relay_preference,
338 bool final);
339
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000340 void AddAddress(const rtc::SocketAddress& address,
341 const rtc::SocketAddress& base_address,
342 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700343 const std::string& protocol,
344 const std::string& relay_protocol,
345 const std::string& tcptype,
346 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200347 uint32_t type_preference,
348 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800349 const std::string& url,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700350 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000351
honghaiz36f50e82016-06-01 15:57:03 -0700352 // Adds the given connection to the map keyed by the remote candidate address.
353 // If an existing connection has the same address, the existing one will be
354 // replaced and destroyed.
355 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000356
357 // Called when a packet is received from an unknown address that is not
358 // currently a connection. If this is an authenticated STUN binding request,
359 // then we will signal the client.
360 void OnReadPacket(const char* data, size_t size,
361 const rtc::SocketAddress& addr,
362 ProtocolType proto);
363
364 // If the given data comprises a complete and correct STUN message then the
365 // return value is true, otherwise false. If the message username corresponds
366 // with this port's username fragment, msg will contain the parsed STUN
367 // message. Otherwise, the function may send a STUN response internally.
368 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700369 bool GetStunMessage(const char* data,
370 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000371 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700372 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700373 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000374
375 // Checks if the address in addr is compatible with the port's ip.
376 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
377
378 // Returns default DSCP value.
379 rtc::DiffServCodePoint DefaultDscpValue() const {
380 // No change from what MediaChannel set.
381 return rtc::DSCP_NO_CHANGE;
382 }
383
honghaiz36f50e82016-06-01 15:57:03 -0700384 // Extra work to be done in subclasses when a connection is destroyed.
385 virtual void HandleConnectionDestroyed(Connection* conn) {}
386
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000387 private:
388 void Construct();
389 // Called when one of our connections deletes itself.
390 void OnConnectionDestroyed(Connection* conn);
391
Honghai Zhang351d77b2016-05-20 15:08:29 -0700392 void OnNetworkTypeChanged(const rtc::Network* network);
393
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394 rtc::Thread* thread_;
395 rtc::PacketSocketFactory* factory_;
396 std::string type_;
397 bool send_retransmit_count_attribute_;
398 rtc::Network* network_;
399 rtc::IPAddress ip_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200400 uint16_t min_port_;
401 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000402 std::string content_name_;
403 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200404 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000405 // In order to establish a connection to this Port (so that real data can be
406 // sent through), the other side must send us a STUN binding request that is
407 // authenticated with this username_fragment and password.
408 // PortAllocatorSession will provide these username_fragment and password.
409 //
410 // Note: we should always use username_fragment() instead of using
411 // |ice_username_fragment_| directly. For the details see the comment on
412 // username_fragment().
413 std::string ice_username_fragment_;
414 std::string password_;
415 std::vector<Candidate> candidates_;
416 AddressMap connections_;
417 int timeout_delay_;
418 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000419 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200420 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000421 bool shared_socket_;
422 // Information to use when going through a proxy.
423 std::string user_agent_;
424 rtc::ProxyInfo proxy_;
425
honghaize1a0c942016-02-16 14:54:56 -0800426 // A virtual cost perceived by the user, usually based on the network type
427 // (WiFi. vs. Cellular). It takes precedence over the priority when
428 // comparing two connections.
honghaiza0c44ea2016-03-23 16:07:48 -0700429 uint16_t network_cost_;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700430 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700431 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 14:54:56 -0800432
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000433 friend class Connection;
434};
435
436// Represents a communication link between a port on the local client and a
437// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700438class Connection : public CandidatePairInterface,
439 public rtc::MessageHandler,
440 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000441 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700442 struct SentPing {
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700443 SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
444 : id(id), sent_time(sent_time), nomination(nomination) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700445
446 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700447 int64_t sent_time;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700448 uint32_t nomination;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700449 };
450
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000451 virtual ~Connection();
452
453 // The local port where this connection sends and receives packets.
454 Port* port() { return port_; }
455 const Port* port() const { return port_; }
456
Honghai Zhangcc411c02016-03-29 17:27:21 -0700457 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000458 // Returns the description of the local port
459 virtual const Candidate& local_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460 // Returns the description of the remote port to which we communicate.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700461 virtual const Candidate& remote_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000462
463 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200464 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466 enum WriteState {
467 STATE_WRITABLE = 0, // we have received ping responses recently
468 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
469 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
470 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
471 };
472
473 WriteState write_state() const { return write_state_; }
474 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700475 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000476
477 // Determines whether the connection has finished connecting. This can only
478 // be false for TCP connections.
479 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700480 bool weak() const { return !(writable() && receiving() && connected()); }
481 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700482 return write_state_ != STATE_WRITE_TIMEOUT;
483 }
honghaiz059e1832016-06-24 11:03:55 -0700484
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700485 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700486 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700487
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000488 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700489 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000490
hbos06495bc2017-01-02 08:08:18 -0800491 // Gets the |ConnectionInfo| stats, where |best_connection| has not been
492 // populated (default value false).
zhihuang5ecf16c2016-06-01 17:09:15 -0700493 ConnectionInfo stats();
494
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000495 sigslot::signal1<Connection*> SignalStateChange;
496
497 // Sent when the connection has decided that it is no longer of value. It
498 // will delete itself immediately after this call.
499 sigslot::signal1<Connection*> SignalDestroyed;
500
501 // The connection can send and receive packets asynchronously. This matches
502 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
503 // covers.
504 virtual int Send(const void* data, size_t size,
505 const rtc::PacketOptions& options) = 0;
506
507 // Error if Send() returns < 0
508 virtual int GetError() = 0;
509
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700510 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
511 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000512
513 sigslot::signal1<Connection*> SignalReadyToSend;
514
515 // Called when a packet is received on this connection.
516 void OnReadPacket(const char* data, size_t size,
517 const rtc::PacketTime& packet_time);
518
519 // Called when the socket is currently able to send.
520 void OnReadyToSend();
521
522 // Called when a connection is determined to be no longer useful to us. We
523 // still keep it around in case the other side wants to use it. But we can
524 // safely stop pinging on it and we can allow it to time out if the other
525 // side stops using it as well.
526 bool pruned() const { return pruned_; }
527 void Prune();
528
529 bool use_candidate_attr() const { return use_candidate_attr_; }
530 void set_use_candidate_attr(bool enable);
531
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700532 void set_nomination(uint32_t value) { nomination_ = value; }
533
534 uint32_t remote_nomination() const { return remote_nomination_; }
hbos92eaec62017-02-27 01:38:08 -0800535 // One or several pairs may be nominated based on if Regular or Aggressive
536 // Nomination is used. https://tools.ietf.org/html/rfc5245#section-8
537 // |nominated| is defined both for the controlling or controlled agent based
538 // on if a nomination has been pinged or acknowledged. The controlled agent
539 // gets its |remote_nomination_| set when pinged by the controlling agent with
540 // a nomination value. The controlling agent gets its |acked_nomination_| set
541 // when receiving a response to a nominating ping.
542 bool nominated() const { return acked_nomination_ || remote_nomination_; }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700543 // Public for unit tests.
544 void set_remote_nomination(uint32_t remote_nomination) {
545 remote_nomination_ = remote_nomination;
546 }
547 // Public for unit tests.
548 uint32_t acked_nomination() const { return acked_nomination_; }
honghaiz5a3acd82015-08-20 15:53:17 -0700549
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000550 void set_remote_ice_mode(IceMode mode) {
551 remote_ice_mode_ = mode;
552 }
553
bertholdherrmann0812030662016-10-18 14:00:02 -0700554 void set_receiving_timeout(int receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700555 receiving_timeout_ = receiving_timeout_ms;
556 }
557
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000558 // Makes the connection go away.
559 void Destroy();
560
deadbeef376e1232015-11-25 09:00:08 -0800561 // Makes the connection go away, in a failed state.
562 void FailAndDestroy();
563
honghaiz079a7a12016-06-22 16:26:29 -0700564 // Prunes the connection and sets its state to STATE_FAILED,
565 // It will not be used or send pings although it can still receive packets.
566 void FailAndPrune();
567
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000568 // Checks that the state of this connection is up-to-date. The argument is
569 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700570 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000571
572 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700573 int64_t last_ping_sent() const { return last_ping_sent_; }
574 void Ping(int64_t now);
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700575 void ReceivedPingResponse(int rtt, const std::string& request_id);
honghaiz34b11eb2016-03-16 08:55:44 -0700576 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800577 return last_ping_response_received_;
578 }
Honghai Zhangfd16da22016-08-17 16:12:46 -0700579 // Used to check if any STUN ping response has been received.
580 int rtt_samples() const { return rtt_samples_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000581
582 // Called whenever a valid ping is received on this connection. This is
583 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700584 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000585 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800586 // Handles the binding request; sends a response if this is a valid request.
587 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000588
Honghai Zhang572b0942016-06-23 12:26:57 -0700589 int64_t last_data_received() const { return last_data_received_; }
590
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000591 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000592 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000593 std::string ToString() const;
594 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700595 // Prints pings_since_last_response_ into a string.
596 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000597
598 bool reported() const { return reported_; }
599 void set_reported(bool reported) { reported_ = reported;}
600
honghaiz5a3acd82015-08-20 15:53:17 -0700601 // This signal will be fired if this connection is nominated by the
602 // controlling side.
603 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700604
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000605 // Invoked when Connection receives STUN error response with 487 code.
606 void HandleRoleConflictFromPeer();
607
hbos06495bc2017-01-02 08:08:18 -0800608 IceCandidatePairState state() const { return state_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000609
honghaiz524ecc22016-05-25 12:48:31 -0700610 int num_pings_sent() const { return num_pings_sent_; }
611
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612 IceMode remote_ice_mode() const { return remote_ice_mode_; }
613
honghaize1a0c942016-02-16 14:54:56 -0800614 uint32_t ComputeNetworkCost() const;
615
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700616 // Update the ICE password and/or generation of the remote candidate if the
617 // ufrag in |params| matches the candidate's ufrag, and the
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700618 // candidate's password and/or ufrag has not been set.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700619 void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
620 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000621
622 // If |remote_candidate_| is peer reflexive and is equivalent to
623 // |new_candidate| except the type, update |remote_candidate_| to
624 // |new_candidate|.
625 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
626
Peter Thatcher54360512015-07-08 11:08:35 -0700627 // Returns the last received time of any data, stun request, or stun
628 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700629 int64_t last_received() const;
honghaiz9ad0db52016-07-14 19:30:28 -0700630 // Returns the last time when the connection changed its receiving state.
631 int64_t receiving_unchanged_since() const {
632 return receiving_unchanged_since_;
633 }
Peter Thatcher54360512015-07-08 11:08:35 -0700634
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700635 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700636
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000637 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700638 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
639
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000640 // Constructs a new connection to the given remote port.
641 Connection(Port* port, size_t index, const Candidate& candidate);
642
643 // Called back when StunRequestManager has a stun packet to send
644 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
645
646 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700647 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
648 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000649 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
650 StunMessage* response);
651 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700652 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000653
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700654 bool rtt_converged() const;
zhihuang435264a2016-06-21 11:28:38 -0700655
656 // If the response is not received within 2 * RTT, the response is assumed to
657 // be missing.
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700658 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700659
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-14 19:30:28 -0700662 void UpdateReceiving(int64_t now);
hbos06495bc2017-01-02 08:08:18 -0800663 void set_state(IceCandidatePairState state);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000664 void set_connected(bool value);
665
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700666 uint32_t nomination() const { return nomination_; }
667
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000668 void OnMessage(rtc::Message *pmsg);
669
670 Port* port_;
671 size_t local_candidate_index_;
672 Candidate remote_candidate_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700673
674 ConnectionInfo stats_;
675 rtc::RateTracker recv_rate_tracker_;
676 rtc::RateTracker send_rate_tracker_;
677
678 private:
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700679 // Update the local candidate based on the mapped address attribute.
680 // If the local candidate changed, fires SignalStateChange.
681 void MaybeUpdateLocalCandidate(ConnectionRequest* request,
682 StunMessage* response);
683
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000684 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700685 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000686 bool connected_;
687 bool pruned_;
688 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700689 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000690 // But when peer is ice-lite, this flag "must" be initialized to false and
691 // turn on when connection becomes "best connection".
692 bool use_candidate_attr_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700693 // Used by the controlling side to indicate that this connection will be
694 // selected for transmission if the peer supports ICE-renomination when this
695 // value is positive. A larger-value indicates that a connection is nominated
696 // later and should be selected by the controlled side with higher precedence.
697 // A zero-value indicates not nominating this connection.
698 uint32_t nomination_ = 0;
699 // The last nomination that has been acknowledged.
700 uint32_t acked_nomination_ = 0;
701 // Used by the controlled side to remember the nomination value received from
702 // the controlling side. When the peer does not support ICE re-nomination,
703 // its value will be 1 if the connection has been nominated.
704 uint32_t remote_nomination_ = 0;
705
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000706 IceMode remote_ice_mode_;
707 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700708 int rtt_;
zhihuang435264a2016-06-21 11:28:38 -0700709 int rtt_samples_ = 0;
hbosbf8d3e52017-02-28 06:34:47 -0800710 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
711 uint64_t total_round_trip_time_ms_ = 0;
712 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
713 rtc::Optional<uint32_t> current_round_trip_time_ms_;
honghaiz34b11eb2016-03-16 08:55:44 -0700714 int64_t last_ping_sent_; // last time we sent a ping to the other side
715 int64_t last_ping_received_; // last time we received a ping from the other
716 // side
717 int64_t last_data_received_;
718 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-14 19:30:28 -0700719 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700720 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000721
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722 bool reported_;
hbos06495bc2017-01-02 08:08:18 -0800723 IceCandidatePairState state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700724 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700725 int receiving_timeout_;
726 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 12:48:31 -0700727 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000728
729 friend class Port;
730 friend class ConnectionRequest;
731};
732
deadbeef376e1232015-11-25 09:00:08 -0800733// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000734class ProxyConnection : public Connection {
735 public:
deadbeef376e1232015-11-25 09:00:08 -0800736 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737
deadbeef376e1232015-11-25 09:00:08 -0800738 int Send(const void* data,
739 size_t size,
740 const rtc::PacketOptions& options) override;
741 int GetError() override { return error_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000742
743 private:
deadbeef376e1232015-11-25 09:00:08 -0800744 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000745};
746
747} // namespace cricket
748
749#endif // WEBRTC_P2P_BASE_PORT_H_