Home | History | Annotate | Download | only in base
      1 /*
      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_BASE_VIRTUALSOCKETSERVER_H_
     12 #define WEBRTC_BASE_VIRTUALSOCKETSERVER_H_
     13 
     14 #include <assert.h>
     15 
     16 #include <deque>
     17 #include <map>
     18 
     19 #include "webrtc/base/messagequeue.h"
     20 #include "webrtc/base/socketserver.h"
     21 
     22 namespace rtc {
     23 
     24 class Packet;
     25 class VirtualSocket;
     26 class SocketAddressPair;
     27 
     28 // Simulates a network in the same manner as a loopback interface.  The
     29 // interface can create as many addresses as you want.  All of the sockets
     30 // created by this network will be able to communicate with one another, unless
     31 // they are bound to addresses from incompatible families.
     32 class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
     33  public:
     34   // TODO: Add "owned" parameter.
     35   // If "owned" is set, the supplied socketserver will be deleted later.
     36   explicit VirtualSocketServer(SocketServer* ss);
     37   ~VirtualSocketServer() override;
     38 
     39   SocketServer* socketserver() { return server_; }
     40 
     41   // The default route indicates which local address to use when a socket is
     42   // bound to the 'any' address, e.g. 0.0.0.0.
     43   IPAddress GetDefaultRoute(int family);
     44   void SetDefaultRoute(const IPAddress& from_addr);
     45 
     46   // Limits the network bandwidth (maximum bytes per second).  Zero means that
     47   // all sends occur instantly.  Defaults to 0.
     48   uint32_t bandwidth() const { return bandwidth_; }
     49   void set_bandwidth(uint32_t bandwidth) { bandwidth_ = bandwidth; }
     50 
     51   // Limits the amount of data which can be in flight on the network without
     52   // packet loss (on a per sender basis).  Defaults to 64 KB.
     53   uint32_t network_capacity() const { return network_capacity_; }
     54   void set_network_capacity(uint32_t capacity) { network_capacity_ = capacity; }
     55 
     56   // The amount of data which can be buffered by tcp on the sender's side
     57   uint32_t send_buffer_capacity() const { return send_buffer_capacity_; }
     58   void set_send_buffer_capacity(uint32_t capacity) {
     59     send_buffer_capacity_ = capacity;
     60   }
     61 
     62   // The amount of data which can be buffered by tcp on the receiver's side
     63   uint32_t recv_buffer_capacity() const { return recv_buffer_capacity_; }
     64   void set_recv_buffer_capacity(uint32_t capacity) {
     65     recv_buffer_capacity_ = capacity;
     66   }
     67 
     68   // Controls the (transit) delay for packets sent in the network.  This does
     69   // not inclue the time required to sit in the send queue.  Both of these
     70   // values are measured in milliseconds.  Defaults to no delay.
     71   uint32_t delay_mean() const { return delay_mean_; }
     72   uint32_t delay_stddev() const { return delay_stddev_; }
     73   uint32_t delay_samples() const { return delay_samples_; }
     74   void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
     75   void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
     76   void set_delay_samples(uint32_t delay_samples) {
     77     delay_samples_ = delay_samples;
     78   }
     79 
     80   // If the (transit) delay parameters are modified, this method should be
     81   // called to recompute the new distribution.
     82   void UpdateDelayDistribution();
     83 
     84   // Controls the (uniform) probability that any sent packet is dropped.  This
     85   // is separate from calculations to drop based on queue size.
     86   double drop_probability() { return drop_prob_; }
     87   void set_drop_probability(double drop_prob) {
     88     assert((0 <= drop_prob) && (drop_prob <= 1));
     89     drop_prob_ = drop_prob;
     90   }
     91 
     92   // SocketFactory:
     93   Socket* CreateSocket(int type) override;
     94   Socket* CreateSocket(int family, int type) override;
     95 
     96   AsyncSocket* CreateAsyncSocket(int type) override;
     97   AsyncSocket* CreateAsyncSocket(int family, int type) override;
     98 
     99   // SocketServer:
    100   void SetMessageQueue(MessageQueue* queue) override;
    101   bool Wait(int cms, bool process_io) override;
    102   void WakeUp() override;
    103 
    104   typedef std::pair<double, double> Point;
    105   typedef std::vector<Point> Function;
    106 
    107   static Function* CreateDistribution(uint32_t mean,
    108                                       uint32_t stddev,
    109                                       uint32_t samples);
    110 
    111   // Similar to Thread::ProcessMessages, but it only processes messages until
    112   // there are no immediate messages or pending network traffic.  Returns false
    113   // if Thread::Stop() was called.
    114   bool ProcessMessagesUntilIdle();
    115 
    116   // Sets the next port number to use for testing.
    117   void SetNextPortForTesting(uint16_t port);
    118 
    119   // Close a pair of Tcp connections by addresses. Both connections will have
    120   // its own OnClose invoked.
    121   bool CloseTcpConnections(const SocketAddress& addr_local,
    122                            const SocketAddress& addr_remote);
    123 
    124  protected:
    125   // Returns a new IP not used before in this network.
    126   IPAddress GetNextIP(int family);
    127   uint16_t GetNextPort();
    128 
    129   VirtualSocket* CreateSocketInternal(int family, int type);
    130 
    131   // Binds the given socket to addr, assigning and IP and Port if necessary
    132   int Bind(VirtualSocket* socket, SocketAddress* addr);
    133 
    134   // Binds the given socket to the given (fully-defined) address.
    135   int Bind(VirtualSocket* socket, const SocketAddress& addr);
    136 
    137   // Find the socket bound to the given address
    138   VirtualSocket* LookupBinding(const SocketAddress& addr);
    139 
    140   int Unbind(const SocketAddress& addr, VirtualSocket* socket);
    141 
    142   // Adds a mapping between this socket pair and the socket.
    143   void AddConnection(const SocketAddress& client,
    144                      const SocketAddress& server,
    145                      VirtualSocket* socket);
    146 
    147   // Find the socket pair corresponding to this server address.
    148   VirtualSocket* LookupConnection(const SocketAddress& client,
    149                                   const SocketAddress& server);
    150 
    151   void RemoveConnection(const SocketAddress& client,
    152                         const SocketAddress& server);
    153 
    154   // Connects the given socket to the socket at the given address
    155   int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
    156               bool use_delay);
    157 
    158   // Sends a disconnect message to the socket at the given address
    159   bool Disconnect(VirtualSocket* socket);
    160 
    161   // Sends the given packet to the socket at the given address (if one exists).
    162   int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
    163               const SocketAddress& remote_addr);
    164 
    165   // Moves as much data as possible from the sender's buffer to the network
    166   void SendTcp(VirtualSocket* socket);
    167 
    168   // Places a packet on the network.
    169   void AddPacketToNetwork(VirtualSocket* socket,
    170                           VirtualSocket* recipient,
    171                           uint32_t cur_time,
    172                           const char* data,
    173                           size_t data_size,
    174                           size_t header_size,
    175                           bool ordered);
    176 
    177   // Removes stale packets from the network
    178   void PurgeNetworkPackets(VirtualSocket* socket, uint32_t cur_time);
    179 
    180   // Computes the number of milliseconds required to send a packet of this size.
    181   uint32_t SendDelay(uint32_t size);
    182 
    183   // Returns a random transit delay chosen from the appropriate distribution.
    184   uint32_t GetRandomTransitDelay();
    185 
    186   // Basic operations on functions.  Those that return a function also take
    187   // ownership of the function given (and hence, may modify or delete it).
    188   static Function* Accumulate(Function* f);
    189   static Function* Invert(Function* f);
    190   static Function* Resample(Function* f,
    191                             double x1,
    192                             double x2,
    193                             uint32_t samples);
    194   static double Evaluate(Function* f, double x);
    195 
    196   // NULL out our message queue if it goes away. Necessary in the case where
    197   // our lifetime is greater than that of the thread we are using, since we
    198   // try to send Close messages for all connected sockets when we shutdown.
    199   void OnMessageQueueDestroyed() { msg_queue_ = NULL; }
    200 
    201   // Determine if two sockets should be able to communicate.
    202   // We don't (currently) specify an address family for sockets; instead,
    203   // the currently bound address is used to infer the address family.
    204   // Any socket that is not explicitly bound to an IPv4 address is assumed to be
    205   // dual-stack capable.
    206   // This function tests if two addresses can communicate, as well as the
    207   // sockets to which they may be bound (the addresses may or may not yet be
    208   // bound to the sockets).
    209   // First the addresses are tested (after normalization):
    210   // If both have the same family, then communication is OK.
    211   // If only one is IPv4 then false, unless the other is bound to ::.
    212   // This applies even if the IPv4 address is 0.0.0.0.
    213   // The socket arguments are optional; the sockets are checked to see if they
    214   // were explicitly bound to IPv6-any ('::'), and if so communication is
    215   // permitted.
    216   // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
    217   static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
    218 
    219  private:
    220   friend class VirtualSocket;
    221 
    222   typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
    223   typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
    224 
    225   SocketServer* server_;
    226   bool server_owned_;
    227   MessageQueue* msg_queue_;
    228   bool stop_on_idle_;
    229   uint32_t network_delay_;
    230   in_addr next_ipv4_;
    231   in6_addr next_ipv6_;
    232   uint16_t next_port_;
    233   AddressMap* bindings_;
    234   ConnectionMap* connections_;
    235 
    236   IPAddress default_route_v4_;
    237   IPAddress default_route_v6_;
    238 
    239   uint32_t bandwidth_;
    240   uint32_t network_capacity_;
    241   uint32_t send_buffer_capacity_;
    242   uint32_t recv_buffer_capacity_;
    243   uint32_t delay_mean_;
    244   uint32_t delay_stddev_;
    245   uint32_t delay_samples_;
    246   Function* delay_dist_;
    247   CriticalSection delay_crit_;
    248 
    249   double drop_prob_;
    250   RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
    251 };
    252 
    253 // Implements the socket interface using the virtual network.  Packets are
    254 // passed as messages using the message queue of the socket server.
    255 class VirtualSocket : public AsyncSocket, public MessageHandler {
    256  public:
    257   VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
    258   ~VirtualSocket() override;
    259 
    260   SocketAddress GetLocalAddress() const override;
    261   SocketAddress GetRemoteAddress() const override;
    262 
    263   // Used by TurnPortTest to mimic a case where proxy returns local host address
    264   // instead of the original one TurnPort was bound against. Please see WebRTC
    265   // issue 3927 for more detail.
    266   void SetAlternativeLocalAddress(const SocketAddress& addr);
    267 
    268   int Bind(const SocketAddress& addr) override;
    269   int Connect(const SocketAddress& addr) override;
    270   int Close() override;
    271   int Send(const void* pv, size_t cb) override;
    272   int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
    273   int Recv(void* pv, size_t cb) override;
    274   int RecvFrom(void* pv, size_t cb, SocketAddress* paddr) override;
    275   int Listen(int backlog) override;
    276   VirtualSocket* Accept(SocketAddress* paddr) override;
    277 
    278   int GetError() const override;
    279   void SetError(int error) override;
    280   ConnState GetState() const override;
    281   int GetOption(Option opt, int* value) override;
    282   int SetOption(Option opt, int value) override;
    283   int EstimateMTU(uint16_t* mtu) override;
    284   void OnMessage(Message* pmsg) override;
    285 
    286   bool was_any() { return was_any_; }
    287   void set_was_any(bool was_any) { was_any_ = was_any; }
    288 
    289   // For testing purpose only. Fired when client socket is bound to an address.
    290   sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
    291 
    292  private:
    293   struct NetworkEntry {
    294     size_t size;
    295     uint32_t done_time;
    296   };
    297 
    298   typedef std::deque<SocketAddress> ListenQueue;
    299   typedef std::deque<NetworkEntry> NetworkQueue;
    300   typedef std::vector<char> SendBuffer;
    301   typedef std::list<Packet*> RecvBuffer;
    302   typedef std::map<Option, int> OptionsMap;
    303 
    304   int InitiateConnect(const SocketAddress& addr, bool use_delay);
    305   void CompleteConnect(const SocketAddress& addr, bool notify);
    306   int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
    307   int SendTcp(const void* pv, size_t cb);
    308 
    309   // Used by server sockets to set the local address without binding.
    310   void SetLocalAddress(const SocketAddress& addr);
    311 
    312   VirtualSocketServer* server_;
    313   int type_;
    314   bool async_;
    315   ConnState state_;
    316   int error_;
    317   SocketAddress local_addr_;
    318   SocketAddress alternative_local_addr_;
    319   SocketAddress remote_addr_;
    320 
    321   // Pending sockets which can be Accepted
    322   ListenQueue* listen_queue_;
    323 
    324   // Data which tcp has buffered for sending
    325   SendBuffer send_buffer_;
    326   bool write_enabled_;
    327 
    328   // Critical section to protect the recv_buffer and queue_
    329   CriticalSection crit_;
    330 
    331   // Network model that enforces bandwidth and capacity constraints
    332   NetworkQueue network_;
    333   size_t network_size_;
    334 
    335   // Data which has been received from the network
    336   RecvBuffer recv_buffer_;
    337   // The amount of data which is in flight or in recv_buffer_
    338   size_t recv_buffer_size_;
    339 
    340   // Is this socket bound?
    341   bool bound_;
    342 
    343   // When we bind a socket to Any, VSS's Bind gives it another address. For
    344   // dual-stack sockets, we want to distinguish between sockets that were
    345   // explicitly given a particular address and sockets that had one picked
    346   // for them by VSS.
    347   bool was_any_;
    348 
    349   // Store the options that are set
    350   OptionsMap options_map_;
    351 
    352   friend class VirtualSocketServer;
    353 };
    354 
    355 }  // namespace rtc
    356 
    357 #endif  // WEBRTC_BASE_VIRTUALSOCKETSERVER_H_
    358