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