blob: 48b85302be70b1a797050b7dd1c5ee2a0cdfa059 [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>
15#include <set>
16#include <string>
17#include <vector>
18
19#include "webrtc/p2p/base/candidate.h"
20#include "webrtc/p2p/base/packetsocketfactory.h"
21#include "webrtc/p2p/base/portinterface.h"
22#include "webrtc/p2p/base/stun.h"
23#include "webrtc/p2p/base/stunrequest.h"
24#include "webrtc/p2p/base/transport.h"
25#include "webrtc/base/asyncpacketsocket.h"
26#include "webrtc/base/network.h"
27#include "webrtc/base/proxyinfo.h"
28#include "webrtc/base/ratetracker.h"
29#include "webrtc/base/sigslot.h"
30#include "webrtc/base/socketaddress.h"
31#include "webrtc/base/thread.h"
32
33namespace cricket {
34
35class Connection;
36class ConnectionRequest;
37
38extern const char LOCAL_PORT_TYPE[];
39extern const char STUN_PORT_TYPE[];
40extern const char PRFLX_PORT_TYPE[];
41extern const char RELAY_PORT_TYPE[];
42
43extern const char UDP_PROTOCOL_NAME[];
44extern const char TCP_PROTOCOL_NAME[];
45extern const char SSLTCP_PROTOCOL_NAME[];
46
47// RFC 6544, TCP candidate encoding rules.
48extern const int DISCARD_PORT;
49extern const char TCPTYPE_ACTIVE_STR[];
50extern const char TCPTYPE_PASSIVE_STR[];
51extern const char TCPTYPE_SIMOPEN_STR[];
52
53// The length of time we wait before timing out readability on a connection.
54const uint32 CONNECTION_READ_TIMEOUT = 30 * 1000; // 30 seconds
55
56// The length of time we wait before timing out writability on a connection.
57const uint32 CONNECTION_WRITE_TIMEOUT = 15 * 1000; // 15 seconds
58
59// The length of time we wait before we become unwritable.
60const uint32 CONNECTION_WRITE_CONNECT_TIMEOUT = 5 * 1000; // 5 seconds
61
62// The number of pings that must fail to respond before we become unwritable.
63const uint32 CONNECTION_WRITE_CONNECT_FAILURES = 5;
64
65// This is the length of time that we wait for a ping response to come back.
66const int CONNECTION_RESPONSE_TIMEOUT = 5 * 1000; // 5 seconds
67
68enum RelayType {
69 RELAY_GTURN, // Legacy google relay service.
70 RELAY_TURN // Standard (TURN) relay service.
71};
72
73enum IcePriorityValue {
74 // The reason we are choosing Relay preference 2 is because, we can run
75 // Relay from client to server on UDP/TCP/TLS. To distinguish the transport
76 // protocol, we prefer UDP over TCP over TLS.
77 // For UDP ICE_TYPE_PREFERENCE_RELAY will be 2.
78 // For TCP ICE_TYPE_PREFERENCE_RELAY will be 1.
79 // For TLS ICE_TYPE_PREFERENCE_RELAY will be 0.
80 // Check turnport.cc for setting these values.
81 ICE_TYPE_PREFERENCE_RELAY = 2,
82 ICE_TYPE_PREFERENCE_HOST_TCP = 90,
83 ICE_TYPE_PREFERENCE_SRFLX = 100,
84 ICE_TYPE_PREFERENCE_PRFLX = 110,
85 ICE_TYPE_PREFERENCE_HOST = 126
86};
87
88const char* ProtoToString(ProtocolType proto);
89bool StringToProto(const char* value, ProtocolType* proto);
90
91struct ProtocolAddress {
92 rtc::SocketAddress address;
93 ProtocolType proto;
94 bool secure;
95
96 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
97 : address(a), proto(p), secure(false) { }
98 ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p, bool sec)
99 : address(a), proto(p), secure(sec) { }
100};
101
102typedef std::set<rtc::SocketAddress> ServerAddresses;
103
104// Represents a local communication mechanism that can be used to create
105// connections to similar mechanisms of the other client. Subclasses of this
106// one add support for specific mechanisms like local UDP ports.
107class Port : public PortInterface, public rtc::MessageHandler,
108 public sigslot::has_slots<> {
109 public:
110 Port(rtc::Thread* thread, rtc::PacketSocketFactory* factory,
111 rtc::Network* network, const rtc::IPAddress& ip,
112 const std::string& username_fragment, const std::string& password);
113 Port(rtc::Thread* thread, const std::string& type,
114 rtc::PacketSocketFactory* factory,
115 rtc::Network* network, const rtc::IPAddress& ip,
116 int min_port, int max_port, const std::string& username_fragment,
117 const std::string& password);
118 virtual ~Port();
119
120 virtual const std::string& Type() const { return type_; }
121 virtual rtc::Network* Network() const { return network_; }
122
123 // This method will set the flag which enables standard ICE/STUN procedures
124 // in STUN connectivity checks. Currently this method does
125 // 1. Add / Verify MI attribute in STUN binding requests.
126 // 2. Username attribute in STUN binding request will be RFRAF:LFRAG,
127 // as opposed to RFRAGLFRAG.
128 virtual void SetIceProtocolType(IceProtocolType protocol) {
129 ice_protocol_ = protocol;
130 }
131 virtual IceProtocolType IceProtocol() const { return ice_protocol_; }
132
133 // Methods to set/get ICE role and tiebreaker values.
134 IceRole GetIceRole() const { return ice_role_; }
135 void SetIceRole(IceRole role) { ice_role_ = role; }
136
137 void SetIceTiebreaker(uint64 tiebreaker) { tiebreaker_ = tiebreaker; }
138 uint64 IceTiebreaker() const { return tiebreaker_; }
139
140 virtual bool SharedSocket() const { return shared_socket_; }
141 void ResetSharedSocket() { shared_socket_ = false; }
142
143 // The thread on which this port performs its I/O.
144 rtc::Thread* thread() { return thread_; }
145
146 // The factory used to create the sockets of this port.
147 rtc::PacketSocketFactory* socket_factory() const { return factory_; }
148 void set_socket_factory(rtc::PacketSocketFactory* factory) {
149 factory_ = factory;
150 }
151
152 // For debugging purposes.
153 const std::string& content_name() const { return content_name_; }
154 void set_content_name(const std::string& content_name) {
155 content_name_ = content_name;
156 }
157
158 int component() const { return component_; }
159 void set_component(int component) { component_ = component; }
160
161 bool send_retransmit_count_attribute() const {
162 return send_retransmit_count_attribute_;
163 }
164 void set_send_retransmit_count_attribute(bool enable) {
165 send_retransmit_count_attribute_ = enable;
166 }
167
168 // Identifies the generation that this port was created in.
169 uint32 generation() { return generation_; }
170 void set_generation(uint32 generation) { generation_ = generation; }
171
172 // ICE requires a single username/password per content/media line. So the
173 // |ice_username_fragment_| of the ports that belongs to the same content will
174 // be the same. However this causes a small complication with our relay
175 // server, which expects different username for RTP and RTCP.
176 //
177 // To resolve this problem, we implemented the username_fragment(),
178 // which returns a different username (calculated from
179 // |ice_username_fragment_|) for RTCP in the case of ICEPROTO_GOOGLE. And the
180 // username_fragment() simply returns |ice_username_fragment_| when running
181 // in ICEPROTO_RFC5245.
182 //
183 // As a result the ICEPROTO_GOOGLE will use different usernames for RTP and
184 // RTCP. And the ICEPROTO_RFC5245 will use same username for both RTP and
185 // RTCP.
186 const std::string username_fragment() const;
187 const std::string& password() const { return password_; }
188
189 // Fired when candidates are discovered by the port. When all candidates
190 // are discovered that belong to port SignalAddressReady is fired.
191 sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
192
193 // Provides all of the above information in one handy object.
194 virtual const std::vector<Candidate>& Candidates() const {
195 return candidates_;
196 }
197
198 // SignalPortComplete is sent when port completes the task of candidates
199 // allocation.
200 sigslot::signal1<Port*> SignalPortComplete;
201 // This signal sent when port fails to allocate candidates and this port
202 // can't be used in establishing the connections. When port is in shared mode
203 // and port fails to allocate one of the candidates, port shouldn't send
204 // this signal as other candidates might be usefull in establishing the
205 // connection.
206 sigslot::signal1<Port*> SignalPortError;
207
208 // Returns a map containing all of the connections of this port, keyed by the
209 // remote address.
210 typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
211 const AddressMap& connections() { return connections_; }
212
213 // Returns the connection to the given address or NULL if none exists.
214 virtual Connection* GetConnection(
215 const rtc::SocketAddress& remote_addr);
216
217 // Called each time a connection is created.
218 sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
219
220 // In a shared socket mode each port which shares the socket will decide
221 // to accept the packet based on the |remote_addr|. Currently only UDP
222 // port implemented this method.
223 // TODO(mallinath) - Make it pure virtual.
224 virtual bool HandleIncomingPacket(
225 rtc::AsyncPacketSocket* socket, const char* data, size_t size,
226 const rtc::SocketAddress& remote_addr,
227 const rtc::PacketTime& packet_time) {
228 ASSERT(false);
229 return false;
230 }
231
232 // Sends a response message (normal or error) to the given request. One of
233 // these methods should be called as a response to SignalUnknownAddress.
234 // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse.
235 virtual void SendBindingResponse(StunMessage* request,
236 const rtc::SocketAddress& addr);
237 virtual void SendBindingErrorResponse(
238 StunMessage* request, const rtc::SocketAddress& addr,
239 int error_code, const std::string& reason);
240
241 void set_proxy(const std::string& user_agent,
242 const rtc::ProxyInfo& proxy) {
243 user_agent_ = user_agent;
244 proxy_ = proxy;
245 }
246 const std::string& user_agent() { return user_agent_; }
247 const rtc::ProxyInfo& proxy() { return proxy_; }
248
249 virtual void EnablePortPackets();
250
251 // Called if the port has no connections and is no longer useful.
252 void Destroy();
253
254 virtual void OnMessage(rtc::Message *pmsg);
255
256 // Debugging description of this port
257 virtual std::string ToString() const;
258 rtc::IPAddress& ip() { return ip_; }
259 int min_port() { return min_port_; }
260 int max_port() { return max_port_; }
261
262 // Timeout shortening function to speed up unit tests.
263 void set_timeout_delay(int delay) { timeout_delay_ = delay; }
264
265 // This method will return local and remote username fragements from the
266 // stun username attribute if present.
267 bool ParseStunUsername(const StunMessage* stun_msg,
268 std::string* local_username,
269 std::string* remote_username,
270 IceProtocolType* remote_protocol_type) const;
271 void CreateStunUsername(const std::string& remote_username,
272 std::string* stun_username_attr_str) const;
273
274 bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
275 IceMessage* stun_msg,
276 const std::string& remote_ufrag);
277
278 // Called when the socket is currently able to send.
279 void OnReadyToSend();
280
281 // Called when the Connection discovers a local peer reflexive candidate.
282 // Returns the index of the new local candidate.
283 size_t AddPrflxCandidate(const Candidate& local);
284
285 // Returns if RFC 5245 ICE protocol is used.
286 bool IsStandardIce() const;
287
288 // Returns if Google ICE protocol is used.
289 bool IsGoogleIce() const;
290
291 // Returns if Hybrid ICE protocol is used.
292 bool IsHybridIce() const;
293
294 void set_candidate_filter(uint32 candidate_filter) {
295 candidate_filter_ = candidate_filter;
296 }
297
298 protected:
299 enum {
300 MSG_CHECKTIMEOUT = 0,
301 MSG_FIRST_AVAILABLE
302 };
303
304 void set_type(const std::string& type) { type_ = type; }
305
306 void AddAddress(const rtc::SocketAddress& address,
307 const rtc::SocketAddress& base_address,
308 const rtc::SocketAddress& related_address,
309 const std::string& protocol, const std::string& tcptype,
310 const std::string& type, uint32 type_preference,
311 uint32 relay_preference, bool final);
312
313 // Adds the given connection to the list. (Deleting removes them.)
314 void AddConnection(Connection* conn);
315
316 // Called when a packet is received from an unknown address that is not
317 // currently a connection. If this is an authenticated STUN binding request,
318 // then we will signal the client.
319 void OnReadPacket(const char* data, size_t size,
320 const rtc::SocketAddress& addr,
321 ProtocolType proto);
322
323 // If the given data comprises a complete and correct STUN message then the
324 // return value is true, otherwise false. If the message username corresponds
325 // with this port's username fragment, msg will contain the parsed STUN
326 // message. Otherwise, the function may send a STUN response internally.
327 // remote_username contains the remote fragment of the STUN username.
328 bool GetStunMessage(const char* data, size_t size,
329 const rtc::SocketAddress& addr,
330 IceMessage** out_msg, std::string* out_username);
331
332 // Checks if the address in addr is compatible with the port's ip.
333 bool IsCompatibleAddress(const rtc::SocketAddress& addr);
334
335 // Returns default DSCP value.
336 rtc::DiffServCodePoint DefaultDscpValue() const {
337 // No change from what MediaChannel set.
338 return rtc::DSCP_NO_CHANGE;
339 }
340
341 uint32 candidate_filter() { return candidate_filter_; }
342
343 private:
344 void Construct();
345 // Called when one of our connections deletes itself.
346 void OnConnectionDestroyed(Connection* conn);
347
348 // Checks if this port is useless, and hence, should be destroyed.
349 void CheckTimeout();
350
351 rtc::Thread* thread_;
352 rtc::PacketSocketFactory* factory_;
353 std::string type_;
354 bool send_retransmit_count_attribute_;
355 rtc::Network* network_;
356 rtc::IPAddress ip_;
357 int min_port_;
358 int max_port_;
359 std::string content_name_;
360 int component_;
361 uint32 generation_;
362 // In order to establish a connection to this Port (so that real data can be
363 // sent through), the other side must send us a STUN binding request that is
364 // authenticated with this username_fragment and password.
365 // PortAllocatorSession will provide these username_fragment and password.
366 //
367 // Note: we should always use username_fragment() instead of using
368 // |ice_username_fragment_| directly. For the details see the comment on
369 // username_fragment().
370 std::string ice_username_fragment_;
371 std::string password_;
372 std::vector<Candidate> candidates_;
373 AddressMap connections_;
374 int timeout_delay_;
375 bool enable_port_packets_;
376 IceProtocolType ice_protocol_;
377 IceRole ice_role_;
378 uint64 tiebreaker_;
379 bool shared_socket_;
380 // Information to use when going through a proxy.
381 std::string user_agent_;
382 rtc::ProxyInfo proxy_;
383
384 // Candidate filter is pushed down to Port such that each Port could
385 // make its own decision on how to create candidates. For example,
386 // when IceTransportsType is set to relay, both RelayPort and
387 // TurnPort will hide raddr to avoid local address leakage.
388 uint32 candidate_filter_;
389
390 friend class Connection;
391};
392
393// Represents a communication link between a port on the local client and a
394// port on the remote client.
395class Connection : public rtc::MessageHandler,
396 public sigslot::has_slots<> {
397 public:
398 // States are from RFC 5245. http://tools.ietf.org/html/rfc5245#section-5.7.4
399 enum State {
400 STATE_WAITING = 0, // Check has not been performed, Waiting pair on CL.
401 STATE_INPROGRESS, // Check has been sent, transaction is in progress.
402 STATE_SUCCEEDED, // Check already done, produced a successful result.
403 STATE_FAILED // Check for this connection failed.
404 };
405
406 virtual ~Connection();
407
408 // The local port where this connection sends and receives packets.
409 Port* port() { return port_; }
410 const Port* port() const { return port_; }
411
412 // Returns the description of the local port
413 virtual const Candidate& local_candidate() const;
414
415 // Returns the description of the remote port to which we communicate.
416 const Candidate& remote_candidate() const { return remote_candidate_; }
417
418 // Returns the pair priority.
419 uint64 priority() const;
420
421 enum ReadState {
422 STATE_READ_INIT = 0, // we have yet to receive a ping
423 STATE_READABLE = 1, // we have received pings recently
424 STATE_READ_TIMEOUT = 2, // we haven't received pings in a while
425 };
426
427 ReadState read_state() const { return read_state_; }
428 bool readable() const { return read_state_ == STATE_READABLE; }
429
430 enum WriteState {
431 STATE_WRITABLE = 0, // we have received ping responses recently
432 STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
433 STATE_WRITE_INIT = 2, // we have yet to receive a ping response
434 STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
435 };
436
437 WriteState write_state() const { return write_state_; }
438 bool writable() const { return write_state_ == STATE_WRITABLE; }
439
440 // Determines whether the connection has finished connecting. This can only
441 // be false for TCP connections.
442 bool connected() const { return connected_; }
443
444 // Estimate of the round-trip time over this connection.
445 uint32 rtt() const { return rtt_; }
446
447 size_t sent_total_bytes();
448 size_t sent_bytes_second();
449 size_t recv_total_bytes();
450 size_t recv_bytes_second();
451 sigslot::signal1<Connection*> SignalStateChange;
452
453 // Sent when the connection has decided that it is no longer of value. It
454 // will delete itself immediately after this call.
455 sigslot::signal1<Connection*> SignalDestroyed;
456
457 // The connection can send and receive packets asynchronously. This matches
458 // the interface of AsyncPacketSocket, which may use UDP or TCP under the
459 // covers.
460 virtual int Send(const void* data, size_t size,
461 const rtc::PacketOptions& options) = 0;
462
463 // Error if Send() returns < 0
464 virtual int GetError() = 0;
465
466 sigslot::signal4<Connection*, const char*, size_t,
467 const rtc::PacketTime&> SignalReadPacket;
468
469 sigslot::signal1<Connection*> SignalReadyToSend;
470
471 // Called when a packet is received on this connection.
472 void OnReadPacket(const char* data, size_t size,
473 const rtc::PacketTime& packet_time);
474
475 // Called when the socket is currently able to send.
476 void OnReadyToSend();
477
478 // Called when a connection is determined to be no longer useful to us. We
479 // still keep it around in case the other side wants to use it. But we can
480 // safely stop pinging on it and we can allow it to time out if the other
481 // side stops using it as well.
482 bool pruned() const { return pruned_; }
483 void Prune();
484
485 bool use_candidate_attr() const { return use_candidate_attr_; }
486 void set_use_candidate_attr(bool enable);
487
488 void set_remote_ice_mode(IceMode mode) {
489 remote_ice_mode_ = mode;
490 }
491
492 // Makes the connection go away.
493 void Destroy();
494
495 // Checks that the state of this connection is up-to-date. The argument is
496 // the current time, which is compared against various timeouts.
497 void UpdateState(uint32 now);
498
499 // Called when this connection should try checking writability again.
500 uint32 last_ping_sent() const { return last_ping_sent_; }
501 void Ping(uint32 now);
502
503 // Called whenever a valid ping is received on this connection. This is
504 // public because the connection intercepts the first ping for us.
505 uint32 last_ping_received() const { return last_ping_received_; }
506 void ReceivedPing();
507
508 // Debugging description of this connection
509 std::string ToString() const;
510 std::string ToSensitiveString() const;
511
512 bool reported() const { return reported_; }
513 void set_reported(bool reported) { reported_ = reported;}
514
515 // This flag will be set if this connection is the chosen one for media
516 // transmission. This connection will send STUN ping with USE-CANDIDATE
517 // attribute.
518 sigslot::signal1<Connection*> SignalUseCandidate;
519 // Invoked when Connection receives STUN error response with 487 code.
520 void HandleRoleConflictFromPeer();
521
522 State state() const { return state_; }
523
524 IceMode remote_ice_mode() const { return remote_ice_mode_; }
525
526 protected:
527 // Constructs a new connection to the given remote port.
528 Connection(Port* port, size_t index, const Candidate& candidate);
529
530 // Called back when StunRequestManager has a stun packet to send
531 void OnSendStunPacket(const void* data, size_t size, StunRequest* req);
532
533 // Callbacks from ConnectionRequest
534 void OnConnectionRequestResponse(ConnectionRequest* req,
535 StunMessage* response);
536 void OnConnectionRequestErrorResponse(ConnectionRequest* req,
537 StunMessage* response);
538 void OnConnectionRequestTimeout(ConnectionRequest* req);
539
540 // Changes the state and signals if necessary.
541 void set_read_state(ReadState value);
542 void set_write_state(WriteState value);
543 void set_state(State state);
544 void set_connected(bool value);
545
546 // Checks if this connection is useless, and hence, should be destroyed.
547 void CheckTimeout();
548
549 void OnMessage(rtc::Message *pmsg);
550
551 Port* port_;
552 size_t local_candidate_index_;
553 Candidate remote_candidate_;
554 ReadState read_state_;
555 WriteState write_state_;
556 bool connected_;
557 bool pruned_;
558 // By default |use_candidate_attr_| flag will be true,
559 // as we will be using agrressive nomination.
560 // But when peer is ice-lite, this flag "must" be initialized to false and
561 // turn on when connection becomes "best connection".
562 bool use_candidate_attr_;
563 IceMode remote_ice_mode_;
564 StunRequestManager requests_;
565 uint32 rtt_;
566 uint32 last_ping_sent_; // last time we sent a ping to the other side
567 uint32 last_ping_received_; // last time we received a ping from the other
568 // side
569 uint32 last_data_received_;
570 uint32 last_ping_response_received_;
571 std::vector<uint32> pings_since_last_response_;
572
573 rtc::RateTracker recv_rate_tracker_;
574 rtc::RateTracker send_rate_tracker_;
575
576 private:
577 void MaybeAddPrflxCandidate(ConnectionRequest* request,
578 StunMessage* response);
579
580 bool reported_;
581 State state_;
582
583 friend class Port;
584 friend class ConnectionRequest;
585};
586
587// ProxyConnection defers all the interesting work to the port
588class ProxyConnection : public Connection {
589 public:
590 ProxyConnection(Port* port, size_t index, const Candidate& candidate);
591
592 virtual int Send(const void* data, size_t size,
593 const rtc::PacketOptions& options);
594 virtual int GetError() { return error_; }
595
596 private:
597 int error_;
598};
599
600} // namespace cricket
601
602#endif // WEBRTC_P2P_BASE_PORT_H_