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