blob: 7ec33bcd0b18169f22998026ee4bd19d37be8830 [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef WEBRTC_P2P_BASE_PORT_H_
12#define WEBRTC_P2P_BASE_PORT_H_
13
14#include <map>
kwiberg3ec46792016-04-27 07:22:53 -070015#include <memory>
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000016#include <set>
17#include <string>
18#include <vector>
19
20#include "webrtc/p2p/base/candidate.h"
Honghai Zhangcc411c02016-03-29 17:27:21 -070021#include "webrtc/p2p/base/candidatepairinterface.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000022#include "webrtc/p2p/base/packetsocketfactory.h"
23#include "webrtc/p2p/base/portinterface.h"
24#include "webrtc/p2p/base/stun.h"
25#include "webrtc/p2p/base/stunrequest.h"
26#include "webrtc/p2p/base/transport.h"
27#include "webrtc/base/asyncpacketsocket.h"
28#include "webrtc/base/network.h"
29#include "webrtc/base/proxyinfo.h"
30#include "webrtc/base/ratetracker.h"
31#include "webrtc/base/sigslot.h"
32#include "webrtc/base/socketaddress.h"
33#include "webrtc/base/thread.h"
34
35namespace cricket {
36
37class Connection;
38class ConnectionRequest;
39
40extern const char LOCAL_PORT_TYPE[];
41extern const char STUN_PORT_TYPE[];
42extern const char PRFLX_PORT_TYPE[];
43extern const char RELAY_PORT_TYPE[];
44
45extern const char UDP_PROTOCOL_NAME[];
46extern const char TCP_PROTOCOL_NAME[];
47extern const char SSLTCP_PROTOCOL_NAME[];
48
49// RFC 6544, TCP candidate encoding rules.
50extern const int DISCARD_PORT;
51extern const char TCPTYPE_ACTIVE_STR[];
52extern const char TCPTYPE_PASSIVE_STR[];
53extern const char TCPTYPE_SIMOPEN_STR[];
54
Honghai Zhang2b342bf2015-09-30 09:51:58 -070055// The minimum time we will wait before destroying a connection after creating
56// it.
honghaiz34b11eb2016-03-16 08:55:44 -070057static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 11:48:28 -070058
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080059// A connection will be declared dead if it has not received anything for this
60// long.
honghaiz34b11eb2016-03-16 08:55:44 -070061static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 11:14:33 -080062
Peter Thatcher04ac81f2015-09-21 11:48:28 -070063// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 08:55:44 -070064static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000065
66// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 08:55:44 -070067static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000068
69// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 08:55:44 -070070static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000071
72// This is the length of time that we wait for a ping response to come back.
honghaiz34b11eb2016-03-16 08:55:44 -070073static const int CONNECTION_RESPONSE_TIMEOUT = 5 * 1000; // 5 seconds
74
75// The number of pings that must fail to respond before we become unwritable.
76static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +000077
78enum RelayType {
79 RELAY_GTURN, // Legacy google relay service.
80 RELAY_TURN // Standard (TURN) relay service.
81};
82
83enum IcePriorityValue {
84 // The reason we are choosing Relay preference 2 is because, we can run
85 // Relay from client to server on UDP/TCP/TLS. To distinguish the transport
86 // protocol, we prefer UDP over TCP over TLS.
87 // For UDP ICE_TYPE_PREFERENCE_RELAY will be 2.
88 // For TCP ICE_TYPE_PREFERENCE_RELAY will be 1.
89 // For TLS ICE_TYPE_PREFERENCE_RELAY will be 0.
90 // Check turnport.cc for setting these values.
91 ICE_TYPE_PREFERENCE_RELAY = 2,
92 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
93 ICE_TYPE_PREFERENCE_SRFLX = 100,
94 ICE_TYPE_PREFERENCE_PRFLX = 110,
95 ICE_TYPE_PREFERENCE_HOST = 126
96};
97
98const char* ProtoToString(ProtocolType proto);
99bool StringToProto(const char* value, ProtocolType* proto);
100
101struct ProtocolAddress {
102 rtc::SocketAddress address;
103 ProtocolType proto;
104 bool secure;
105
106 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
107 : address(a), proto(p), secure(false) { }
108 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p, bool sec)
109 : address(a), proto(p), secure(sec) { }
110};
111
112typedef std::set<rtc::SocketAddress> ServerAddresses;
113
114// Represents a local communication mechanism that can be used to create
115// connections to similar mechanisms of the other client. Subclasses of this
116// one add support for specific mechanisms like local UDP ports.
117class Port : public PortInterface, public rtc::MessageHandler,
118 public sigslot::has_slots<> {
119 public:
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000120 Port(rtc::Thread* thread,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000121 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000122 rtc::Network* network,
123 const rtc::IPAddress& ip,
124 const std::string& username_fragment,
125 const std::string& password);
126 Port(rtc::Thread* thread,
127 const std::string& type,
128 rtc::PacketSocketFactory* factory,
129 rtc::Network* network,
130 const rtc::IPAddress& ip,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200131 uint16_t min_port,
132 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22 +0000133 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000134 const std::string& password);
135 virtual ~Port();
136
137 virtual const std::string& Type() const { return type_; }
138 virtual rtc::Network* Network() const { return network_; }
139
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000140 // Methods to set/get ICE role and tiebreaker values.
141 IceRole GetIceRole() const { return ice_role_; }
142 void SetIceRole(IceRole role) { ice_role_ = role; }
143
Peter Boström0c4e06b2015-10-07 12:23:21 +0200144 void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
145 uint64_t IceTiebreaker() const { return tiebreaker_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000146
147 virtual bool SharedSocket() const { return shared_socket_; }
148 void ResetSharedSocket() { shared_socket_ = false; }
149
150 // The thread on which this port performs its I/O.
151 rtc::Thread* thread() { return thread_; }
152
153 // The factory used to create the sockets of this port.
154 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
155 void set_socket_factory(rtc::PacketSocketFactory* factory) {
156 factory_ = factory;
157 }
158
159 // For debugging purposes.
160 const std::string& content_name() const { return content_name_; }
161 void set_content_name(const std::string& content_name) {
162 content_name_ = content_name;
163 }
164
165 int component() const { return component_; }
166 void set_component(int component) { component_ = component; }
167
168 bool send_retransmit_count_attribute() const {
169 return send_retransmit_count_attribute_;
170 }
171 void set_send_retransmit_count_attribute(bool enable) {
172 send_retransmit_count_attribute_ = enable;
173 }
174
175 // Identifies the generation that this port was created in.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200176 uint32_t generation() { return generation_; }
177 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000178
179 // ICE requires a single username/password per content/media line. So the
180 // |ice_username_fragment_| of the ports that belongs to the same content will
181 // be the same. However this causes a small complication with our relay
182 // server, which expects different username for RTP and RTCP.
183 //
184 // To resolve this problem, we implemented the username_fragment(),
185 // which returns a different username (calculated from
186 // |ice_username_fragment_|) for RTCP in the case of ICEPROTO_GOOGLE. And the
187 // username_fragment() simply returns |ice_username_fragment_| when running
188 // in ICEPROTO_RFC5245.
189 //
190 // As a result the ICEPROTO_GOOGLE will use different usernames for RTP and
191 // RTCP. And the ICEPROTO_RFC5245 will use same username for both RTP and
192 // RTCP.
193 const std::string username_fragment() const;
194 const std::string& password() const { return password_; }
195
196 // Fired when candidates are discovered by the port. When all candidates
197 // are discovered that belong to port SignalAddressReady is fired.
198 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
199
200 // Provides all of the above information in one handy object.
201 virtual const std::vector<Candidate>& Candidates() const {
202 return candidates_;
203 }
204
205 // SignalPortComplete is sent when port completes the task of candidates
206 // allocation.
207 sigslot::signal1<Port*> SignalPortComplete;
208 // This signal sent when port fails to allocate candidates and this port
209 // can't be used in establishing the connections. When port is in shared mode
210 // and port fails to allocate one of the candidates, port shouldn't send
211 // this signal as other candidates might be usefull in establishing the
212 // connection.
213 sigslot::signal1<Port*> SignalPortError;
214
215 // Returns a map containing all of the connections of this port, keyed by the
216 // remote address.
217 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
218 const AddressMap& connections() { return connections_; }
219
220 // Returns the connection to the given address or NULL if none exists.
221 virtual Connection* GetConnection(
222 const rtc::SocketAddress& remote_addr);
223
224 // Called each time a connection is created.
225 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
226
227 // In a shared socket mode each port which shares the socket will decide
228 // to accept the packet based on the |remote_addr|. Currently only UDP
229 // port implemented this method.
230 // TODO(mallinath) - Make it pure virtual.
231 virtual bool HandleIncomingPacket(
232 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
233 const rtc::SocketAddress& remote_addr,
234 const rtc::PacketTime& packet_time) {
235 ASSERT(false);
236 return false;
237 }
238
239 // Sends a response message (normal or error) to the given request. One of
240 // these methods should be called as a response to SignalUnknownAddress.
241 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
242 virtual void SendBindingResponse(StunMessage* request,
243 const rtc::SocketAddress& addr);
244 virtual void SendBindingErrorResponse(
245 StunMessage* request, const rtc::SocketAddress& addr,
246 int error_code, const std::string& reason);
247
248 void set_proxy(const std::string& user_agent,
249 const rtc::ProxyInfo& proxy) {
250 user_agent_ = user_agent;
251 proxy_ = proxy;
252 }
253 const std::string& user_agent() { return user_agent_; }
254 const rtc::ProxyInfo& proxy() { return proxy_; }
255
256 virtual void EnablePortPackets();
257
258 // Called if the port has no connections and is no longer useful.
259 void Destroy();
260
261 virtual void OnMessage(rtc::Message *pmsg);
262
263 // Debugging description of this port
264 virtual std::string ToString() const;
pthatcher@webrtc.org0ba15332015-01-10 00:47:02 +0000265 const rtc::IPAddress& ip() const { return ip_; }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200266 uint16_t min_port() { return min_port_; }
267 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000268
269 // Timeout shortening function to speed up unit tests.
270 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
271
272 // This method will return local and remote username fragements from the
273 // stun username attribute if present.
274 bool ParseStunUsername(const StunMessage* stun_msg,
275 std::string* local_username,
Peter Thatcher7cbd1882015-09-17 18:54:52 -0700276 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000277 void CreateStunUsername(const std::string& remote_username,
278 std::string* stun_username_attr_str) const;
279
280 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
281 IceMessage* stun_msg,
282 const std::string& remote_ufrag);
283
stefanc1aeaf02015-10-15 07:26:07 -0700284 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 15:49:16 +0100285 // This is made pure virtual to notify subclasses of Port that they MUST
286 // listen to AsyncPacketSocket::SignalSentPacket and then call
287 // PortInterface::OnSentPacket.
288 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
289 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 07:26:07 -0700290
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000291 // Called when the socket is currently able to send.
292 void OnReadyToSend();
293
294 // Called when the Connection discovers a local peer reflexive candidate.
295 // Returns the index of the new local candidate.
296 size_t AddPrflxCandidate(const Candidate& local);
297
Peter Boström0c4e06b2015-10-07 12:23:21 +0200298 void set_candidate_filter(uint32_t candidate_filter) {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000299 candidate_filter_ = candidate_filter;
300 }
honghaiza0c44ea2016-03-23 16:07:48 -0700301 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000302
303 protected:
304 enum {
honghaizd0b31432015-09-30 12:42:17 -0700305 MSG_DEAD = 0,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000306 MSG_FIRST_AVAILABLE
307 };
308
309 void set_type(const std::string& type) { type_ = type; }
310
311 void AddAddress(const rtc::SocketAddress& address,
312 const rtc::SocketAddress& base_address,
313 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700314 const std::string& protocol,
315 const std::string& relay_protocol,
316 const std::string& tcptype,
317 const std::string& type,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200318 uint32_t type_preference,
319 uint32_t relay_preference,
Guo-wei Shieh3d564c12015-08-19 16:51:15 -0700320 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000321
322 // Adds the given connection to the list. (Deleting removes them.)
323 void AddConnection(Connection* conn);
324
325 // Called when a packet is received from an unknown address that is not
326 // currently a connection. If this is an authenticated STUN binding request,
327 // then we will signal the client.
328 void OnReadPacket(const char* data, size_t size,
329 const rtc::SocketAddress& addr,
330 ProtocolType proto);
331
332 // If the given data comprises a complete and correct STUN message then the
333 // return value is true, otherwise false. If the message username corresponds
334 // with this port's username fragment, msg will contain the parsed STUN
335 // message. Otherwise, the function may send a STUN response internally.
336 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 11:09:39 -0700337 bool GetStunMessage(const char* data,
338 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000339 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 07:22:53 -0700340 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 11:09:39 -0700341 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000342
343 // Checks if the address in addr is compatible with the port's ip.
344 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
345
346 // Returns default DSCP value.
347 rtc::DiffServCodePoint DefaultDscpValue() const {
348 // No change from what MediaChannel set.
349 return rtc::DSCP_NO_CHANGE;
350 }
351
Peter Boström0c4e06b2015-10-07 12:23:21 +0200352 uint32_t candidate_filter() { return candidate_filter_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000353
354 private:
355 void Construct();
356 // Called when one of our connections deletes itself.
357 void OnConnectionDestroyed(Connection* conn);
358
honghaizd0b31432015-09-30 12:42:17 -0700359 // Whether this port is dead, and hence, should be destroyed on the controlled
360 // side.
361 bool dead() const {
362 return ice_role_ == ICEROLE_CONTROLLED && connections_.empty();
363 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000364
honghaize3c6c822016-02-17 13:00:28 -0800365 void OnNetworkInactive(const rtc::Network* network);
366
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000367 rtc::Thread* thread_;
368 rtc::PacketSocketFactory* factory_;
369 std::string type_;
370 bool send_retransmit_count_attribute_;
371 rtc::Network* network_;
372 rtc::IPAddress ip_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200373 uint16_t min_port_;
374 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000375 std::string content_name_;
376 int component_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200377 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000378 // In order to establish a connection to this Port (so that real data can be
379 // sent through), the other side must send us a STUN binding request that is
380 // authenticated with this username_fragment and password.
381 // PortAllocatorSession will provide these username_fragment and password.
382 //
383 // Note: we should always use username_fragment() instead of using
384 // |ice_username_fragment_| directly. For the details see the comment on
385 // username_fragment().
386 std::string ice_username_fragment_;
387 std::string password_;
388 std::vector<Candidate> candidates_;
389 AddressMap connections_;
390 int timeout_delay_;
391 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000392 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200393 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000394 bool shared_socket_;
395 // Information to use when going through a proxy.
396 std::string user_agent_;
397 rtc::ProxyInfo proxy_;
398
399 // Candidate filter is pushed down to Port such that each Port could
400 // make its own decision on how to create candidates. For example,
401 // when IceTransportsType is set to relay, both RelayPort and
402 // TurnPort will hide raddr to avoid local address leakage.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200403 uint32_t candidate_filter_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000404
honghaize1a0c942016-02-16 14:54:56 -0800405 // A virtual cost perceived by the user, usually based on the network type
406 // (WiFi. vs. Cellular). It takes precedence over the priority when
407 // comparing two connections.
honghaiza0c44ea2016-03-23 16:07:48 -0700408 uint16_t network_cost_;
honghaize1a0c942016-02-16 14:54:56 -0800409
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000410 friend class Connection;
411};
412
413// Represents a communication link between a port on the local client and a
414// port on the remote client.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700415class Connection : public CandidatePairInterface,
416 public rtc::MessageHandler,
417 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000418 public:
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700419 struct SentPing {
honghaiz34b11eb2016-03-16 08:55:44 -0700420 SentPing(const std::string id, int64_t sent_time)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200421 : id(id), sent_time(sent_time) {}
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700422
423 std::string id;
honghaiz34b11eb2016-03-16 08:55:44 -0700424 int64_t sent_time;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700425 };
426
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000427 // States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
428 enum State {
429 STATE_WAITING = 0, // Check has not been performed, Waiting pair on CL.
430 STATE_INPROGRESS, // Check has been sent, transaction is in progress.
431 STATE_SUCCEEDED, // Check already done, produced a successful result.
432 STATE_FAILED // Check for this connection failed.
433 };
434
435 virtual ~Connection();
436
437 // The local port where this connection sends and receives packets.
438 Port* port() { return port_; }
439 const Port* port() const { return port_; }
440
Honghai Zhangcc411c02016-03-29 17:27:21 -0700441 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000442 // Returns the description of the local port
443 virtual const Candidate& local_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000444 // Returns the description of the remote port to which we communicate.
Honghai Zhangcc411c02016-03-29 17:27:21 -0700445 virtual const Candidate& remote_candidate() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000446
447 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200448 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000449
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000450 enum WriteState {
451 STATE_WRITABLE = 0, // we have received ping responses recently
452 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
453 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
454 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
455 };
456
457 WriteState write_state() const { return write_state_; }
458 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700459 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000460
461 // Determines whether the connection has finished connecting. This can only
462 // be false for TCP connections.
463 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700464 bool weak() const { return !(writable() && receiving() && connected()); }
465 bool active() const {
Honghai Zhang2b342bf2015-09-30 09:51:58 -0700466 return write_state_ != STATE_WRITE_TIMEOUT;
467 }
468 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 08:55:44 -0700469 bool dead(int64_t now) const;
honghaiz89374372015-09-24 13:14:47 -0700470
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000471 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 08:55:44 -0700472 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000473
474 size_t sent_total_bytes();
475 size_t sent_bytes_second();
guoweis@webrtc.org930e0042014-11-17 19:42:14 +0000476 // Used to track how many packets are discarded in the application socket due
477 // to errors.
478 size_t sent_discarded_packets();
479 size_t sent_total_packets();
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000480 size_t recv_total_bytes();
481 size_t recv_bytes_second();
482 sigslot::signal1<Connection*> SignalStateChange;
483
484 // Sent when the connection has decided that it is no longer of value. It
485 // will delete itself immediately after this call.
486 sigslot::signal1<Connection*> SignalDestroyed;
487
488 // The connection can send and receive packets asynchronously. This matches
489 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
490 // covers.
491 virtual int Send(const void* data, size_t size,
492 const rtc::PacketOptions& options) = 0;
493
494 // Error if Send() returns < 0
495 virtual int GetError() = 0;
496
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700497 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
498 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000499
500 sigslot::signal1<Connection*> SignalReadyToSend;
501
502 // Called when a packet is received on this connection.
503 void OnReadPacket(const char* data, size_t size,
504 const rtc::PacketTime& packet_time);
505
506 // Called when the socket is currently able to send.
507 void OnReadyToSend();
508
509 // Called when a connection is determined to be no longer useful to us. We
510 // still keep it around in case the other side wants to use it. But we can
511 // safely stop pinging on it and we can allow it to time out if the other
512 // side stops using it as well.
513 bool pruned() const { return pruned_; }
514 void Prune();
515
516 bool use_candidate_attr() const { return use_candidate_attr_; }
517 void set_use_candidate_attr(bool enable);
518
honghaiz5a3acd82015-08-20 15:53:17 -0700519 bool nominated() const { return nominated_; }
520 void set_nominated(bool nominated) { nominated_ = nominated; }
521
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000522 void set_remote_ice_mode(IceMode mode) {
523 remote_ice_mode_ = mode;
524 }
525
honghaiz34b11eb2016-03-16 08:55:44 -0700526 void set_receiving_timeout(int64_t receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700527 receiving_timeout_ = receiving_timeout_ms;
528 }
529
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000530 // Makes the connection go away.
531 void Destroy();
532
deadbeef376e1232015-11-25 09:00:08 -0800533 // Makes the connection go away, in a failed state.
534 void FailAndDestroy();
535
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000536 // Checks that the state of this connection is up-to-date. The argument is
537 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 08:55:44 -0700538 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000539
540 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 08:55:44 -0700541 int64_t last_ping_sent() const { return last_ping_sent_; }
542 void Ping(int64_t now);
Peter Thatcher1fe120a2015-06-10 11:33:17 -0700543 void ReceivedPingResponse();
honghaiz34b11eb2016-03-16 08:55:44 -0700544 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 12:24:03 -0800545 return last_ping_response_received_;
546 }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000547
548 // Called whenever a valid ping is received on this connection. This is
549 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 08:55:44 -0700550 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000551 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 13:19:17 -0800552 // Handles the binding request; sends a response if this is a valid request.
553 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000554
555 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02 +0000556 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000557 std::string ToString() const;
558 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700559 // Prints pings_since_last_response_ into a string.
560 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000561
562 bool reported() const { return reported_; }
563 void set_reported(bool reported) { reported_ = reported;}
564
honghaiz5a3acd82015-08-20 15:53:17 -0700565 // This signal will be fired if this connection is nominated by the
566 // controlling side.
567 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 11:08:35 -0700568
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000569 // Invoked when Connection receives STUN error response with 487 code.
570 void HandleRoleConflictFromPeer();
571
572 State state() const { return state_; }
573
574 IceMode remote_ice_mode() const { return remote_ice_mode_; }
575
honghaize1a0c942016-02-16 14:54:56 -0800576 uint32_t ComputeNetworkCost() const;
577
Taylor Brandstetter0a1bc532016-04-19 18:03:26 -0700578 // Update the ICE password and/or generation of the remote candidate if a
579 // ufrag in |remote_ice_parameters| matches the candidate's ufrag, and the
580 // candidate's password and/or ufrag has not been set.
581 // |remote_ice_parameters| should be a list of known ICE parameters ordered
582 // by generation.
583 void MaybeSetRemoteIceCredentialsAndGeneration(const std::string& ice_ufrag,
584 const std::string& ice_pwd,
585 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34 +0000586
587 // If |remote_candidate_| is peer reflexive and is equivalent to
588 // |new_candidate| except the type, update |remote_candidate_| to
589 // |new_candidate|.
590 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
591
Peter Thatcher54360512015-07-08 11:08:35 -0700592 // Returns the last received time of any data, stun request, or stun
593 // response in milliseconds
honghaiz34b11eb2016-03-16 08:55:44 -0700594 int64_t last_received() const;
Peter Thatcher54360512015-07-08 11:08:35 -0700595
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000596 protected:
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700597 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
598
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000599 // Constructs a new connection to the given remote port.
600 Connection(Port* port, size_t index, const Candidate& candidate);
601
602 // Called back when StunRequestManager has a stun packet to send
603 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
604
605 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700606 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
607 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000608 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
609 StunMessage* response);
610 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700611 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000612
613 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000614 void set_write_state(WriteState value);
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700615 void set_receiving(bool value);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000616 void set_state(State state);
617 void set_connected(bool value);
618
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000619 void OnMessage(rtc::Message *pmsg);
620
621 Port* port_;
622 size_t local_candidate_index_;
623 Candidate remote_candidate_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000624 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700625 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000626 bool connected_;
627 bool pruned_;
628 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 15:53:17 -0700629 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000630 // But when peer is ice-lite, this flag "must" be initialized to false and
631 // turn on when connection becomes "best connection".
632 bool use_candidate_attr_;
honghaiz5a3acd82015-08-20 15:53:17 -0700633 // Whether this connection has been nominated by the controlling side via
634 // the use_candidate attribute.
635 bool nominated_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000636 IceMode remote_ice_mode_;
637 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 08:55:44 -0700638 int rtt_;
639 int64_t last_ping_sent_; // last time we sent a ping to the other side
640 int64_t last_ping_received_; // last time we received a ping from the other
641 // side
642 int64_t last_data_received_;
643 int64_t last_ping_response_received_;
Peter Thatcher1cf6f812015-05-15 10:40:45 -0700644 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000645
646 rtc::RateTracker recv_rate_tracker_;
647 rtc::RateTracker send_rate_tracker_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200648 uint32_t sent_packets_discarded_;
649 uint32_t sent_packets_total_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000650
651 private:
652 void MaybeAddPrflxCandidate(ConnectionRequest* request,
653 StunMessage* response);
654
655 bool reported_;
656 State state_;
Peter Thatcher04ac81f2015-09-21 11:48:28 -0700657 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 08:55:44 -0700658 int receiving_timeout_;
659 int64_t time_created_ms_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000660
661 friend class Port;
662 friend class ConnectionRequest;
663};
664
deadbeef376e1232015-11-25 09:00:08 -0800665// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000666class ProxyConnection : public Connection {
667 public:
deadbeef376e1232015-11-25 09:00:08 -0800668 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000669
deadbeef376e1232015-11-25 09:00:08 -0800670 int Send(const void* data,
671 size_t size,
672 const rtc::PacketOptions& options) override;
673 int GetError() override { return error_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000674
675 private:
deadbeef376e1232015-11-25 09:00:08 -0800676 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11 +0000677};
678
679} // namespace cricket
680
681#endif // WEBRTC_P2P_BASE_PORT_H_