blob: 2957fd8b742842b05ae9dd5bddb284f9c515b3df [file] [log] [blame]
henrike@webrtc.org269fb4b2014-10-28 22:20:111/*
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
Mirko Bonadei92ea95e2017-09-15 04:47:3111#ifndef P2P_BASE_PORT_H_
12#define P2P_BASE_PORT_H_
henrike@webrtc.org269fb4b2014-10-28 22:20:1113
14#include <map>
kwiberg3ec46792016-04-27 14:22:5315#include <memory>
henrike@webrtc.org269fb4b2014-10-28 22:20:1116#include <set>
17#include <string>
18#include <vector>
19
Patrik Höglunde2d6a062017-10-05 12:53:3320#include "api/candidate.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3121#include "api/optional.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3122#include "p2p/base/candidatepairinterface.h"
23#include "p2p/base/jseptransport.h"
24#include "p2p/base/packetlossestimator.h"
25#include "p2p/base/packetsocketfactory.h"
26#include "p2p/base/portinterface.h"
27#include "p2p/base/stun.h"
28#include "p2p/base/stunrequest.h"
29#include "rtc_base/asyncpacketsocket.h"
30#include "rtc_base/checks.h"
Zhi Huang942bc2e2017-11-13 21:26:0731#include "rtc_base/nethelper.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3132#include "rtc_base/network.h"
33#include "rtc_base/proxyinfo.h"
34#include "rtc_base/ratetracker.h"
35#include "rtc_base/sigslot.h"
36#include "rtc_base/socketaddress.h"
37#include "rtc_base/thread.h"
henrike@webrtc.org269fb4b2014-10-28 22:20:1138
39namespace cricket {
40
41class Connection;
42class ConnectionRequest;
43
44extern const char LOCAL_PORT_TYPE[];
45extern const char STUN_PORT_TYPE[];
46extern const char PRFLX_PORT_TYPE[];
47extern const char RELAY_PORT_TYPE[];
48
henrike@webrtc.org269fb4b2014-10-28 22:20:1149// 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 16:51:5855// The minimum time we will wait before destroying a connection after creating
56// it.
honghaiz34b11eb2016-03-16 15:55:4457static const int MIN_CONNECTION_LIFETIME = 10 * 1000; // 10 seconds.
Peter Thatcher04ac81f2015-09-21 18:48:2858
Honghai Zhang2cd7afe2015-11-12 19:14:3359// A connection will be declared dead if it has not received anything for this
60// long.
honghaiz34b11eb2016-03-16 15:55:4461static const int DEAD_CONNECTION_RECEIVE_TIMEOUT = 30 * 1000; // 30 seconds.
Honghai Zhang2cd7afe2015-11-12 19:14:3362
Peter Thatcher04ac81f2015-09-21 18:48:2863// The timeout duration when a connection does not receive anything.
honghaiz34b11eb2016-03-16 15:55:4464static const int WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500; // 2.5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:1165
66// The length of time we wait before timing out writability on a connection.
honghaiz34b11eb2016-03-16 15:55:4467static const int CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:1168
69// The length of time we wait before we become unwritable.
honghaiz34b11eb2016-03-16 15:55:4470static const int CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
henrike@webrtc.org269fb4b2014-10-28 22:20:1171
72// This is the length of time that we wait for a ping response to come back.
skvlad51072462017-02-02 19:50:1473// There is no harm to keep this value high other than a small amount
74// of increased memory. But in some networks (2G),
75// we observe up to 60s RTTs.
76static const int CONNECTION_RESPONSE_TIMEOUT = 60 * 1000; // 60 seconds
honghaiz34b11eb2016-03-16 15:55:4477
78// The number of pings that must fail to respond before we become unwritable.
79static const uint32_t CONNECTION_WRITE_CONNECT_FAILURES = 5;
henrike@webrtc.org269fb4b2014-10-28 22:20:1180
81enum RelayType {
82 RELAY_GTURN, // Legacy google relay service.
83 RELAY_TURN // Standard (TURN) relay service.
84};
85
86enum IcePriorityValue {
hnsl277b2502016-12-13 13:17:2387 ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
88 ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
89 ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
Taylor Brandstetter62351c92016-08-11 23:05:0790 ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
henrike@webrtc.org269fb4b2014-10-28 22:20:1191 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
92 ICE_TYPE_PREFERENCE_SRFLX = 100,
93 ICE_TYPE_PREFERENCE_PRFLX = 110,
94 ICE_TYPE_PREFERENCE_HOST = 126
95};
96
hbos06495bc2017-01-02 16:08:1897// States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
98enum class IceCandidatePairState {
99 WAITING = 0, // Check has not been performed, Waiting pair on CL.
100 IN_PROGRESS, // Check has been sent, transaction is in progress.
101 SUCCEEDED, // Check already done, produced a successful result.
102 FAILED, // Check for this connection failed.
103 // According to spec there should also be a frozen state, but nothing is ever
104 // frozen because we have not implemented ICE freezing logic.
105};
106
henrike@webrtc.org269fb4b2014-10-28 22:20:11107const char* ProtoToString(ProtocolType proto);
108bool StringToProto(const char* value, ProtocolType* proto);
109
110struct ProtocolAddress {
111 rtc::SocketAddress address;
112 ProtocolType proto;
henrike@webrtc.org269fb4b2014-10-28 22:20:11113
114 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
hnsl277b2502016-12-13 13:17:23115 : address(a), proto(p) {}
Taylor Brandstettera1c30352016-05-13 15:15:11116
117 bool operator==(const ProtocolAddress& o) const {
hnsl277b2502016-12-13 13:17:23118 return address == o.address && proto == o.proto;
Taylor Brandstettera1c30352016-05-13 15:15:11119 }
120 bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
henrike@webrtc.org269fb4b2014-10-28 22:20:11121};
122
123typedef std::set<rtc::SocketAddress> ServerAddresses;
124
125// Represents a local communication mechanism that can be used to create
126// connections to similar mechanisms of the other client. Subclasses of this
127// one add support for specific mechanisms like local UDP ports.
128class Port : public PortInterface, public rtc::MessageHandler,
129 public sigslot::has_slots<> {
130 public:
Honghai Zhanga74363c2016-07-29 01:06:15131 // INIT: The state when a port is just created.
132 // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
133 // connection is using it.
134 // PRUNED: It will be destroyed if no connection is using it for a period of
135 // 30 seconds.
136 enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
pkasting@chromium.org332331f2014-11-06 20:19:22137 Port(rtc::Thread* thread,
Honghai Zhangd00c0572016-06-28 16:44:47138 const std::string& type,
henrike@webrtc.org269fb4b2014-10-28 22:20:11139 rtc::PacketSocketFactory* factory,
pkasting@chromium.org332331f2014-11-06 20:19:22140 rtc::Network* network,
pkasting@chromium.org332331f2014-11-06 20:19:22141 const std::string& username_fragment,
142 const std::string& password);
deadbeef5c3c1042017-08-04 22:01:57143 // TODO(deadbeef): Delete this constructor once clients are moved off of it.
pkasting@chromium.org332331f2014-11-06 20:19:22144 Port(rtc::Thread* thread,
145 const std::string& type,
146 rtc::PacketSocketFactory* factory,
147 rtc::Network* network,
148 const rtc::IPAddress& ip,
deadbeef5c3c1042017-08-04 22:01:57149 const std::string& username_fragment,
Steve Antonf2737d22017-10-31 23:27:34150 const std::string& password);
deadbeef5c3c1042017-08-04 22:01:57151 Port(rtc::Thread* thread,
152 const std::string& type,
153 rtc::PacketSocketFactory* factory,
154 rtc::Network* network,
Peter Boström0c4e06b2015-10-07 10:23:21155 uint16_t min_port,
156 uint16_t max_port,
pkasting@chromium.org332331f2014-11-06 20:19:22157 const std::string& username_fragment,
henrike@webrtc.org269fb4b2014-10-28 22:20:11158 const std::string& password);
Steve Anton1cf1b7d2017-10-30 17:00:15159 ~Port() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11160
Steve Anton1cf1b7d2017-10-30 17:00:15161 const std::string& Type() const override;
162 rtc::Network* Network() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11163
henrike@webrtc.org269fb4b2014-10-28 22:20:11164 // Methods to set/get ICE role and tiebreaker values.
Steve Anton1cf1b7d2017-10-30 17:00:15165 IceRole GetIceRole() const override;
166 void SetIceRole(IceRole role) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11167
Steve Anton1cf1b7d2017-10-30 17:00:15168 void SetIceTiebreaker(uint64_t tiebreaker) override;
169 uint64_t IceTiebreaker() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11170
Steve Anton1cf1b7d2017-10-30 17:00:15171 bool SharedSocket() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11172 void ResetSharedSocket() { shared_socket_ = false; }
173
Honghai Zhanga74363c2016-07-29 01:06:15174 // Should not destroy the port even if no connection is using it. Called when
175 // a port is ready to use.
176 void KeepAliveUntilPruned();
177 // Allows a port to be destroyed if no connection is using it.
178 void Prune();
179
henrike@webrtc.org269fb4b2014-10-28 22:20:11180 // The thread on which this port performs its I/O.
181 rtc::Thread* thread() { return thread_; }
182
183 // The factory used to create the sockets of this port.
184 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
185 void set_socket_factory(rtc::PacketSocketFactory* factory) {
186 factory_ = factory;
187 }
188
189 // For debugging purposes.
190 const std::string& content_name() const { return content_name_; }
191 void set_content_name(const std::string& content_name) {
192 content_name_ = content_name;
193 }
194
195 int component() const { return component_; }
196 void set_component(int component) { component_ = component; }
197
198 bool send_retransmit_count_attribute() const {
199 return send_retransmit_count_attribute_;
200 }
201 void set_send_retransmit_count_attribute(bool enable) {
202 send_retransmit_count_attribute_ = enable;
203 }
204
205 // Identifies the generation that this port was created in.
deadbeef14f97f52016-06-23 00:14:15206 uint32_t generation() const { return generation_; }
Peter Boström0c4e06b2015-10-07 10:23:21207 void set_generation(uint32_t generation) { generation_ = generation; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11208
henrike@webrtc.org269fb4b2014-10-28 22:20:11209 const std::string username_fragment() const;
210 const std::string& password() const { return password_; }
211
Taylor Brandstettera1c30352016-05-13 15:15:11212 // May be called when this port was initially created by a pooled
213 // PortAllocatorSession, and is now being assigned to an ICE transport.
214 // Updates the information for candidates as well.
215 void SetIceParameters(int component,
216 const std::string& username_fragment,
217 const std::string& password);
218
henrike@webrtc.org269fb4b2014-10-28 22:20:11219 // Fired when candidates are discovered by the port. When all candidates
220 // are discovered that belong to port SignalAddressReady is fired.
221 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
222
223 // Provides all of the above information in one handy object.
Steve Anton1cf1b7d2017-10-30 17:00:15224 const std::vector<Candidate>& Candidates() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11225
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.
Steve Anton1cf1b7d2017-10-30 17:00:15242 Connection* GetConnection(const rtc::SocketAddress& remote_addr) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11243
244 // Called each time a connection is created.
245 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
246
247 // In a shared socket mode each port which shares the socket will decide
248 // to accept the packet based on the |remote_addr|. Currently only UDP
249 // port implemented this method.
250 // TODO(mallinath) - Make it pure virtual.
Steve Anton1cf1b7d2017-10-30 17:00:15251 virtual bool HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
252 const char* data,
253 size_t size,
254 const rtc::SocketAddress& remote_addr,
255 const rtc::PacketTime& packet_time);
henrike@webrtc.org269fb4b2014-10-28 22:20:11256
henrike@webrtc.org269fb4b2014-10-28 22:20:11257 // Sends a response message (normal or error) to the given request. One of
258 // these methods should be called as a response to SignalUnknownAddress.
259 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
Steve Anton1cf1b7d2017-10-30 17:00:15260 void SendBindingResponse(StunMessage* request,
261 const rtc::SocketAddress& addr) override;
262 void SendBindingErrorResponse(StunMessage* request,
263 const rtc::SocketAddress& addr,
264 int error_code,
265 const std::string& reason) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11266
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
Steve Anton1cf1b7d2017-10-30 17:00:15275 void EnablePortPackets() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11276
277 // Called if the port has no connections and is no longer useful.
278 void Destroy();
279
Steve Anton1cf1b7d2017-10-30 17:00:15280 void OnMessage(rtc::Message* pmsg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11281
282 // Debugging description of this port
Steve Anton1cf1b7d2017-10-30 17:00:15283 std::string ToString() const override;
Peter Boström0c4e06b2015-10-07 10:23:21284 uint16_t min_port() { return min_port_; }
285 uint16_t max_port() { return max_port_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11286
287 // Timeout shortening function to speed up unit tests.
288 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
289
290 // This method will return local and remote username fragements from the
291 // stun username attribute if present.
292 bool ParseStunUsername(const StunMessage* stun_msg,
293 std::string* local_username,
Peter Thatcher7cbd1882015-09-18 01:54:52294 std::string* remote_username) const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11295 void CreateStunUsername(const std::string& remote_username,
296 std::string* stun_username_attr_str) const;
297
298 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
299 IceMessage* stun_msg,
300 const std::string& remote_ufrag);
301
stefanc1aeaf02015-10-15 14:26:07302 // Called when a packet has been sent to the socket.
Stefan Holmer55674ff2016-01-14 14:49:16303 // This is made pure virtual to notify subclasses of Port that they MUST
304 // listen to AsyncPacketSocket::SignalSentPacket and then call
305 // PortInterface::OnSentPacket.
306 virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
307 const rtc::SentPacket& sent_packet) = 0;
stefanc1aeaf02015-10-15 14:26:07308
henrike@webrtc.org269fb4b2014-10-28 22:20:11309 // Called when the socket is currently able to send.
310 void OnReadyToSend();
311
312 // Called when the Connection discovers a local peer reflexive candidate.
313 // Returns the index of the new local candidate.
314 size_t AddPrflxCandidate(const Candidate& local);
315
honghaiza0c44ea2016-03-23 23:07:48316 int16_t network_cost() const { return network_cost_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11317
318 protected:
Honghai Zhanga74363c2016-07-29 01:06:15319 enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
henrike@webrtc.org269fb4b2014-10-28 22:20:11320
Honghai Zhang351d77b2016-05-20 22:08:29321 virtual void UpdateNetworkCost();
322
henrike@webrtc.org269fb4b2014-10-28 22:20:11323 void set_type(const std::string& type) { type_ = type; }
324
Peter Boström2758c662017-02-14 01:33:27325 // Deprecated. Use the AddAddress() method below with "url" instead.
326 // TODO(zhihuang): Remove this after downstream applications stop using it.
327 void AddAddress(const rtc::SocketAddress& address,
328 const rtc::SocketAddress& base_address,
329 const rtc::SocketAddress& related_address,
330 const std::string& protocol,
331 const std::string& relay_protocol,
332 const std::string& tcptype,
333 const std::string& type,
334 uint32_t type_preference,
335 uint32_t relay_preference,
336 bool final);
337
henrike@webrtc.org269fb4b2014-10-28 22:20:11338 void AddAddress(const rtc::SocketAddress& address,
339 const rtc::SocketAddress& base_address,
340 const rtc::SocketAddress& related_address,
Guo-wei Shieh3d564c12015-08-19 23:51:15341 const std::string& protocol,
342 const std::string& relay_protocol,
343 const std::string& tcptype,
344 const std::string& type,
Peter Boström0c4e06b2015-10-07 10:23:21345 uint32_t type_preference,
346 uint32_t relay_preference,
zhihuang26d99c22017-02-13 20:47:27347 const std::string& url,
Guo-wei Shieh3d564c12015-08-19 23:51:15348 bool final);
henrike@webrtc.org269fb4b2014-10-28 22:20:11349
honghaiz36f50e82016-06-01 22:57:03350 // Adds the given connection to the map keyed by the remote candidate address.
351 // If an existing connection has the same address, the existing one will be
352 // replaced and destroyed.
353 void AddOrReplaceConnection(Connection* conn);
henrike@webrtc.org269fb4b2014-10-28 22:20:11354
355 // Called when a packet is received from an unknown address that is not
356 // currently a connection. If this is an authenticated STUN binding request,
357 // then we will signal the client.
358 void OnReadPacket(const char* data, size_t size,
359 const rtc::SocketAddress& addr,
360 ProtocolType proto);
361
362 // If the given data comprises a complete and correct STUN message then the
363 // return value is true, otherwise false. If the message username corresponds
364 // with this port's username fragment, msg will contain the parsed STUN
365 // message. Otherwise, the function may send a STUN response internally.
366 // remote_username contains the remote fragment of the STUN username.
kwiberg6baec032016-03-15 18:09:39367 bool GetStunMessage(const char* data,
368 size_t size,
henrike@webrtc.org269fb4b2014-10-28 22:20:11369 const rtc::SocketAddress& addr,
kwiberg3ec46792016-04-27 14:22:53370 std::unique_ptr<IceMessage>* out_msg,
kwiberg6baec032016-03-15 18:09:39371 std::string* out_username);
henrike@webrtc.org269fb4b2014-10-28 22:20:11372
373 // Checks if the address in addr is compatible with the port's ip.
374 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
375
376 // Returns default DSCP value.
377 rtc::DiffServCodePoint DefaultDscpValue() const {
378 // No change from what MediaChannel set.
379 return rtc::DSCP_NO_CHANGE;
380 }
381
honghaiz36f50e82016-06-01 22:57:03382 // Extra work to be done in subclasses when a connection is destroyed.
383 virtual void HandleConnectionDestroyed(Connection* conn) {}
384
henrike@webrtc.org269fb4b2014-10-28 22:20:11385 private:
386 void Construct();
387 // Called when one of our connections deletes itself.
388 void OnConnectionDestroyed(Connection* conn);
389
Honghai Zhang351d77b2016-05-20 22:08:29390 void OnNetworkTypeChanged(const rtc::Network* network);
391
henrike@webrtc.org269fb4b2014-10-28 22:20:11392 rtc::Thread* thread_;
393 rtc::PacketSocketFactory* factory_;
394 std::string type_;
395 bool send_retransmit_count_attribute_;
396 rtc::Network* network_;
Peter Boström0c4e06b2015-10-07 10:23:21397 uint16_t min_port_;
398 uint16_t max_port_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11399 std::string content_name_;
400 int component_;
Peter Boström0c4e06b2015-10-07 10:23:21401 uint32_t generation_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11402 // In order to establish a connection to this Port (so that real data can be
403 // sent through), the other side must send us a STUN binding request that is
404 // authenticated with this username_fragment and password.
405 // PortAllocatorSession will provide these username_fragment and password.
406 //
407 // Note: we should always use username_fragment() instead of using
408 // |ice_username_fragment_| directly. For the details see the comment on
409 // username_fragment().
410 std::string ice_username_fragment_;
411 std::string password_;
412 std::vector<Candidate> candidates_;
413 AddressMap connections_;
414 int timeout_delay_;
415 bool enable_port_packets_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11416 IceRole ice_role_;
Peter Boström0c4e06b2015-10-07 10:23:21417 uint64_t tiebreaker_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11418 bool shared_socket_;
419 // Information to use when going through a proxy.
420 std::string user_agent_;
421 rtc::ProxyInfo proxy_;
422
honghaize1a0c942016-02-16 22:54:56423 // A virtual cost perceived by the user, usually based on the network type
424 // (WiFi. vs. Cellular). It takes precedence over the priority when
425 // comparing two connections.
Kári Tristan Helgason47d3a012017-10-24 13:28:51426 int16_t network_cost_;
Honghai Zhanga74363c2016-07-29 01:06:15427 State state_ = State::INIT;
Honghai Zhangb5db1ec2016-07-28 20:23:05428 int64_t last_time_all_connections_removed_ = 0;
honghaize1a0c942016-02-16 22:54:56429
henrike@webrtc.org269fb4b2014-10-28 22:20:11430 friend class Connection;
431};
432
433// Represents a communication link between a port on the local client and a
434// port on the remote client.
Honghai Zhangcc411c02016-03-30 00:27:21435class Connection : public CandidatePairInterface,
436 public rtc::MessageHandler,
437 public sigslot::has_slots<> {
henrike@webrtc.org269fb4b2014-10-28 22:20:11438 public:
Peter Thatcher1cf6f812015-05-15 17:40:45439 struct SentPing {
Honghai Zhang8cd8f812016-08-04 02:50:41440 SentPing(const std::string id, int64_t sent_time, uint32_t nomination)
441 : id(id), sent_time(sent_time), nomination(nomination) {}
Peter Thatcher1cf6f812015-05-15 17:40:45442
443 std::string id;
honghaiz34b11eb2016-03-16 15:55:44444 int64_t sent_time;
Honghai Zhang8cd8f812016-08-04 02:50:41445 uint32_t nomination;
Peter Thatcher1cf6f812015-05-15 17:40:45446 };
447
Steve Anton1cf1b7d2017-10-30 17:00:15448 ~Connection() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11449
450 // The local port where this connection sends and receives packets.
451 Port* port() { return port_; }
452 const Port* port() const { return port_; }
453
Honghai Zhangcc411c02016-03-30 00:27:21454 // Implementation of virtual methods in CandidatePairInterface.
henrike@webrtc.org269fb4b2014-10-28 22:20:11455 // Returns the description of the local port
Steve Anton1cf1b7d2017-10-30 17:00:15456 const Candidate& local_candidate() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11457 // Returns the description of the remote port to which we communicate.
Steve Anton1cf1b7d2017-10-30 17:00:15458 const Candidate& remote_candidate() const override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11459
460 // Returns the pair priority.
Peter Boström0c4e06b2015-10-07 10:23:21461 uint64_t priority() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11462
henrike@webrtc.org269fb4b2014-10-28 22:20:11463 enum WriteState {
464 STATE_WRITABLE = 0, // we have received ping responses recently
465 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
466 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
467 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
468 };
469
470 WriteState write_state() const { return write_state_; }
471 bool writable() const { return write_state_ == STATE_WRITABLE; }
Peter Thatcher04ac81f2015-09-21 18:48:28472 bool receiving() const { return receiving_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11473
474 // Determines whether the connection has finished connecting. This can only
475 // be false for TCP connections.
476 bool connected() const { return connected_; }
Honghai Zhang2b342bf2015-09-30 16:51:58477 bool weak() const { return !(writable() && receiving() && connected()); }
478 bool active() const {
Honghai Zhang2b342bf2015-09-30 16:51:58479 return write_state_ != STATE_WRITE_TIMEOUT;
480 }
honghaiz059e1832016-06-24 18:03:55481
Honghai Zhang2b342bf2015-09-30 16:51:58482 // A connection is dead if it can be safely deleted.
honghaiz34b11eb2016-03-16 15:55:44483 bool dead(int64_t now) const;
honghaiz89374372015-09-24 20:14:47484
henrike@webrtc.org269fb4b2014-10-28 22:20:11485 // Estimate of the round-trip time over this connection.
honghaiz34b11eb2016-03-16 15:55:44486 int rtt() const { return rtt_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11487
hbos06495bc2017-01-02 16:08:18488 // Gets the |ConnectionInfo| stats, where |best_connection| has not been
489 // populated (default value false).
zhihuang5ecf16c2016-06-02 00:09:15490 ConnectionInfo stats();
491
henrike@webrtc.org269fb4b2014-10-28 22:20:11492 sigslot::signal1<Connection*> SignalStateChange;
493
494 // Sent when the connection has decided that it is no longer of value. It
495 // will delete itself immediately after this call.
496 sigslot::signal1<Connection*> SignalDestroyed;
497
498 // The connection can send and receive packets asynchronously. This matches
499 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
500 // covers.
501 virtual int Send(const void* data, size_t size,
502 const rtc::PacketOptions& options) = 0;
503
504 // Error if Send() returns < 0
505 virtual int GetError() = 0;
506
Peter Thatcher04ac81f2015-09-21 18:48:28507 sigslot::signal4<Connection*, const char*, size_t, const rtc::PacketTime&>
508 SignalReadPacket;
henrike@webrtc.org269fb4b2014-10-28 22:20:11509
510 sigslot::signal1<Connection*> SignalReadyToSend;
511
512 // Called when a packet is received on this connection.
513 void OnReadPacket(const char* data, size_t size,
514 const rtc::PacketTime& packet_time);
515
516 // Called when the socket is currently able to send.
517 void OnReadyToSend();
518
519 // Called when a connection is determined to be no longer useful to us. We
520 // still keep it around in case the other side wants to use it. But we can
521 // safely stop pinging on it and we can allow it to time out if the other
522 // side stops using it as well.
523 bool pruned() const { return pruned_; }
524 void Prune();
525
526 bool use_candidate_attr() const { return use_candidate_attr_; }
527 void set_use_candidate_attr(bool enable);
528
Honghai Zhang8cd8f812016-08-04 02:50:41529 void set_nomination(uint32_t value) { nomination_ = value; }
530
531 uint32_t remote_nomination() const { return remote_nomination_; }
hbos92eaec62017-02-27 09:38:08532 // One or several pairs may be nominated based on if Regular or Aggressive
533 // Nomination is used. https://tools.ietf.org/html/rfc5245#section-8
534 // |nominated| is defined both for the controlling or controlled agent based
535 // on if a nomination has been pinged or acknowledged. The controlled agent
536 // gets its |remote_nomination_| set when pinged by the controlling agent with
537 // a nomination value. The controlling agent gets its |acked_nomination_| set
538 // when receiving a response to a nominating ping.
539 bool nominated() const { return acked_nomination_ || remote_nomination_; }
Honghai Zhang8cd8f812016-08-04 02:50:41540 // Public for unit tests.
541 void set_remote_nomination(uint32_t remote_nomination) {
542 remote_nomination_ = remote_nomination;
543 }
544 // Public for unit tests.
545 uint32_t acked_nomination() const { return acked_nomination_; }
honghaiz5a3acd82015-08-20 22:53:17546
henrike@webrtc.org269fb4b2014-10-28 22:20:11547 void set_remote_ice_mode(IceMode mode) {
548 remote_ice_mode_ = mode;
549 }
550
bertholdherrmann0812030662016-10-18 21:00:02551 void set_receiving_timeout(int receiving_timeout_ms) {
Peter Thatcher04ac81f2015-09-21 18:48:28552 receiving_timeout_ = receiving_timeout_ms;
553 }
554
henrike@webrtc.org269fb4b2014-10-28 22:20:11555 // Makes the connection go away.
556 void Destroy();
557
deadbeef376e1232015-11-25 17:00:08558 // Makes the connection go away, in a failed state.
559 void FailAndDestroy();
560
honghaiz079a7a12016-06-22 23:26:29561 // Prunes the connection and sets its state to STATE_FAILED,
562 // It will not be used or send pings although it can still receive packets.
563 void FailAndPrune();
564
henrike@webrtc.org269fb4b2014-10-28 22:20:11565 // Checks that the state of this connection is up-to-date. The argument is
566 // the current time, which is compared against various timeouts.
honghaiz34b11eb2016-03-16 15:55:44567 void UpdateState(int64_t now);
henrike@webrtc.org269fb4b2014-10-28 22:20:11568
569 // Called when this connection should try checking writability again.
honghaiz34b11eb2016-03-16 15:55:44570 int64_t last_ping_sent() const { return last_ping_sent_; }
571 void Ping(int64_t now);
Honghai Zhang8cd8f812016-08-04 02:50:41572 void ReceivedPingResponse(int rtt, const std::string& request_id);
honghaiz34b11eb2016-03-16 15:55:44573 int64_t last_ping_response_received() const {
Honghai Zhang381b4212015-12-04 20:24:03574 return last_ping_response_received_;
575 }
Honghai Zhangfd16da22016-08-17 23:12:46576 // Used to check if any STUN ping response has been received.
577 int rtt_samples() const { return rtt_samples_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11578
579 // Called whenever a valid ping is received on this connection. This is
580 // public because the connection intercepts the first ping for us.
honghaiz34b11eb2016-03-16 15:55:44581 int64_t last_ping_received() const { return last_ping_received_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11582 void ReceivedPing();
honghaiz9b5ee9c2015-11-11 21:19:17583 // Handles the binding request; sends a response if this is a valid request.
584 void HandleBindingRequest(IceMessage* msg);
henrike@webrtc.org269fb4b2014-10-28 22:20:11585
Honghai Zhang572b0942016-06-23 19:26:57586 int64_t last_data_received() const { return last_data_received_; }
587
henrike@webrtc.org269fb4b2014-10-28 22:20:11588 // Debugging description of this connection
guoweis@webrtc.org8c9ff202014-12-04 07:56:02589 std::string ToDebugId() const;
henrike@webrtc.org269fb4b2014-10-28 22:20:11590 std::string ToString() const;
591 std::string ToSensitiveString() const;
Peter Thatcher1cf6f812015-05-15 17:40:45592 // Prints pings_since_last_response_ into a string.
593 void PrintPingsSinceLastResponse(std::string* pings, size_t max);
henrike@webrtc.org269fb4b2014-10-28 22:20:11594
595 bool reported() const { return reported_; }
596 void set_reported(bool reported) { reported_ = reported;}
597
honghaiz5a3acd82015-08-20 22:53:17598 // This signal will be fired if this connection is nominated by the
599 // controlling side.
600 sigslot::signal1<Connection*> SignalNominated;
Peter Thatcher54360512015-07-08 18:08:35601
henrike@webrtc.org269fb4b2014-10-28 22:20:11602 // Invoked when Connection receives STUN error response with 487 code.
603 void HandleRoleConflictFromPeer();
604
hbos06495bc2017-01-02 16:08:18605 IceCandidatePairState state() const { return state_; }
henrike@webrtc.org269fb4b2014-10-28 22:20:11606
honghaiz524ecc22016-05-25 19:48:31607 int num_pings_sent() const { return num_pings_sent_; }
608
henrike@webrtc.org269fb4b2014-10-28 22:20:11609 IceMode remote_ice_mode() const { return remote_ice_mode_; }
610
honghaize1a0c942016-02-16 22:54:56611 uint32_t ComputeNetworkCost() const;
612
Honghai Zhang4cedf2b2016-08-31 15:18:11613 // Update the ICE password and/or generation of the remote candidate if the
614 // ufrag in |params| matches the candidate's ufrag, and the
Taylor Brandstetter0a1bc532016-04-20 01:03:26615 // candidate's password and/or ufrag has not been set.
Honghai Zhang4cedf2b2016-08-31 15:18:11616 void MaybeSetRemoteIceParametersAndGeneration(const IceParameters& params,
617 int generation);
jiayl@webrtc.orgdacdd942015-01-23 17:33:34618
619 // If |remote_candidate_| is peer reflexive and is equivalent to
620 // |new_candidate| except the type, update |remote_candidate_| to
621 // |new_candidate|.
622 void MaybeUpdatePeerReflexiveCandidate(const Candidate& new_candidate);
623
Peter Thatcher54360512015-07-08 18:08:35624 // Returns the last received time of any data, stun request, or stun
625 // response in milliseconds
honghaiz34b11eb2016-03-16 15:55:44626 int64_t last_received() const;
honghaiz9ad0db52016-07-15 02:30:28627 // Returns the last time when the connection changed its receiving state.
628 int64_t receiving_unchanged_since() const {
629 return receiving_unchanged_since_;
630 }
Peter Thatcher54360512015-07-08 18:08:35631
Taylor Brandstetterb825aee2016-06-29 20:07:16632 bool stable(int64_t now) const;
zhihuang435264a2016-06-21 18:28:38633
henrike@webrtc.org269fb4b2014-10-28 22:20:11634 protected:
Guo-wei Shiehbe508a12015-04-06 19:48:47635 enum { MSG_DELETE = 0, MSG_FIRST_AVAILABLE };
636
henrike@webrtc.org269fb4b2014-10-28 22:20:11637 // Constructs a new connection to the given remote port.
638 Connection(Port* port, size_t index, const Candidate& candidate);
639
640 // Called back when StunRequestManager has a stun packet to send
641 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
642
643 // Callbacks from ConnectionRequest
Guo-wei Shiehbe508a12015-04-06 19:48:47644 virtual void OnConnectionRequestResponse(ConnectionRequest* req,
645 StunMessage* response);
henrike@webrtc.org269fb4b2014-10-28 22:20:11646 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
647 StunMessage* response);
648 void OnConnectionRequestTimeout(ConnectionRequest* req);
Peter Thatcher1cf6f812015-05-15 17:40:45649 void OnConnectionRequestSent(ConnectionRequest* req);
henrike@webrtc.org269fb4b2014-10-28 22:20:11650
Taylor Brandstetterb825aee2016-06-29 20:07:16651 bool rtt_converged() const;
zhihuang435264a2016-06-21 18:28:38652
653 // If the response is not received within 2 * RTT, the response is assumed to
654 // be missing.
Taylor Brandstetterb825aee2016-06-29 20:07:16655 bool missing_responses(int64_t now) const;
zhihuang435264a2016-06-21 18:28:38656
henrike@webrtc.org269fb4b2014-10-28 22:20:11657 // Changes the state and signals if necessary.
henrike@webrtc.org269fb4b2014-10-28 22:20:11658 void set_write_state(WriteState value);
honghaiz9ad0db52016-07-15 02:30:28659 void UpdateReceiving(int64_t now);
hbos06495bc2017-01-02 16:08:18660 void set_state(IceCandidatePairState state);
henrike@webrtc.org269fb4b2014-10-28 22:20:11661 void set_connected(bool value);
662
Honghai Zhang8cd8f812016-08-04 02:50:41663 uint32_t nomination() const { return nomination_; }
664
Steve Anton1cf1b7d2017-10-30 17:00:15665 void OnMessage(rtc::Message* pmsg) override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11666
667 Port* port_;
668 size_t local_candidate_index_;
669 Candidate remote_candidate_;
Honghai Zhang8cd8f812016-08-04 02:50:41670
671 ConnectionInfo stats_;
672 rtc::RateTracker recv_rate_tracker_;
673 rtc::RateTracker send_rate_tracker_;
674
675 private:
Taylor Brandstetter62351c92016-08-11 23:05:07676 // Update the local candidate based on the mapped address attribute.
677 // If the local candidate changed, fires SignalStateChange.
678 void MaybeUpdateLocalCandidate(ConnectionRequest* request,
679 StunMessage* response);
680
henrike@webrtc.org269fb4b2014-10-28 22:20:11681 WriteState write_state_;
Peter Thatcher04ac81f2015-09-21 18:48:28682 bool receiving_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11683 bool connected_;
684 bool pruned_;
685 // By default |use_candidate_attr_| flag will be true,
honghaiz5a3acd82015-08-20 22:53:17686 // as we will be using aggressive nomination.
henrike@webrtc.org269fb4b2014-10-28 22:20:11687 // But when peer is ice-lite, this flag "must" be initialized to false and
688 // turn on when connection becomes "best connection".
689 bool use_candidate_attr_;
Honghai Zhang8cd8f812016-08-04 02:50:41690 // Used by the controlling side to indicate that this connection will be
691 // selected for transmission if the peer supports ICE-renomination when this
692 // value is positive. A larger-value indicates that a connection is nominated
693 // later and should be selected by the controlled side with higher precedence.
694 // A zero-value indicates not nominating this connection.
695 uint32_t nomination_ = 0;
696 // The last nomination that has been acknowledged.
697 uint32_t acked_nomination_ = 0;
698 // Used by the controlled side to remember the nomination value received from
699 // the controlling side. When the peer does not support ICE re-nomination,
700 // its value will be 1 if the connection has been nominated.
701 uint32_t remote_nomination_ = 0;
702
henrike@webrtc.org269fb4b2014-10-28 22:20:11703 IceMode remote_ice_mode_;
704 StunRequestManager requests_;
honghaiz34b11eb2016-03-16 15:55:44705 int rtt_;
zhihuang435264a2016-06-21 18:28:38706 int rtt_samples_ = 0;
hbosbf8d3e52017-02-28 14:34:47707 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
708 uint64_t total_round_trip_time_ms_ = 0;
709 // https://w3c.github.io/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
710 rtc::Optional<uint32_t> current_round_trip_time_ms_;
honghaiz34b11eb2016-03-16 15:55:44711 int64_t last_ping_sent_; // last time we sent a ping to the other side
712 int64_t last_ping_received_; // last time we received a ping from the other
713 // side
714 int64_t last_data_received_;
715 int64_t last_ping_response_received_;
honghaiz9ad0db52016-07-15 02:30:28716 int64_t receiving_unchanged_since_ = 0;
Peter Thatcher1cf6f812015-05-15 17:40:45717 std::vector<SentPing> pings_since_last_response_;
henrike@webrtc.org269fb4b2014-10-28 22:20:11718
zsteinabbacbf2017-03-20 17:53:12719 PacketLossEstimator packet_loss_estimator_;
720
henrike@webrtc.org269fb4b2014-10-28 22:20:11721 bool reported_;
hbos06495bc2017-01-02 16:08:18722 IceCandidatePairState state_;
Peter Thatcher04ac81f2015-09-21 18:48:28723 // Time duration to switch from receiving to not receiving.
honghaiz34b11eb2016-03-16 15:55:44724 int receiving_timeout_;
725 int64_t time_created_ms_;
honghaiz524ecc22016-05-25 19:48:31726 int num_pings_sent_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11727
728 friend class Port;
729 friend class ConnectionRequest;
730};
731
deadbeef376e1232015-11-25 17:00:08732// ProxyConnection defers all the interesting work to the port.
henrike@webrtc.org269fb4b2014-10-28 22:20:11733class ProxyConnection : public Connection {
734 public:
deadbeef376e1232015-11-25 17:00:08735 ProxyConnection(Port* port, size_t index, const Candidate& remote_candidate);
henrike@webrtc.org269fb4b2014-10-28 22:20:11736
deadbeef376e1232015-11-25 17:00:08737 int Send(const void* data,
738 size_t size,
739 const rtc::PacketOptions& options) override;
Steve Anton1cf1b7d2017-10-30 17:00:15740 int GetError() override;
henrike@webrtc.org269fb4b2014-10-28 22:20:11741
742 private:
deadbeef376e1232015-11-25 17:00:08743 int error_ = 0;
henrike@webrtc.org269fb4b2014-10-28 22:20:11744};
745
746} // namespace cricket
747
Mirko Bonadei92ea95e2017-09-15 04:47:31748#endif // P2P_BASE_PORT_H_