blob: fd6d18290b444384df893fbeb92dc496fbd881c2 [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
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000020#include "webrtc/base/asyncpacketsocket.h"
nissec80e7412017-01-11 05:56:46 -080021#include "webrtc/base/checks.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000022#include "webrtc/base/network.h"
hbosbf8d3e52017-02-28 06:34:47 -080023#include "webrtc/base/optional.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000024#include "webrtc/base/proxyinfo.h"
25#include "webrtc/base/ratetracker.h"
26#include "webrtc/base/sigslot.h"
27#include "webrtc/base/socketaddress.h"
28#include "webrtc/base/thread.h"
zsteinabbacbf2017-03-20 10:53:12 -070029#include "webrtc/p2p/base/candidate.h"
30#include "webrtc/p2p/base/candidatepairinterface.h"
31#include "webrtc/p2p/base/jseptransport.h"
32#include "webrtc/p2p/base/packetlossestimator.h"
33#include "webrtc/p2p/base/packetsocketfactory.h"
34#include "webrtc/p2p/base/portinterface.h"
35#include "webrtc/p2p/base/stun.h"
36#include "webrtc/p2p/base/stunrequest.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000037
38namespace cricket {
39
40class Connection;
41class ConnectionRequest;
42
43extern const char LOCAL_PORT_TYPE[];
44extern const char STUN_PORT_TYPE[];
45extern const char PRFLX_PORT_TYPE[];
46extern const char RELAY_PORT_TYPE[];
47
48extern const char UDP_PROTOCOL_NAME[];
49extern const char TCP_PROTOCOL_NAME[];
50extern const char SSLTCP_PROTOCOL_NAME[];
hnslb68cc752016-12-13 10:33:41 -080051extern const char TLS_PROTOCOL_NAME[];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000052
53// RFC 6544, TCP candidate encoding rules.
54extern const int DISCARD_PORT;
55extern const char TCPTYPE_ACTIVE_STR[];
56extern const char TCPTYPE_PASSIVE_STR[];
57extern const char TCPTYPE_SIMOPEN_STR[];
58
Honghai Zhang2b342bf2015-09-30 09:51:58 -070059// The minimum time we will wait before destroying a connection after creating
60// it.
honghaiz34b11eb2016-03-16 08:55:44 -070061static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070062
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080063// A connection will be declared dead if it has not received anything for this
64// long.
honghaiz34b11eb2016-03-16 08:55:44 -070065static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080066
Peter Thatcher04ac81f2015-09-21 11:48:28 -070067// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070068static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000069
70// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070071static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000072
73// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070074static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000075
76// This is the length of time that we wait for a ping response to come back.
skvlad51072462017-02-02 11:50:14 -080077// There is no harm to keep this value high other than a small amount
78// of increased memory. But in some networks (2G),
79// we observe up to 60s RTTs.
80static const int CONNECTION_RESPONSE_TIMEOUT = 60 * 1000; // 60 seconds
honghaiz34b11eb2016-03-16 08:55:44 -070081
82// The number of pings that must fail to respond before we become unwritable.
83static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000084
85enum RelayType {
86 RELAY_GTURN, // Legacy google relay service.
87 RELAY_TURN // Standard (TURN) relay service.
88};
89
90enum IcePriorityValue {
hnsl277b2502016-12-13 05:17:23 -080091 ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
92 ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
93 ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
Taylor Brandstetter62351c92016-08-11 16:05:07 -070094 ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000095 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
96 ICE_TYPE_PREFERENCE_SRFLX = 100,
97 ICE_TYPE_PREFERENCE_PRFLX = 110,
98 ICE_TYPE_PREFERENCE_HOST = 126
99};
100
hbos06495bc2017-01-02 08:08:18 -0800101// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
102enum class IceCandidatePairState {
103 WAITING = 0, // Check has not been performed, Waiting pair on CL.
104 IN_PROGRESS, // Check has been sent, transaction is in progress.
105 SUCCEEDED, // Check already done, produced a successful result.
106 FAILED, // Check for this connection failed.
107 // According to spec there should also be a frozen state, but nothing is ever
108 // frozen because we have not implemented ICE freezing logic.
109};
110
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000111const char* ProtoToString(ProtocolType proto);
112bool StringToProto(const char* value, ProtocolType* proto);
113
114struct ProtocolAddress {
115 rtc::SocketAddress address;
116 ProtocolType proto;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000117
118 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
hnsl277b2502016-12-13 05:17:23 -0800119 : address(a), proto(p) {}
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700120
121 bool operator==(const ProtocolAddress& o) const {
hnsl277b2502016-12-13 05:17:23 -0800122 return address == o.address && proto == o.proto;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700123 }
124 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000125};
126
127typedef std::set<rtc::SocketAddress> ServerAddresses;
128
129// Represents a local communication mechanism that can be used to create
130// connections to similar mechanisms of the other client. Subclasses of this
131// one add support for specific mechanisms like local UDP ports.
132class Port : public PortInterface, public rtc::MessageHandler,
133 public sigslot::has_slots<> {
134 public:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700135 // INIT: The state when a port is just created.
136 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
137 // connection is using it.
138 // PRUNED: It will be destroyed if no connection is using it for a period of
139 // 30 seconds.
140 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000141 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700142 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000143 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000144 rtc::Network* network,
145 const rtc::IPAddress& ip,
146 const std::string& username_fragment,
147 const std::string& password);
148 Port(rtc::Thread* thread,
149 const std::string& type,
150 rtc::PacketSocketFactory* factory,
151 rtc::Network* network,
152 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200153 uint16_t min_port,
154 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000155 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000156 const std::string& password);
157 virtual ~Port();
158
159 virtual const std::string& Type() const { return type_; }
160 virtual rtc::Network* Network() const { return network_; }
161
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000162 // Methods to set/get ICE role and tiebreaker values.
163 IceRole GetIceRole() const { return ice_role_; }
164 void SetIceRole(IceRole role) { ice_role_ = role; }
165
Peter Boström0c4e06b2015-10-07 12:23:21 +0200166 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
167 uint64_t IceTiebreaker() const { return tiebreaker_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000168
169 virtual bool SharedSocket() const { return shared_socket_; }
170 void ResetSharedSocket() { shared_socket_ = false; }
171
Honghai Zhanga74363c2016-07-28 18:06:15 -0700172 // Should not destroy the port even if no connection is using it. Called when
173 // a port is ready to use.
174 void KeepAliveUntilPruned();
175 // Allows a port to be destroyed if no connection is using it.
176 void Prune();
177
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178 // The thread on which this port performs its I/O.
179 rtc::Thread* thread() { return thread_; }
180
181 // The factory used to create the sockets of this port.
182 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
183 void set_socket_factory(rtc::PacketSocketFactory* factory) {
184 factory_ = factory;
185 }
186
187 // For debugging purposes.
188 const std::string& content_name() const { return content_name_; }
189 void set_content_name(const std::string& content_name) {
190 content_name_ = content_name;
191 }
192
193 int component() const { return component_; }
194 void set_component(int component) { component_ = component; }
195
196 bool send_retransmit_count_attribute() const {
197 return send_retransmit_count_attribute_;
198 }
199 void set_send_retransmit_count_attribute(bool enable) {
200 send_retransmit_count_attribute_ = enable;
201 }
202
203 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-22 17:14:15 -0700204 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200205 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000206
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000207 const std::string username_fragment() const;
208 const std::string& password() const { return password_; }
209
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700210 // May be called when this port was initially created by a pooled
211 // PortAllocatorSession, and is now being assigned to an ICE transport.
212 // Updates the information for candidates as well.
213 void SetIceParameters(int component,
214 const std::string& username_fragment,
215 const std::string& password);
216
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000217 // Fired when candidates are discovered by the port. When all candidates
218 // are discovered that belong to port SignalAddressReady is fired.
219 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
220
221 // Provides all of the above information in one handy object.
222 virtual const std::vector<Candidate>& Candidates() const {
223 return candidates_;
224 }
225
226 // SignalPortComplete is sent when port completes the task of candidates
227 // allocation.
228 sigslot::signal1<Port*> SignalPortComplete;
229 // This signal sent when port fails to allocate candidates and this port
230 // can't be used in establishing the connections. When port is in shared mode
231 // and port fails to allocate one of the candidates, port shouldn't send
232 // this signal as other candidates might be usefull in establishing the
233 // connection.
234 sigslot::signal1<Port*> SignalPortError;
235
236 // Returns a map containing all of the connections of this port, keyed by the
237 // remote address.
238 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
239 const AddressMap& connections() { return connections_; }
240
241 // Returns the connection to the given address or NULL if none exists.
242 virtual Connection* GetConnection(
243 const rtc::SocketAddress& remote_addr);
244
245 // Called each time a connection is created.
246 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
247
248 // In a shared socket mode each port which shares the socket will decide
249 // to accept the packet based on the |remote_addr|. Currently only UDP
250 // port implemented this method.
251 // TODO(mallinath) - Make it pure virtual.
252 virtual bool HandleIncomingPacket(
253 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
254 const rtc::SocketAddress& remote_addr,
255 const rtc::PacketTime& packet_time) {
nissec80e7412017-01-11 05:56:46 -0800256 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000257 return false;
258 }
259
260 // Sends a response message (normal or error) to the given request. One of
261 // these methods should be called as a response to SignalUnknownAddress.
262 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
263 virtual void SendBindingResponse(StunMessage* request,
264 const rtc::SocketAddress& addr);
265 virtual void SendBindingErrorResponse(
266 StunMessage* request, const rtc::SocketAddress& addr,
267 int error_code, const std::string& reason);
268
269 void set_proxy(const std::string& user_agent,
270 const rtc::ProxyInfo& proxy) {
271 user_agent_ = user_agent;
272 proxy_ = proxy;
273 }
274 const std::string& user_agent() { return user_agent_; }
275 const rtc::ProxyInfo& proxy() { return proxy_; }
276
277 virtual void EnablePortPackets();
278
279 // Called if the port has no connections and is no longer useful.
280 void Destroy();
281
282 virtual void OnMessage(rtc::Message *pmsg);
283
284 // Debugging description of this port
285 virtual std::string ToString() const;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000286 const rtc::IPAddress& ip() const { return ip_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200287 uint16_t min_port() { return min_port_; }
288 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000289
290 // Timeout shortening function to speed up unit tests.
291 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
292
293 // This method will return local and remote username fragements from the
294 // stun username attribute if present.
295 bool ParseStunUsername(const StunMessage* stun_msg,
296 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700297 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000298 void CreateStunUsername(const std::string& remote_username,
299 std::string* stun_username_attr_str) const;
300
301 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
302 IceMessage* stun_msg,
303 const std::string& remote_ufrag);
304
stefanc1aeaf02015-10-15 07:26:07 -0700305 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100306 // This is made pure virtual to notify subclasses of Port that they MUST
307 // listen to AsyncPacketSocket::SignalSentPacket and then call
308 // PortInterface::OnSentPacket.
309 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
310 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700311
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000312 // Called when the socket is currently able to send.
313 void OnReadyToSend();
314
315 // Called when the Connection discovers a local peer reflexive candidate.
316 // Returns the index of the new local candidate.
317 size_t AddPrflxCandidate(const Candidate& local);
318
honghaiza0c44ea2016-03-23 16:07:48 -0700319 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000320
321 protected:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700322 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000323
Honghai Zhang351d77b2016-05-20 15:08:29 -0700324 virtual void UpdateNetworkCost();
325
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000326 void set_type(const std::string& type) { type_ = type; }
327
Peter Boström2758c662017-02-13 20:33:27 -0500328 // Deprecated. Use the AddAddress() method below with "url" instead.
329 // TODO(zhihuang): Remove this after downstream applications stop using it.
330 void AddAddress(const rtc::SocketAddress& address,
331 const rtc::SocketAddress& base_address,
332 const rtc::SocketAddress& related_address,
333 const std::string& protocol,
334 const std::string& relay_protocol,
335 const std::string& tcptype,
336 const std::string& type,
337 uint32_t type_preference,
338 uint32_t relay_preference,
339 bool final);
340
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000341 void AddAddress(const rtc::SocketAddress& address,
342 const rtc::SocketAddress& base_address,
343 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700344 const std::string& protocol,
345 const std::string& relay_protocol,
346 const std::string& tcptype,
347 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200348 uint32_t type_preference,
349 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800350 const std::string& url,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700351 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000352
honghaiz36f50e82016-06-01 15:57:03 -0700353 // Adds the given connection to the map keyed by the remote candidate address.
354 // If an existing connection has the same address, the existing one will be
355 // replaced and destroyed.
356 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000357
358 // Called when a packet is received from an unknown address that is not
359 // currently a connection. If this is an authenticated STUN binding request,
360 // then we will signal the client.
361 void OnReadPacket(const char* data, size_t size,
362 const rtc::SocketAddress& addr,
363 ProtocolType proto);
364
365 // If the given data comprises a complete and correct STUN message then the
366 // return value is true, otherwise false. If the message username corresponds
367 // with this port's username fragment, msg will contain the parsed STUN
368 // message. Otherwise, the function may send a STUN response internally.
369 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700370 bool GetStunMessage(const char* data,
371 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000372 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700373 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700374 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000375
376 // Checks if the address in addr is compatible with the port's ip.
377 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
378
379 // Returns default DSCP value.
380 rtc::DiffServCodePoint DefaultDscpValue() const {
381 // No change from what MediaChannel set.
382 return rtc::DSCP_NO_CHANGE;
383 }
384
honghaiz36f50e82016-06-01 15:57:03 -0700385 // Extra work to be done in subclasses when a connection is destroyed.
386 virtual void HandleConnectionDestroyed(Connection* conn) {}
387
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000388 private:
389 void Construct();
390 // Called when one of our connections deletes itself.
391 void OnConnectionDestroyed(Connection* conn);
392
Honghai Zhang351d77b2016-05-20 15:08:29 -0700393 void OnNetworkTypeChanged(const rtc::Network* network);
394
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000395 rtc::Thread* thread_;
396 rtc::PacketSocketFactory* factory_;
397 std::string type_;
398 bool send_retransmit_count_attribute_;
399 rtc::Network* network_;
400 rtc::IPAddress ip_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200401 uint16_t min_port_;
402 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000403 std::string content_name_;
404 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200405 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000406 // In order to establish a connection to this Port (so that real data can be
407 // sent through), the other side must send us a STUN binding request that is
408 // authenticated with this username_fragment and password.
409 // PortAllocatorSession will provide these username_fragment and password.
410 //
411 // Note: we should always use username_fragment() instead of using
412 // |ice_username_fragment_| directly. For the details see the comment on
413 // username_fragment().
414 std::string ice_username_fragment_;
415 std::string password_;
416 std::vector<Candidate> candidates_;
417 AddressMap connections_;
418 int timeout_delay_;
419 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200421 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000422 bool shared_socket_;
423 // Information to use when going through a proxy.
424 std::string user_agent_;
425 rtc::ProxyInfo proxy_;
426
honghaize1a0c942016-02-16 14:54:56 -0800427 // A virtual cost perceived by the user, usually based on the network type
428 // (WiFi. vs. Cellular). It takes precedence over the priority when
429 // comparing two connections.
honghaiza0c44ea2016-03-23 16:07:48 -0700430 uint16_t network_cost_;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700431 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700432 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 14:54:56 -0800433
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000434 friend class Connection;
435};
436
437// Represents a communication link between a port on the local client and a
438// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700439class Connection : public CandidatePairInterface,
440 public rtc::MessageHandler,
441 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700443 struct SentPing {
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700444 SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
445 : id(id), sent_time(sent_time), nomination(nomination) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700446
447 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700448 int64_t sent_time;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700449 uint32_t nomination;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700450 };
451
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000452 virtual ~Connection();
453
454 // The local port where this connection sends and receives packets.
455 Port* port() { return port_; }
456 const Port* port() const { return port_; }
457
Honghai Zhangcc411c02016-03-29 17:27:21 -0700458 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 // Returns the description of the local port
460 virtual const Candidate& local_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461 // Returns the description of the remote port to which we communicate.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700462 virtual const Candidate& remote_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000463
464 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200465 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000466
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000467 enum WriteState {
468 STATE_WRITABLE = 0, // we have received ping responses recently
469 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
470 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
471 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
472 };
473
474 WriteState write_state() const { return write_state_; }
475 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700476 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000477
478 // Determines whether the connection has finished connecting. This can only
479 // be false for TCP connections.
480 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700481 bool weak() const { return !(writable() && receiving() && connected()); }
482 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700483 return write_state_ != STATE_WRITE_TIMEOUT;
484 }
honghaiz059e1832016-06-24 11:03:55 -0700485
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700486 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700487 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700488
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700490 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000491
hbos06495bc2017-01-02 08:08:18 -0800492 // Gets the |ConnectionInfo| stats, where |best_connection| has not been
493 // populated (default value false).
zhihuang5ecf16c2016-06-01 17:09:15 -0700494 ConnectionInfo stats();
495
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000496 sigslot::signal1<Connection*> SignalStateChange;
497
498 // Sent when the connection has decided that it is no longer of value. It
499 // will delete itself immediately after this call.
500 sigslot::signal1<Connection*> SignalDestroyed;
501
502 // The connection can send and receive packets asynchronously. This matches
503 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
504 // covers.
505 virtual int Send(const void* data, size_t size,
506 const rtc::PacketOptions& options) = 0;
507
508 // Error if Send() returns < 0
509 virtual int GetError() = 0;
510
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700511 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
512 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000513
514 sigslot::signal1<Connection*> SignalReadyToSend;
515
516 // Called when a packet is received on this connection.
517 void OnReadPacket(const char* data, size_t size,
518 const rtc::PacketTime& packet_time);
519
520 // Called when the socket is currently able to send.
521 void OnReadyToSend();
522
523 // Called when a connection is determined to be no longer useful to us. We
524 // still keep it around in case the other side wants to use it. But we can
525 // safely stop pinging on it and we can allow it to time out if the other
526 // side stops using it as well.
527 bool pruned() const { return pruned_; }
528 void Prune();
529
530 bool use_candidate_attr() const { return use_candidate_attr_; }
531 void set_use_candidate_attr(bool enable);
532
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700533 void set_nomination(uint32_t value) { nomination_ = value; }
534
535 uint32_t remote_nomination() const { return remote_nomination_; }
hbos92eaec62017-02-27 01:38:08 -0800536 // One or several pairs may be nominated based on if Regular or Aggressive
537 // Nomination is used. https://tools.ietf.org/html/rfc5245#section-8
538 // |nominated| is defined both for the controlling or controlled agent based
539 // on if a nomination has been pinged or acknowledged. The controlled agent
540 // gets its |remote_nomination_| set when pinged by the controlling agent with
541 // a nomination value. The controlling agent gets its |acked_nomination_| set
542 // when receiving a response to a nominating ping.
543 bool nominated() const { return acked_nomination_ || remote_nomination_; }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700544 // Public for unit tests.
545 void set_remote_nomination(uint32_t remote_nomination) {
546 remote_nomination_ = remote_nomination;
547 }
548 // Public for unit tests.
549 uint32_t acked_nomination() const { return acked_nomination_; }
honghaiz5a3acd82015-08-20 15:53:17 -0700550
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000551 void set_remote_ice_mode(IceMode mode) {
552 remote_ice_mode_ = mode;
553 }
554
bertholdherrmann0812030662016-10-18 14:00:02 -0700555 void set_receiving_timeout(int receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700556 receiving_timeout_ = receiving_timeout_ms;
557 }
558
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000559 // Makes the connection go away.
560 void Destroy();
561
deadbeef376e1232015-11-25 09:00:08 -0800562 // Makes the connection go away, in a failed state.
563 void FailAndDestroy();
564
honghaiz079a7a12016-06-22 16:26:29 -0700565 // Prunes the connection and sets its state to STATE_FAILED,
566 // It will not be used or send pings although it can still receive packets.
567 void FailAndPrune();
568
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 // Checks that the state of this connection is up-to-date. The argument is
570 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700571 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000572
573 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700574 int64_t last_ping_sent() const { return last_ping_sent_; }
575 void Ping(int64_t now);
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700576 void ReceivedPingResponse(int rtt, const std::string& request_id);
honghaiz34b11eb2016-03-16 08:55:44 -0700577 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800578 return last_ping_response_received_;
579 }
Honghai Zhangfd16da22016-08-17 16:12:46 -0700580 // Used to check if any STUN ping response has been received.
581 int rtt_samples() const { return rtt_samples_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000582
583 // Called whenever a valid ping is received on this connection. This is
584 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700585 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000586 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800587 // Handles the binding request; sends a response if this is a valid request.
588 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000589
Honghai Zhang572b0942016-06-23 12:26:57 -0700590 int64_t last_data_received() const { return last_data_received_; }
591
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000593 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000594 std::string ToString() const;
595 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700596 // Prints pings_since_last_response_ into a string.
597 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000598
599 bool reported() const { return reported_; }
600 void set_reported(bool reported) { reported_ = reported;}
601
honghaiz5a3acd82015-08-20 15:53:17 -0700602 // This signal will be fired if this connection is nominated by the
603 // controlling side.
604 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700605
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000606 // Invoked when Connection receives STUN error response with 487 code.
607 void HandleRoleConflictFromPeer();
608
hbos06495bc2017-01-02 08:08:18 -0800609 IceCandidatePairState state() const { return state_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000610
honghaiz524ecc22016-05-25 12:48:31 -0700611 int num_pings_sent() const { return num_pings_sent_; }
612
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000613 IceMode remote_ice_mode() const { return remote_ice_mode_; }
614
honghaize1a0c942016-02-16 14:54:56 -0800615 uint32_t ComputeNetworkCost() const;
616
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700617 // Update the ICE password and/or generation of the remote candidate if the
618 // ufrag in |params| matches the candidate's ufrag, and the
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700619 // candidate's password and/or ufrag has not been set.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700620 void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
621 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000622
623 // If |remote_candidate_| is peer reflexive and is equivalent to
624 // |new_candidate| except the type, update |remote_candidate_| to
625 // |new_candidate|.
626 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
627
Peter Thatcher54360512015-07-08 11:08:35 -0700628 // Returns the last received time of any data, stun request, or stun
629 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700630 int64_t last_received() const;
honghaiz9ad0db52016-07-14 19:30:28 -0700631 // Returns the last time when the connection changed its receiving state.
632 int64_t receiving_unchanged_since() const {
633 return receiving_unchanged_since_;
634 }
Peter Thatcher54360512015-07-08 11:08:35 -0700635
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700636 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700637
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000638 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700639 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
640
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000641 // Constructs a new connection to the given remote port.
642 Connection(Port* port, size_t index, const Candidate& candidate);
643
644 // Called back when StunRequestManager has a stun packet to send
645 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
646
647 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700648 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
649 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000650 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
651 StunMessage* response);
652 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700653 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000654
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700655 bool rtt_converged() const;
zhihuang435264a2016-06-21 11:28:38 -0700656
657 // If the response is not received within 2 * RTT, the response is assumed to
658 // be missing.
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700659 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700660
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000661 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000662 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-14 19:30:28 -0700663 void UpdateReceiving(int64_t now);
hbos06495bc2017-01-02 08:08:18 -0800664 void set_state(IceCandidatePairState state);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000665 void set_connected(bool value);
666
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700667 uint32_t nomination() const { return nomination_; }
668
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000669 void OnMessage(rtc::Message *pmsg);
670
671 Port* port_;
672 size_t local_candidate_index_;
673 Candidate remote_candidate_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700674
675 ConnectionInfo stats_;
676 rtc::RateTracker recv_rate_tracker_;
677 rtc::RateTracker send_rate_tracker_;
678
679 private:
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700680 // Update the local candidate based on the mapped address attribute.
681 // If the local candidate changed, fires SignalStateChange.
682 void MaybeUpdateLocalCandidate(ConnectionRequest* request,
683 StunMessage* response);
684
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700686 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000687 bool connected_;
688 bool pruned_;
689 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700690 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000691 // But when peer is ice-lite, this flag "must" be initialized to false and
692 // turn on when connection becomes "best connection".
693 bool use_candidate_attr_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700694 // Used by the controlling side to indicate that this connection will be
695 // selected for transmission if the peer supports ICE-renomination when this
696 // value is positive. A larger-value indicates that a connection is nominated
697 // later and should be selected by the controlled side with higher precedence.
698 // A zero-value indicates not nominating this connection.
699 uint32_t nomination_ = 0;
700 // The last nomination that has been acknowledged.
701 uint32_t acked_nomination_ = 0;
702 // Used by the controlled side to remember the nomination value received from
703 // the controlling side. When the peer does not support ICE re-nomination,
704 // its value will be 1 if the connection has been nominated.
705 uint32_t remote_nomination_ = 0;
706
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000707 IceMode remote_ice_mode_;
708 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700709 int rtt_;
zhihuang435264a2016-06-21 11:28:38 -0700710 int rtt_samples_ = 0;
hbosbf8d3e52017-02-28 06:34:47 -0800711 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
712 uint64_t total_round_trip_time_ms_ = 0;
713 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
714 rtc::Optional<uint32_t> current_round_trip_time_ms_;
honghaiz34b11eb2016-03-16 08:55:44 -0700715 int64_t last_ping_sent_; // last time we sent a ping to the other side
716 int64_t last_ping_received_; // last time we received a ping from the other
717 // side
718 int64_t last_data_received_;
719 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-14 19:30:28 -0700720 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700721 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000722
zsteinabbacbf2017-03-20 10:53:12 -0700723 PacketLossEstimator packet_loss_estimator_;
724
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000725 bool reported_;
hbos06495bc2017-01-02 08:08:18 -0800726 IceCandidatePairState state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700727 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700728 int receiving_timeout_;
729 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 12:48:31 -0700730 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000731
732 friend class Port;
733 friend class ConnectionRequest;
734};
735
deadbeef376e1232015-11-25 09:00:08 -0800736// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737class ProxyConnection : public Connection {
738 public:
deadbeef376e1232015-11-25 09:00:08 -0800739 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000740
deadbeef376e1232015-11-25 09:00:08 -0800741 int Send(const void* data,
742 size_t size,
743 const rtc::PacketOptions& options) override;
744 int GetError() override { return error_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000745
746 private:
deadbeef376e1232015-11-25 09:00:08 -0800747 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000748};
749
750} // namespace cricket
751
752#endif // WEBRTC_P2P_BASE_PORT_H_