blob: a80fde79a9c40229a6b3759dba11abb7da51861c [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"
30#include "webrtc/base/proxyinfo.h"
31#include "webrtc/base/ratetracker.h"
32#include "webrtc/base/sigslot.h"
33#include "webrtc/base/socketaddress.h"
34#include "webrtc/base/thread.h"
35
36namespace cricket {
37
38class Connection;
39class ConnectionRequest;
40
41extern const char LOCAL_PORT_TYPE[];
42extern const char STUN_PORT_TYPE[];
43extern const char PRFLX_PORT_TYPE[];
44extern const char RELAY_PORT_TYPE[];
45
46extern const char UDP_PROTOCOL_NAME[];
47extern const char TCP_PROTOCOL_NAME[];
48extern const char SSLTCP_PROTOCOL_NAME[];
hnslb68cc752016-12-13 10:33:41 -080049extern const char TLS_PROTOCOL_NAME[];
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000050
51// RFC 6544, TCP candidate encoding rules.
52extern const int DISCARD_PORT;
53extern const char TCPTYPE_ACTIVE_STR[];
54extern const char TCPTYPE_PASSIVE_STR[];
55extern const char TCPTYPE_SIMOPEN_STR[];
56
Honghai Zhang2b342bf2015-09-30 09:51:58 -070057// The minimum time we will wait before destroying a connection after creating
58// it.
honghaiz34b11eb2016-03-16 08:55:44 -070059static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070060
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080061// A connection will be declared dead if it has not received anything for this
62// long.
honghaiz34b11eb2016-03-16 08:55:44 -070063static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080064
Peter Thatcher04ac81f2015-09-21 11:48:28 -070065// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070066static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000067
68// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070069static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000070
71// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070072static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000073
74// This is the length of time that we wait for a ping response to come back.
skvlad51072462017-02-02 11:50:14 -080075// There is no harm to keep this value high other than a small amount
76// of increased memory. But in some networks (2G),
77// we observe up to 60s RTTs.
78static const int CONNECTION_RESPONSE_TIMEOUT = 60 * 1000; // 60 seconds
honghaiz34b11eb2016-03-16 08:55:44 -070079
80// The number of pings that must fail to respond before we become unwritable.
81static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000082
83enum RelayType {
84 RELAY_GTURN, // Legacy google relay service.
85 RELAY_TURN // Standard (TURN) relay service.
86};
87
88enum IcePriorityValue {
hnsl277b2502016-12-13 05:17:23 -080089 ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
90 ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
91 ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
Taylor Brandstetter62351c92016-08-11 16:05:07 -070092 ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000093 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
94 ICE_TYPE_PREFERENCE_SRFLX = 100,
95 ICE_TYPE_PREFERENCE_PRFLX = 110,
96 ICE_TYPE_PREFERENCE_HOST = 126
97};
98
hbos06495bc2017-01-02 08:08:18 -080099// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
100enum class IceCandidatePairState {
101 WAITING = 0, // Check has not been performed, Waiting pair on CL.
102 IN_PROGRESS, // Check has been sent, transaction is in progress.
103 SUCCEEDED, // Check already done, produced a successful result.
104 FAILED, // Check for this connection failed.
105 // According to spec there should also be a frozen state, but nothing is ever
106 // frozen because we have not implemented ICE freezing logic.
107};
108
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000109const char* ProtoToString(ProtocolType proto);
110bool StringToProto(const char* value, ProtocolType* proto);
111
112struct ProtocolAddress {
113 rtc::SocketAddress address;
114 ProtocolType proto;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000115
116 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
hnsl277b2502016-12-13 05:17:23 -0800117 : address(a), proto(p) {}
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700118
119 bool operator==(const ProtocolAddress& o) const {
hnsl277b2502016-12-13 05:17:23 -0800120 return address == o.address && proto == o.proto;
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700121 }
122 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000123};
124
125typedef std::set<rtc::SocketAddress> ServerAddresses;
126
127// Represents a local communication mechanism that can be used to create
128// connections to similar mechanisms of the other client. Subclasses of this
129// one add support for specific mechanisms like local UDP ports.
130class Port : public PortInterface, public rtc::MessageHandler,
131 public sigslot::has_slots<> {
132 public:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700133 // INIT: The state when a port is just created.
134 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
135 // connection is using it.
136 // PRUNED: It will be destroyed if no connection is using it for a period of
137 // 30 seconds.
138 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000139 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 09:44:47 -0700140 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000141 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000142 rtc::Network* network,
143 const rtc::IPAddress& ip,
144 const std::string& username_fragment,
145 const std::string& password);
146 Port(rtc::Thread* thread,
147 const std::string& type,
148 rtc::PacketSocketFactory* factory,
149 rtc::Network* network,
150 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200151 uint16_t min_port,
152 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000153 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000154 const std::string& password);
155 virtual ~Port();
156
157 virtual const std::string& Type() const { return type_; }
158 virtual rtc::Network* Network() const { return network_; }
159
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000160 // Methods to set/get ICE role and tiebreaker values.
161 IceRole GetIceRole() const { return ice_role_; }
162 void SetIceRole(IceRole role) { ice_role_ = role; }
163
Peter Boström0c4e06b2015-10-07 12:23:21 +0200164 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
165 uint64_t IceTiebreaker() const { return tiebreaker_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000166
167 virtual bool SharedSocket() const { return shared_socket_; }
168 void ResetSharedSocket() { shared_socket_ = false; }
169
Honghai Zhanga74363c2016-07-28 18:06:15 -0700170 // Should not destroy the port even if no connection is using it. Called when
171 // a port is ready to use.
172 void KeepAliveUntilPruned();
173 // Allows a port to be destroyed if no connection is using it.
174 void Prune();
175
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000176 // The thread on which this port performs its I/O.
177 rtc::Thread* thread() { return thread_; }
178
179 // The factory used to create the sockets of this port.
180 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
181 void set_socket_factory(rtc::PacketSocketFactory* factory) {
182 factory_ = factory;
183 }
184
185 // For debugging purposes.
186 const std::string& content_name() const { return content_name_; }
187 void set_content_name(const std::string& content_name) {
188 content_name_ = content_name;
189 }
190
191 int component() const { return component_; }
192 void set_component(int component) { component_ = component; }
193
194 bool send_retransmit_count_attribute() const {
195 return send_retransmit_count_attribute_;
196 }
197 void set_send_retransmit_count_attribute(bool enable) {
198 send_retransmit_count_attribute_ = enable;
199 }
200
201 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-22 17:14:15 -0700202 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200203 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000204
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000205 const std::string username_fragment() const;
206 const std::string& password() const { return password_; }
207
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700208 // May be called when this port was initially created by a pooled
209 // PortAllocatorSession, and is now being assigned to an ICE transport.
210 // Updates the information for candidates as well.
211 void SetIceParameters(int component,
212 const std::string& username_fragment,
213 const std::string& password);
214
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000215 // Fired when candidates are discovered by the port. When all candidates
216 // are discovered that belong to port SignalAddressReady is fired.
217 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
218
219 // Provides all of the above information in one handy object.
220 virtual const std::vector<Candidate>& Candidates() const {
221 return candidates_;
222 }
223
224 // SignalPortComplete is sent when port completes the task of candidates
225 // allocation.
226 sigslot::signal1<Port*> SignalPortComplete;
227 // This signal sent when port fails to allocate candidates and this port
228 // can't be used in establishing the connections. When port is in shared mode
229 // and port fails to allocate one of the candidates, port shouldn't send
230 // this signal as other candidates might be usefull in establishing the
231 // connection.
232 sigslot::signal1<Port*> SignalPortError;
233
234 // Returns a map containing all of the connections of this port, keyed by the
235 // remote address.
236 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
237 const AddressMap& connections() { return connections_; }
238
239 // Returns the connection to the given address or NULL if none exists.
240 virtual Connection* GetConnection(
241 const rtc::SocketAddress& remote_addr);
242
243 // Called each time a connection is created.
244 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
245
246 // In a shared socket mode each port which shares the socket will decide
247 // to accept the packet based on the |remote_addr|. Currently only UDP
248 // port implemented this method.
249 // TODO(mallinath) - Make it pure virtual.
250 virtual bool HandleIncomingPacket(
251 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
252 const rtc::SocketAddress& remote_addr,
253 const rtc::PacketTime& packet_time) {
nissec80e7412017-01-11 05:56:46 -0800254 RTC_NOTREACHED();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000255 return false;
256 }
257
258 // Sends a response message (normal or error) to the given request. One of
259 // these methods should be called as a response to SignalUnknownAddress.
260 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
261 virtual void SendBindingResponse(StunMessage* request,
262 const rtc::SocketAddress& addr);
263 virtual void SendBindingErrorResponse(
264 StunMessage* request, const rtc::SocketAddress& addr,
265 int error_code, const std::string& reason);
266
267 void set_proxy(const std::string& user_agent,
268 const rtc::ProxyInfo& proxy) {
269 user_agent_ = user_agent;
270 proxy_ = proxy;
271 }
272 const std::string& user_agent() { return user_agent_; }
273 const rtc::ProxyInfo& proxy() { return proxy_; }
274
275 virtual void EnablePortPackets();
276
277 // Called if the port has no connections and is no longer useful.
278 void Destroy();
279
280 virtual void OnMessage(rtc::Message *pmsg);
281
282 // Debugging description of this port
283 virtual std::string ToString() const;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000284 const rtc::IPAddress& ip() const { return ip_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200285 uint16_t min_port() { return min_port_; }
286 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000287
288 // Timeout shortening function to speed up unit tests.
289 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
290
291 // This method will return local and remote username fragements from the
292 // stun username attribute if present.
293 bool ParseStunUsername(const StunMessage* stun_msg,
294 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700295 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000296 void CreateStunUsername(const std::string& remote_username,
297 std::string* stun_username_attr_str) const;
298
299 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
300 IceMessage* stun_msg,
301 const std::string& remote_ufrag);
302
stefanc1aeaf02015-10-15 07:26:07 -0700303 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100304 // This is made pure virtual to notify subclasses of Port that they MUST
305 // listen to AsyncPacketSocket::SignalSentPacket and then call
306 // PortInterface::OnSentPacket.
307 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
308 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700309
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000310 // Called when the socket is currently able to send.
311 void OnReadyToSend();
312
313 // Called when the Connection discovers a local peer reflexive candidate.
314 // Returns the index of the new local candidate.
315 size_t AddPrflxCandidate(const Candidate& local);
316
honghaiza0c44ea2016-03-23 16:07:48 -0700317 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000318
319 protected:
Honghai Zhanga74363c2016-07-28 18:06:15 -0700320 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321
Honghai Zhang351d77b2016-05-20 15:08:29 -0700322 virtual void UpdateNetworkCost();
323
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000324 void set_type(const std::string& type) { type_ = type; }
325
Peter Boström2758c662017-02-13 20:33:27 -0500326 // Deprecated. Use the AddAddress() method below with "url" instead.
327 // TODO(zhihuang): Remove this after downstream applications stop using it.
328 void AddAddress(const rtc::SocketAddress& address,
329 const rtc::SocketAddress& base_address,
330 const rtc::SocketAddress& related_address,
331 const std::string& protocol,
332 const std::string& relay_protocol,
333 const std::string& tcptype,
334 const std::string& type,
335 uint32_t type_preference,
336 uint32_t relay_preference,
337 bool final);
338
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 void AddAddress(const rtc::SocketAddress& address,
340 const rtc::SocketAddress& base_address,
341 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700342 const std::string& protocol,
343 const std::string& relay_protocol,
344 const std::string& tcptype,
345 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200346 uint32_t type_preference,
347 uint32_t relay_preference,
zhihuang26d99c22017-02-13 12:47:27 -0800348 const std::string& url,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700349 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000350
honghaiz36f50e82016-06-01 15:57:03 -0700351 // Adds the given connection to the map keyed by the remote candidate address.
352 // If an existing connection has the same address, the existing one will be
353 // replaced and destroyed.
354 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000355
356 // Called when a packet is received from an unknown address that is not
357 // currently a connection. If this is an authenticated STUN binding request,
358 // then we will signal the client.
359 void OnReadPacket(const char* data, size_t size,
360 const rtc::SocketAddress& addr,
361 ProtocolType proto);
362
363 // If the given data comprises a complete and correct STUN message then the
364 // return value is true, otherwise false. If the message username corresponds
365 // with this port's username fragment, msg will contain the parsed STUN
366 // message. Otherwise, the function may send a STUN response internally.
367 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700368 bool GetStunMessage(const char* data,
369 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000370 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700371 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700372 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000373
374 // Checks if the address in addr is compatible with the port's ip.
375 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
376
377 // Returns default DSCP value.
378 rtc::DiffServCodePoint DefaultDscpValue() const {
379 // No change from what MediaChannel set.
380 return rtc::DSCP_NO_CHANGE;
381 }
382
honghaiz36f50e82016-06-01 15:57:03 -0700383 // Extra work to be done in subclasses when a connection is destroyed.
384 virtual void HandleConnectionDestroyed(Connection* conn) {}
385
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000386 private:
387 void Construct();
388 // Called when one of our connections deletes itself.
389 void OnConnectionDestroyed(Connection* conn);
390
Honghai Zhang351d77b2016-05-20 15:08:29 -0700391 void OnNetworkTypeChanged(const rtc::Network* network);
392
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000393 rtc::Thread* thread_;
394 rtc::PacketSocketFactory* factory_;
395 std::string type_;
396 bool send_retransmit_count_attribute_;
397 rtc::Network* network_;
398 rtc::IPAddress ip_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200399 uint16_t min_port_;
400 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000401 std::string content_name_;
402 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200403 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404 // In order to establish a connection to this Port (so that real data can be
405 // sent through), the other side must send us a STUN binding request that is
406 // authenticated with this username_fragment and password.
407 // PortAllocatorSession will provide these username_fragment and password.
408 //
409 // Note: we should always use username_fragment() instead of using
410 // |ice_username_fragment_| directly. For the details see the comment on
411 // username_fragment().
412 std::string ice_username_fragment_;
413 std::string password_;
414 std::vector<Candidate> candidates_;
415 AddressMap connections_;
416 int timeout_delay_;
417 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200419 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000420 bool shared_socket_;
421 // Information to use when going through a proxy.
422 std::string user_agent_;
423 rtc::ProxyInfo proxy_;
424
honghaize1a0c942016-02-16 14:54:56 -0800425 // A virtual cost perceived by the user, usually based on the network type
426 // (WiFi. vs. Cellular). It takes precedence over the priority when
427 // comparing two connections.
honghaiza0c44ea2016-03-23 16:07:48 -0700428 uint16_t network_cost_;
Honghai Zhanga74363c2016-07-28 18:06:15 -0700429 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 13:23:05 -0700430 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 14:54:56 -0800431
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000432 friend class Connection;
433};
434
435// Represents a communication link between a port on the local client and a
436// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700437class Connection : public CandidatePairInterface,
438 public rtc::MessageHandler,
439 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000440 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700441 struct SentPing {
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700442 SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
443 : id(id), sent_time(sent_time), nomination(nomination) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700444
445 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700446 int64_t sent_time;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700447 uint32_t nomination;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700448 };
449
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 virtual ~Connection();
451
452 // The local port where this connection sends and receives packets.
453 Port* port() { return port_; }
454 const Port* port() const { return port_; }
455
Honghai Zhangcc411c02016-03-29 17:27:21 -0700456 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000457 // Returns the description of the local port
458 virtual const Candidate& local_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000459 // Returns the description of the remote port to which we communicate.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700460 virtual const Candidate& remote_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000461
462 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200463 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000464
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000465 enum WriteState {
466 STATE_WRITABLE = 0, // we have received ping responses recently
467 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
468 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
469 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
470 };
471
472 WriteState write_state() const { return write_state_; }
473 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700474 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000475
476 // Determines whether the connection has finished connecting. This can only
477 // be false for TCP connections.
478 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700479 bool weak() const { return !(writable() && receiving() && connected()); }
480 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700481 return write_state_ != STATE_WRITE_TIMEOUT;
482 }
honghaiz059e1832016-06-24 11:03:55 -0700483
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700484 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700485 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700486
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000487 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700488 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000489
hbos06495bc2017-01-02 08:08:18 -0800490 // Gets the |ConnectionInfo| stats, where |best_connection| has not been
491 // populated (default value false).
zhihuang5ecf16c2016-06-01 17:09:15 -0700492 ConnectionInfo stats();
493
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000494 sigslot::signal1<Connection*> SignalStateChange;
495
496 // Sent when the connection has decided that it is no longer of value. It
497 // will delete itself immediately after this call.
498 sigslot::signal1<Connection*> SignalDestroyed;
499
500 // The connection can send and receive packets asynchronously. This matches
501 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
502 // covers.
503 virtual int Send(const void* data, size_t size,
504 const rtc::PacketOptions& options) = 0;
505
506 // Error if Send() returns < 0
507 virtual int GetError() = 0;
508
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700509 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
510 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000511
512 sigslot::signal1<Connection*> SignalReadyToSend;
513
514 // Called when a packet is received on this connection.
515 void OnReadPacket(const char* data, size_t size,
516 const rtc::PacketTime& packet_time);
517
518 // Called when the socket is currently able to send.
519 void OnReadyToSend();
520
521 // Called when a connection is determined to be no longer useful to us. We
522 // still keep it around in case the other side wants to use it. But we can
523 // safely stop pinging on it and we can allow it to time out if the other
524 // side stops using it as well.
525 bool pruned() const { return pruned_; }
526 void Prune();
527
528 bool use_candidate_attr() const { return use_candidate_attr_; }
529 void set_use_candidate_attr(bool enable);
530
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700531 void set_nomination(uint32_t value) { nomination_ = value; }
532
533 uint32_t remote_nomination() const { return remote_nomination_; }
hbos92eaec62017-02-27 01:38:08 -0800534 // One or several pairs may be nominated based on if Regular or Aggressive
535 // Nomination is used. https://tools.ietf.org/html/rfc5245#section-8
536 // |nominated| is defined both for the controlling or controlled agent based
537 // on if a nomination has been pinged or acknowledged. The controlled agent
538 // gets its |remote_nomination_| set when pinged by the controlling agent with
539 // a nomination value. The controlling agent gets its |acked_nomination_| set
540 // when receiving a response to a nominating ping.
541 bool nominated() const { return acked_nomination_ || remote_nomination_; }
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700542 // Public for unit tests.
543 void set_remote_nomination(uint32_t remote_nomination) {
544 remote_nomination_ = remote_nomination;
545 }
546 // Public for unit tests.
547 uint32_t acked_nomination() const { return acked_nomination_; }
honghaiz5a3acd82015-08-20 15:53:17 -0700548
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000549 void set_remote_ice_mode(IceMode mode) {
550 remote_ice_mode_ = mode;
551 }
552
bertholdherrmann0812030662016-10-18 14:00:02 -0700553 void set_receiving_timeout(int receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700554 receiving_timeout_ = receiving_timeout_ms;
555 }
556
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000557 // Makes the connection go away.
558 void Destroy();
559
deadbeef376e1232015-11-25 09:00:08 -0800560 // Makes the connection go away, in a failed state.
561 void FailAndDestroy();
562
honghaiz079a7a12016-06-22 16:26:29 -0700563 // Prunes the connection and sets its state to STATE_FAILED,
564 // It will not be used or send pings although it can still receive packets.
565 void FailAndPrune();
566
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000567 // Checks that the state of this connection is up-to-date. The argument is
568 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700569 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000570
571 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700572 int64_t last_ping_sent() const { return last_ping_sent_; }
573 void Ping(int64_t now);
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700574 void ReceivedPingResponse(int rtt, const std::string& request_id);
honghaiz34b11eb2016-03-16 08:55:44 -0700575 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800576 return last_ping_response_received_;
577 }
Honghai Zhangfd16da22016-08-17 16:12:46 -0700578 // Used to check if any STUN ping response has been received.
579 int rtt_samples() const { return rtt_samples_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000580
581 // Called whenever a valid ping is received on this connection. This is
582 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700583 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000584 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800585 // Handles the binding request; sends a response if this is a valid request.
586 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000587
Honghai Zhang572b0942016-06-23 12:26:57 -0700588 int64_t last_data_received() const { return last_data_received_; }
589
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000590 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000591 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000592 std::string ToString() const;
593 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700594 // Prints pings_since_last_response_ into a string.
595 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000596
597 bool reported() const { return reported_; }
598 void set_reported(bool reported) { reported_ = reported;}
599
honghaiz5a3acd82015-08-20 15:53:17 -0700600 // This signal will be fired if this connection is nominated by the
601 // controlling side.
602 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700603
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000604 // Invoked when Connection receives STUN error response with 487 code.
605 void HandleRoleConflictFromPeer();
606
hbos06495bc2017-01-02 08:08:18 -0800607 IceCandidatePairState state() const { return state_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608
honghaiz524ecc22016-05-25 12:48:31 -0700609 int num_pings_sent() const { return num_pings_sent_; }
610
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000611 IceMode remote_ice_mode() const { return remote_ice_mode_; }
612
honghaize1a0c942016-02-16 14:54:56 -0800613 uint32_t ComputeNetworkCost() const;
614
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700615 // Update the ICE password and/or generation of the remote candidate if the
616 // ufrag in |params| matches the candidate's ufrag, and the
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700617 // candidate's password and/or ufrag has not been set.
Honghai Zhang4cedf2b2016-08-31 08:18:11 -0700618 void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
619 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000620
621 // If |remote_candidate_| is peer reflexive and is equivalent to
622 // |new_candidate| except the type, update |remote_candidate_| to
623 // |new_candidate|.
624 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
625
Peter Thatcher54360512015-07-08 11:08:35 -0700626 // Returns the last received time of any data, stun request, or stun
627 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700628 int64_t last_received() const;
honghaiz9ad0db52016-07-14 19:30:28 -0700629 // Returns the last time when the connection changed its receiving state.
630 int64_t receiving_unchanged_since() const {
631 return receiving_unchanged_since_;
632 }
Peter Thatcher54360512015-07-08 11:08:35 -0700633
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700634 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700635
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700637 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
638
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000639 // Constructs a new connection to the given remote port.
640 Connection(Port* port, size_t index, const Candidate& candidate);
641
642 // Called back when StunRequestManager has a stun packet to send
643 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
644
645 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700646 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
647 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000648 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
649 StunMessage* response);
650 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700651 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000652
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700653 bool rtt_converged() const;
zhihuang435264a2016-06-21 11:28:38 -0700654
655 // If the response is not received within 2 * RTT, the response is assumed to
656 // be missing.
Taylor Brandstetterb825aee2016-06-29 13:07:16 -0700657 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 11:28:38 -0700658
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000659 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-14 19:30:28 -0700661 void UpdateReceiving(int64_t now);
hbos06495bc2017-01-02 08:08:18 -0800662 void set_state(IceCandidatePairState state);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000663 void set_connected(bool value);
664
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700665 uint32_t nomination() const { return nomination_; }
666
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000667 void OnMessage(rtc::Message *pmsg);
668
669 Port* port_;
670 size_t local_candidate_index_;
671 Candidate remote_candidate_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700672
673 ConnectionInfo stats_;
674 rtc::RateTracker recv_rate_tracker_;
675 rtc::RateTracker send_rate_tracker_;
676
677 private:
Taylor Brandstetter62351c92016-08-11 16:05:07 -0700678 // Update the local candidate based on the mapped address attribute.
679 // If the local candidate changed, fires SignalStateChange.
680 void MaybeUpdateLocalCandidate(ConnectionRequest* request,
681 StunMessage* response);
682
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000683 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700684 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000685 bool connected_;
686 bool pruned_;
687 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700688 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000689 // But when peer is ice-lite, this flag "must" be initialized to false and
690 // turn on when connection becomes "best connection".
691 bool use_candidate_attr_;
Honghai Zhang8cd8f812016-08-03 19:50:41 -0700692 // Used by the controlling side to indicate that this connection will be
693 // selected for transmission if the peer supports ICE-renomination when this
694 // value is positive. A larger-value indicates that a connection is nominated
695 // later and should be selected by the controlled side with higher precedence.
696 // A zero-value indicates not nominating this connection.
697 uint32_t nomination_ = 0;
698 // The last nomination that has been acknowledged.
699 uint32_t acked_nomination_ = 0;
700 // Used by the controlled side to remember the nomination value received from
701 // the controlling side. When the peer does not support ICE re-nomination,
702 // its value will be 1 if the connection has been nominated.
703 uint32_t remote_nomination_ = 0;
704
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000705 IceMode remote_ice_mode_;
706 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700707 int rtt_;
zhihuang435264a2016-06-21 11:28:38 -0700708 int rtt_samples_ = 0;
honghaiz34b11eb2016-03-16 08:55:44 -0700709 int64_t last_ping_sent_; // last time we sent a ping to the other side
710 int64_t last_ping_received_; // last time we received a ping from the other
711 // side
712 int64_t last_data_received_;
713 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-14 19:30:28 -0700714 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700715 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000716
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000717 bool reported_;
hbos06495bc2017-01-02 08:08:18 -0800718 IceCandidatePairState state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700719 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700720 int receiving_timeout_;
721 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 12:48:31 -0700722 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000723
724 friend class Port;
725 friend class ConnectionRequest;
726};
727
deadbeef376e1232015-11-25 09:00:08 -0800728// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000729class ProxyConnection : public Connection {
730 public:
deadbeef376e1232015-11-25 09:00:08 -0800731 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000732
deadbeef376e1232015-11-25 09:00:08 -0800733 int Send(const void* data,
734 size_t size,
735 const rtc::PacketOptions& options) override;
736 int GetError() override { return error_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000737
738 private:
deadbeef376e1232015-11-25 09:00:08 -0800739 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000740};
741
742} // namespace cricket
743
744#endif // WEBRTC_P2P_BASE_PORT_H_