Home | History | Annotate | Download | only in base
      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_RELAYSERVER_H_
     29 #define TALK_P2P_BASE_RELAYSERVER_H_
     30 
     31 #include <string>
     32 #include <vector>
     33 #include <map>
     34 
     35 #include "talk/base/asyncudpsocket.h"
     36 #include "talk/base/socketaddresspair.h"
     37 #include "talk/base/thread.h"
     38 #include "talk/base/timeutils.h"
     39 #include "talk/p2p/base/port.h"
     40 #include "talk/p2p/base/stun.h"
     41 
     42 namespace cricket {
     43 
     44 class RelayServerBinding;
     45 class RelayServerConnection;
     46 
     47 // Relays traffic between connections to the server that are "bound" together.
     48 // All connections created with the same username/password are bound together.
     49 class RelayServer : public talk_base::MessageHandler,
     50                     public sigslot::has_slots<> {
     51  public:
     52   // Creates a server, which will use this thread to post messages to itself.
     53   explicit RelayServer(talk_base::Thread* thread);
     54   ~RelayServer();
     55 
     56   talk_base::Thread* thread() { return thread_; }
     57 
     58   // Indicates whether we will print updates of the number of bindings.
     59   bool log_bindings() const { return log_bindings_; }
     60   void set_log_bindings(bool log_bindings) { log_bindings_ = log_bindings; }
     61 
     62   // Updates the set of sockets that the server uses to talk to "internal"
     63   // clients.  These are clients that do the "port allocations".
     64   void AddInternalSocket(talk_base::AsyncPacketSocket* socket);
     65   void RemoveInternalSocket(talk_base::AsyncPacketSocket* socket);
     66 
     67   // Updates the set of sockets that the server uses to talk to "external"
     68   // clients.  These are the clients that do not do allocations.  They do not
     69   // know that these addresses represent a relay server.
     70   void AddExternalSocket(talk_base::AsyncPacketSocket* socket);
     71   void RemoveExternalSocket(talk_base::AsyncPacketSocket* socket);
     72 
     73   // Starts listening for connections on this sockets. When someone
     74   // tries to connect, the connection will be accepted and a new
     75   // internal socket will be added.
     76   void AddInternalServerSocket(talk_base::AsyncSocket* socket,
     77                                cricket::ProtocolType proto);
     78 
     79   // Removes this server socket from the list.
     80   void RemoveInternalServerSocket(talk_base::AsyncSocket* socket);
     81 
     82   // Methods for testing and debuging.
     83   int GetConnectionCount() const;
     84   talk_base::SocketAddressPair GetConnection(int connection) const;
     85   bool HasConnection(const talk_base::SocketAddress& address) const;
     86 
     87  private:
     88   typedef std::vector<talk_base::AsyncPacketSocket*> SocketList;
     89   typedef std::map<talk_base::AsyncSocket*,
     90                    cricket::ProtocolType> ServerSocketMap;
     91   typedef std::map<std::string, RelayServerBinding*> BindingMap;
     92   typedef std::map<talk_base::SocketAddressPair,
     93                    RelayServerConnection*> ConnectionMap;
     94 
     95   talk_base::Thread* thread_;
     96   bool log_bindings_;
     97   SocketList internal_sockets_;
     98   SocketList external_sockets_;
     99   SocketList removed_sockets_;
    100   ServerSocketMap server_sockets_;
    101   BindingMap bindings_;
    102   ConnectionMap connections_;
    103 
    104   // Called when a packet is received by the server on one of its sockets.
    105   void OnInternalPacket(talk_base::AsyncPacketSocket* socket,
    106                         const char* bytes, size_t size,
    107                         const talk_base::SocketAddress& remote_addr);
    108   void OnExternalPacket(talk_base::AsyncPacketSocket* socket,
    109                         const char* bytes, size_t size,
    110                         const talk_base::SocketAddress& remote_addr);
    111 
    112   void OnReadEvent(talk_base::AsyncSocket* socket);
    113 
    114   // Processes the relevant STUN request types from the client.
    115   bool HandleStun(const char* bytes, size_t size,
    116                   const talk_base::SocketAddress& remote_addr,
    117                   talk_base::AsyncPacketSocket* socket,
    118                   std::string* username, StunMessage* msg);
    119   void HandleStunAllocate(const char* bytes, size_t size,
    120                           const talk_base::SocketAddressPair& ap,
    121                           talk_base::AsyncPacketSocket* socket);
    122   void HandleStun(RelayServerConnection* int_conn, const char* bytes,
    123                   size_t size);
    124   void HandleStunAllocate(RelayServerConnection* int_conn,
    125                           const StunMessage& msg);
    126   void HandleStunSend(RelayServerConnection* int_conn, const StunMessage& msg);
    127 
    128   // Adds/Removes the a connection or binding.
    129   void AddConnection(RelayServerConnection* conn);
    130   void RemoveConnection(RelayServerConnection* conn);
    131   void RemoveBinding(RelayServerBinding* binding);
    132 
    133   // Handle messages in our worker thread.
    134   void OnMessage(talk_base::Message *pmsg);
    135 
    136   // Called when the timer for checking lifetime times out.
    137   void OnTimeout(RelayServerBinding* binding);
    138 
    139   // Accept connections on this server socket.
    140   void AcceptConnection(talk_base::AsyncSocket* server_socket);
    141 
    142   friend class RelayServerConnection;
    143   friend class RelayServerBinding;
    144 };
    145 
    146 // Maintains information about a connection to the server.  Each connection is
    147 // part of one and only one binding.
    148 class RelayServerConnection {
    149  public:
    150   RelayServerConnection(RelayServerBinding* binding,
    151                         const talk_base::SocketAddressPair& addrs,
    152                         talk_base::AsyncPacketSocket* socket);
    153   ~RelayServerConnection();
    154 
    155   RelayServerBinding* binding() { return binding_; }
    156   talk_base::AsyncPacketSocket* socket() { return socket_; }
    157 
    158   // Returns a pair where the source is the remote address and the destination
    159   // is the local address.
    160   const talk_base::SocketAddressPair& addr_pair() { return addr_pair_; }
    161 
    162   // Sends a packet to the connected client.  If an address is provided, then
    163   // we make sure the internal client receives it, wrapping if necessary.
    164   void Send(const char* data, size_t size);
    165   void Send(const char* data, size_t size,
    166             const talk_base::SocketAddress& ext_addr);
    167 
    168   // Sends a STUN message to the connected client with no wrapping.
    169   void SendStun(const StunMessage& msg);
    170   void SendStunError(const StunMessage& request, int code, const char* desc);
    171 
    172   // A locked connection is one for which we know the intended destination of
    173   // any raw packet received.
    174   bool locked() const { return locked_; }
    175   void Lock();
    176   void Unlock();
    177 
    178   // Records the address that raw packets should be forwarded to (for internal
    179   // packets only; for external, we already know where they go).
    180   const talk_base::SocketAddress& default_destination() const {
    181     return default_dest_;
    182   }
    183   void set_default_destination(const talk_base::SocketAddress& addr) {
    184     default_dest_ = addr;
    185   }
    186 
    187  private:
    188   RelayServerBinding* binding_;
    189   talk_base::SocketAddressPair addr_pair_;
    190   talk_base::AsyncPacketSocket* socket_;
    191   bool locked_;
    192   talk_base::SocketAddress default_dest_;
    193 };
    194 
    195 // Records a set of internal and external connections that we relay between,
    196 // or in other words, that are "bound" together.
    197 class RelayServerBinding : public talk_base::MessageHandler {
    198  public:
    199   RelayServerBinding(
    200       RelayServer* server, const std::string& username,
    201       const std::string& password, uint32 lifetime);
    202   virtual ~RelayServerBinding();
    203 
    204   RelayServer* server() { return server_; }
    205   uint32 lifetime() { return lifetime_; }
    206   const std::string& username() { return username_; }
    207   const std::string& password() { return password_; }
    208   const std::string& magic_cookie() { return magic_cookie_; }
    209 
    210   // Adds/Removes a connection into the binding.
    211   void AddInternalConnection(RelayServerConnection* conn);
    212   void AddExternalConnection(RelayServerConnection* conn);
    213 
    214   // We keep track of the use of each binding.  If we detect that it was not
    215   // used for longer than the lifetime, then we send a signal.
    216   void NoteUsed();
    217   sigslot::signal1<RelayServerBinding*> SignalTimeout;
    218 
    219   // Determines whether the given packet has the magic cookie present (in the
    220   // right place).
    221   bool HasMagicCookie(const char* bytes, size_t size) const;
    222 
    223   // Determines the connection to use to send packets to or from the given
    224   // external address.
    225   RelayServerConnection* GetInternalConnection(
    226       const talk_base::SocketAddress& ext_addr);
    227   RelayServerConnection* GetExternalConnection(
    228       const talk_base::SocketAddress& ext_addr);
    229 
    230   // MessageHandler:
    231   void OnMessage(talk_base::Message *pmsg);
    232 
    233  private:
    234   RelayServer* server_;
    235 
    236   std::string username_;
    237   std::string password_;
    238   std::string magic_cookie_;
    239 
    240   std::vector<RelayServerConnection*> internal_connections_;
    241   std::vector<RelayServerConnection*> external_connections_;
    242 
    243   uint32 lifetime_;
    244   uint32 last_used_;
    245   // TODO: bandwidth
    246 };
    247 
    248 }  // namespace cricket
    249 
    250 #endif  // TALK_P2P_BASE_RELAYSERVER_H_
    251