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_BASE_VIRTUALSOCKETSERVER_H_
     29 #define TALK_BASE_VIRTUALSOCKETSERVER_H_
     30 
     31 #include <assert.h>
     32 
     33 #include <deque>
     34 #include <map>
     35 
     36 #include "talk/base/messagequeue.h"
     37 #include "talk/base/socketserver.h"
     38 
     39 namespace talk_base {
     40 
     41 class VirtualSocket;
     42 class SocketAddressPair;
     43 
     44 // Simulates a network in the same manner as a loopback interface.  The
     45 // interface can create as many addresses as you want.  All of the sockets
     46 // created by this network will be able to communicate with one another, unless
     47 // they are bound to addresses from incompatible families.
     48 class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
     49  public:
     50   // TODO: Add "owned" parameter.
     51   // If "owned" is set, the supplied socketserver will be deleted later.
     52   explicit VirtualSocketServer(SocketServer* ss);
     53   virtual ~VirtualSocketServer();
     54 
     55   SocketServer* socketserver() { return server_; }
     56 
     57   // Limits the network bandwidth (maximum bytes per second).  Zero means that
     58   // all sends occur instantly.  Defaults to 0.
     59   uint32 bandwidth() const { return bandwidth_; }
     60   void set_bandwidth(uint32 bandwidth) { bandwidth_ = bandwidth; }
     61 
     62   // Limits the amount of data which can be in flight on the network without
     63   // packet loss (on a per sender basis).  Defaults to 64 KB.
     64   uint32 network_capacity() const { return network_capacity_; }
     65   void set_network_capacity(uint32 capacity) {
     66     network_capacity_ = capacity;
     67   }
     68 
     69   // The amount of data which can be buffered by tcp on the sender's side
     70   uint32 send_buffer_capacity() const { return send_buffer_capacity_; }
     71   void set_send_buffer_capacity(uint32 capacity) {
     72     send_buffer_capacity_ = capacity;
     73   }
     74 
     75   // The amount of data which can be buffered by tcp on the receiver's side
     76   uint32 recv_buffer_capacity() const { return recv_buffer_capacity_; }
     77   void set_recv_buffer_capacity(uint32 capacity) {
     78     recv_buffer_capacity_ = capacity;
     79   }
     80 
     81   // Controls the (transit) delay for packets sent in the network.  This does
     82   // not inclue the time required to sit in the send queue.  Both of these
     83   // values are measured in milliseconds.  Defaults to no delay.
     84   uint32 delay_mean() const { return delay_mean_; }
     85   uint32 delay_stddev() const { return delay_stddev_; }
     86   uint32 delay_samples() const { return delay_samples_; }
     87   void set_delay_mean(uint32 delay_mean) { delay_mean_ = delay_mean; }
     88   void set_delay_stddev(uint32 delay_stddev) {
     89     delay_stddev_ = delay_stddev;
     90   }
     91   void set_delay_samples(uint32 delay_samples) {
     92     delay_samples_ = delay_samples;
     93   }
     94 
     95   // If the (transit) delay parameters are modified, this method should be
     96   // called to recompute the new distribution.
     97   void UpdateDelayDistribution();
     98 
     99   // Controls the (uniform) probability that any sent packet is dropped.  This
    100   // is separate from calculations to drop based on queue size.
    101   double drop_probability() { return drop_prob_; }
    102   void set_drop_probability(double drop_prob) {
    103     assert((0 <= drop_prob) && (drop_prob <= 1));
    104     drop_prob_ = drop_prob;
    105   }
    106 
    107   // SocketFactory:
    108   virtual Socket* CreateSocket(int type);
    109   virtual Socket* CreateSocket(int family, int type);
    110 
    111   virtual AsyncSocket* CreateAsyncSocket(int type);
    112   virtual AsyncSocket* CreateAsyncSocket(int family, int type);
    113 
    114   // SocketServer:
    115   virtual void SetMessageQueue(MessageQueue* queue);
    116   virtual bool Wait(int cms, bool process_io);
    117   virtual void WakeUp();
    118 
    119   typedef std::pair<double, double> Point;
    120   typedef std::vector<Point> Function;
    121 
    122   static Function* CreateDistribution(uint32 mean, uint32 stddev,
    123                                       uint32 samples);
    124 
    125   // Similar to Thread::ProcessMessages, but it only processes messages until
    126   // there are no immediate messages or pending network traffic.  Returns false
    127   // if Thread::Stop() was called.
    128   bool ProcessMessagesUntilIdle();
    129 
    130  protected:
    131   // Returns a new IP not used before in this network.
    132   IPAddress GetNextIP(int family);
    133   uint16 GetNextPort();
    134 
    135   VirtualSocket* CreateSocketInternal(int family, int type);
    136 
    137   // Binds the given socket to addr, assigning and IP and Port if necessary
    138   int Bind(VirtualSocket* socket, SocketAddress* addr);
    139 
    140   // Binds the given socket to the given (fully-defined) address.
    141   int Bind(VirtualSocket* socket, const SocketAddress& addr);
    142 
    143   // Find the socket bound to the given address
    144   VirtualSocket* LookupBinding(const SocketAddress& addr);
    145 
    146   int Unbind(const SocketAddress& addr, VirtualSocket* socket);
    147 
    148   // Adds a mapping between this socket pair and the socket.
    149   void AddConnection(const SocketAddress& client,
    150                      const SocketAddress& server,
    151                      VirtualSocket* socket);
    152 
    153   // Find the socket pair corresponding to this server address.
    154   VirtualSocket* LookupConnection(const SocketAddress& client,
    155                                   const SocketAddress& server);
    156 
    157   void RemoveConnection(const SocketAddress& client,
    158                         const SocketAddress& server);
    159 
    160   // Connects the given socket to the socket at the given address
    161   int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
    162               bool use_delay);
    163 
    164   // Sends a disconnect message to the socket at the given address
    165   bool Disconnect(VirtualSocket* socket);
    166 
    167   // Sends the given packet to the socket at the given address (if one exists).
    168   int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
    169               const SocketAddress& remote_addr);
    170 
    171   // Moves as much data as possible from the sender's buffer to the network
    172   void SendTcp(VirtualSocket* socket);
    173 
    174   // Places a packet on the network.
    175   void AddPacketToNetwork(VirtualSocket* socket, VirtualSocket* recipient,
    176                           uint32 cur_time, const char* data, size_t data_size,
    177                           size_t header_size, bool ordered);
    178 
    179   // Removes stale packets from the network
    180   void PurgeNetworkPackets(VirtualSocket* socket, uint32 cur_time);
    181 
    182   // Computes the number of milliseconds required to send a packet of this size.
    183   uint32 SendDelay(uint32 size);
    184 
    185   // Returns a random transit delay chosen from the appropriate distribution.
    186   uint32 GetRandomTransitDelay();
    187 
    188   // Basic operations on functions.  Those that return a function also take
    189   // ownership of the function given (and hence, may modify or delete it).
    190   static Function* Accumulate(Function* f);
    191   static Function* Invert(Function* f);
    192   static Function* Resample(Function* f, double x1, double x2, uint32 samples);
    193   static double Evaluate(Function* f, double x);
    194 
    195   // NULL out our message queue if it goes away. Necessary in the case where
    196   // our lifetime is greater than that of the thread we are using, since we
    197   // try to send Close messages for all connected sockets when we shutdown.
    198   void OnMessageQueueDestroyed() { msg_queue_ = NULL; }
    199 
    200   // Determine if two sockets should be able to communicate.
    201   // We don't (currently) specify an address family for sockets; instead,
    202   // the currently bound address is used to infer the address family.
    203   // Any socket that is not explicitly bound to an IPv4 address is assumed to be
    204   // dual-stack capable.
    205   // This function tests if two addresses can communicate, as well as the
    206   // sockets to which they may be bound (the addresses may or may not yet be
    207   // bound to the sockets).
    208   // First the addresses are tested (after normalization):
    209   // If both have the same family, then communication is OK.
    210   // If only one is IPv4 then false, unless the other is bound to ::.
    211   // This applies even if the IPv4 address is 0.0.0.0.
    212   // The socket arguments are optional; the sockets are checked to see if they
    213   // were explicitly bound to IPv6-any ('::'), and if so communication is
    214   // permitted.
    215   // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
    216   static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
    217 
    218  private:
    219   friend class VirtualSocket;
    220 
    221   typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
    222   typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
    223 
    224   SocketServer* server_;
    225   bool server_owned_;
    226   MessageQueue* msg_queue_;
    227   bool stop_on_idle_;
    228   uint32 network_delay_;
    229   in_addr next_ipv4_;
    230   in6_addr next_ipv6_;
    231   uint16 next_port_;
    232   AddressMap* bindings_;
    233   ConnectionMap* connections_;
    234 
    235   uint32 bandwidth_;
    236   uint32 network_capacity_;
    237   uint32 send_buffer_capacity_;
    238   uint32 recv_buffer_capacity_;
    239   uint32 delay_mean_;
    240   uint32 delay_stddev_;
    241   uint32 delay_samples_;
    242   Function* delay_dist_;
    243   CriticalSection delay_crit_;
    244 
    245   double drop_prob_;
    246   DISALLOW_EVIL_CONSTRUCTORS(VirtualSocketServer);
    247 };
    248 
    249 }  // namespace talk_base
    250 
    251 #endif  // TALK_BASE_VIRTUALSOCKETSERVER_H_
    252