blob: dafab541b6260c14a04a3bc432244729810b5d6c [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#ifndef RTC_BASE_VIRTUAL_SOCKET_SERVER_H_
12#define RTC_BASE_VIRTUAL_SOCKET_SERVER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <deque>
15#include <map>
Steve Antonf4172382020-01-27 15:45:02 -080016#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/constructor_magic.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/event.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "rtc_base/fake_clock.h"
Sebastian Jansson4db28b52020-01-08 14:07:15 +010022#include "rtc_base/message_handler.h"
Steve Anton10542f22019-01-11 09:11:00 -080023#include "rtc_base/socket_server.h"
Niels Möllerc413c552021-06-22 10:03:14 +020024#include "rtc_base/synchronization/mutex.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025
26namespace rtc {
27
28class Packet;
29class VirtualSocket;
30class 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.
Niels Möller9bd24572021-04-19 12:18:27 +020036class VirtualSocketServer : public SocketServer {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020037 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.
Sebastian Janssond624c392019-04-17 10:36:03 +020042 explicit VirtualSocketServer(ThreadProcessingFakeClock* fake_clock);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020043 ~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.
52 uint32_t bandwidth() const { return 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.
57 uint32_t network_capacity() const { return network_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
61 uint32_t send_buffer_capacity() const { return send_buffer_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
67 uint32_t recv_buffer_capacity() const { return recv_buffer_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.
75 uint32_t delay_mean() const { return delay_mean_; }
76 uint32_t delay_stddev() const { return delay_stddev_; }
77 uint32_t delay_samples() const { return delay_samples_; }
78 void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
79 void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
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.
90 double drop_probability() { return 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
Harald Alvestrand3d792e92021-03-10 07:29:28 +000097 // Controls the maximum UDP payload for the networks simulated
98 // by this server. Any UDP payload sent that is larger than this will
99 // be dropped.
100 size_t max_udp_payload() { return max_udp_payload_; }
101 void set_max_udp_payload(size_t payload_size) {
102 max_udp_payload_ = payload_size;
103 }
104
105 size_t largest_seen_udp_payload() { return largest_seen_udp_payload_; }
106
Artem Titov96e3b992021-07-26 16:03:14 +0200107 // If `blocked` is true, subsequent attempts to send will result in -1 being
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200108 // returned, with the socket error set to EWOULDBLOCK.
109 //
Artem Titov96e3b992021-07-26 16:03:14 +0200110 // If this method is later called with `blocked` set to false, any sockets
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 // that previously failed to send with EWOULDBLOCK will emit SignalWriteEvent.
112 //
113 // This can be used to simulate the send buffer on a network interface being
114 // full, and test functionality related to EWOULDBLOCK/SignalWriteEvent.
115 void SetSendingBlocked(bool blocked);
116
117 // SocketFactory:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200118 Socket* CreateSocket(int family, int type) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200119
120 // SocketServer:
Sebastian Jansson290de822020-01-09 14:20:23 +0100121 void SetMessageQueue(Thread* queue) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 bool Wait(int cms, bool process_io) override;
123 void WakeUp() override;
124
125 void SetDelayOnAddress(const rtc::SocketAddress& address, int delay_ms) {
126 delay_by_ip_[address.ipaddr()] = delay_ms;
127 }
128
deadbeef5c3c1042017-08-04 15:01:57 -0700129 // Used by TurnPortTest and TcpPortTest (for example), to mimic a case where
130 // a proxy returns the local host address instead of the original one the
131 // port was bound against. Please see WebRTC issue 3927 for more detail.
132 //
133 // If SetAlternativeLocalAddress(A, B) is called, then when something
134 // attempts to bind a socket to address A, it will get a socket bound to
135 // address B instead.
136 void SetAlternativeLocalAddress(const rtc::IPAddress& address,
137 const rtc::IPAddress& alternative);
138
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200139 typedef std::pair<double, double> Point;
140 typedef std::vector<Point> Function;
141
Niels Möller983627c2021-02-09 15:12:28 +0100142 static std::unique_ptr<Function> CreateDistribution(uint32_t mean,
143 uint32_t stddev,
144 uint32_t samples);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200145
146 // Similar to Thread::ProcessMessages, but it only processes messages until
147 // there are no immediate messages or pending network traffic. Returns false
148 // if Thread::Stop() was called.
149 bool ProcessMessagesUntilIdle();
150
151 // Sets the next port number to use for testing.
152 void SetNextPortForTesting(uint16_t port);
153
154 // Close a pair of Tcp connections by addresses. Both connections will have
155 // its own OnClose invoked.
156 bool CloseTcpConnections(const SocketAddress& addr_local,
157 const SocketAddress& addr_remote);
158
Taylor Brandstetter389a97c2018-01-03 16:26:06 -0800159 // Number of packets that clients have attempted to send through this virtual
160 // socket server. Intended to be used for test assertions.
161 uint32_t sent_packets() const { return sent_packets_; }
162
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200163 // Binds the given socket to addr, assigning and IP and Port if necessary
164 int Bind(VirtualSocket* socket, SocketAddress* addr);
165
166 // Binds the given socket to the given (fully-defined) address.
167 int Bind(VirtualSocket* socket, const SocketAddress& addr);
168
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200169 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
170
171 // Adds a mapping between this socket pair and the socket.
172 void AddConnection(const SocketAddress& client,
173 const SocketAddress& server,
174 VirtualSocket* socket);
175
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200176 // Connects the given socket to the socket at the given address
Yves Gerey665174f2018-06-19 15:03:05 +0200177 int Connect(VirtualSocket* socket,
178 const SocketAddress& remote_addr,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200179 bool use_delay);
180
181 // Sends a disconnect message to the socket at the given address
182 bool Disconnect(VirtualSocket* socket);
183
Niels Möllerc79bd432021-02-16 09:25:52 +0100184 // Lookup address, and disconnect corresponding socket.
185 bool Disconnect(const SocketAddress& addr);
186
187 // Lookup connection, close corresponding socket.
188 bool Disconnect(const SocketAddress& local_addr,
189 const SocketAddress& remote_addr);
190
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191 // Sends the given packet to the socket at the given address (if one exists).
Yves Gerey665174f2018-06-19 15:03:05 +0200192 int SendUdp(VirtualSocket* socket,
193 const char* data,
194 size_t data_size,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200195 const SocketAddress& remote_addr);
196
197 // Moves as much data as possible from the sender's buffer to the network
198 void SendTcp(VirtualSocket* socket);
199
Niels Möllerc79bd432021-02-16 09:25:52 +0100200 // Like above, but lookup sender by address.
201 void SendTcp(const SocketAddress& addr);
202
203 // Computes the number of milliseconds required to send a packet of this size.
204 uint32_t SendDelay(uint32_t size);
205
206 // Cancel attempts to connect to a socket that is being closed.
207 void CancelConnects(VirtualSocket* socket);
208
209 // Clear incoming messages for a socket that is being closed.
210 void Clear(VirtualSocket* socket);
211
212 void ProcessOneMessage();
213
214 void PostSignalReadEvent(VirtualSocket* socket);
215
216 // Sending was previously blocked, but now isn't.
217 sigslot::signal0<> SignalReadyToSend;
218
219 protected:
220 // Returns a new IP not used before in this network.
221 IPAddress GetNextIP(int family);
222
223 // Find the socket bound to the given address
224 VirtualSocket* LookupBinding(const SocketAddress& addr);
225
226 private:
227 uint16_t GetNextPort();
228
229 VirtualSocket* CreateSocketInternal(int family, int type);
230
231 // Find the socket pair corresponding to this server address.
232 VirtualSocket* LookupConnection(const SocketAddress& client,
233 const SocketAddress& server);
234
235 void RemoveConnection(const SocketAddress& client,
236 const SocketAddress& server);
237
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200238 // Places a packet on the network.
239 void AddPacketToNetwork(VirtualSocket* socket,
240 VirtualSocket* recipient,
241 int64_t cur_time,
242 const char* data,
243 size_t data_size,
244 size_t header_size,
245 bool ordered);
246
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200247 // If the delay has been set for the address of the socket, returns the set
248 // delay. Otherwise, returns a random transit delay chosen from the
249 // appropriate distribution.
250 uint32_t GetTransitDelay(Socket* socket);
251
Niels Möller983627c2021-02-09 15:12:28 +0100252 // Basic operations on functions.
253 static std::unique_ptr<Function> Accumulate(std::unique_ptr<Function> f);
254 static std::unique_ptr<Function> Invert(std::unique_ptr<Function> f);
255 static std::unique_ptr<Function> Resample(std::unique_ptr<Function> f,
256 double x1,
257 double x2,
258 uint32_t samples);
259 static double Evaluate(const Function* f, double x);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200260
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200261 // Determine if two sockets should be able to communicate.
262 // We don't (currently) specify an address family for sockets; instead,
263 // the currently bound address is used to infer the address family.
264 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
265 // dual-stack capable.
266 // This function tests if two addresses can communicate, as well as the
267 // sockets to which they may be bound (the addresses may or may not yet be
268 // bound to the sockets).
269 // First the addresses are tested (after normalization):
270 // If both have the same family, then communication is OK.
271 // If only one is IPv4 then false, unless the other is bound to ::.
272 // This applies even if the IPv4 address is 0.0.0.0.
273 // The socket arguments are optional; the sockets are checked to see if they
274 // were explicitly bound to IPv6-any ('::'), and if so communication is
275 // permitted.
276 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
277 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
278
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200279 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
280 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
281
282 // May be null if the test doesn't use a fake clock, or it does but doesn't
283 // use ProcessMessagesUntilIdle.
Sebastian Janssond624c392019-04-17 10:36:03 +0200284 ThreadProcessingFakeClock* fake_clock_ = nullptr;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200285
286 // Used to implement Wait/WakeUp.
287 Event wakeup_;
Sebastian Jansson290de822020-01-09 14:20:23 +0100288 Thread* msg_queue_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200289 bool stop_on_idle_;
290 in_addr next_ipv4_;
291 in6_addr next_ipv6_;
292 uint16_t next_port_;
293 AddressMap* bindings_;
294 ConnectionMap* connections_;
295
296 IPAddress default_route_v4_;
297 IPAddress default_route_v6_;
298
299 uint32_t bandwidth_;
300 uint32_t network_capacity_;
301 uint32_t send_buffer_capacity_;
302 uint32_t recv_buffer_capacity_;
303 uint32_t delay_mean_;
304 uint32_t delay_stddev_;
305 uint32_t delay_samples_;
306
Taylor Brandstetter389a97c2018-01-03 16:26:06 -0800307 // Used for testing.
308 uint32_t sent_packets_ = 0;
309
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200310 std::map<rtc::IPAddress, int> delay_by_ip_;
deadbeef5c3c1042017-08-04 15:01:57 -0700311 std::map<rtc::IPAddress, rtc::IPAddress> alternative_address_mapping_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200312 std::unique_ptr<Function> delay_dist_;
313
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200314 double drop_prob_;
Harald Alvestrand3d792e92021-03-10 07:29:28 +0000315 // The largest UDP payload permitted on this virtual socket server.
316 // The default is the max size of IPv4 fragmented UDP packet payload:
317 // 65535 bytes - 8 bytes UDP header - 20 bytes IP header.
318 size_t max_udp_payload_ = 65507;
319 // The largest UDP payload seen so far.
320 size_t largest_seen_udp_payload_ = 0;
321
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200322 bool sending_blocked_ = false;
323 RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
324};
325
326// Implements the socket interface using the virtual network. Packets are
327// passed as messages using the message queue of the socket server.
Niels Möllerd0b88792021-08-12 10:32:30 +0200328class VirtualSocket : public Socket,
Tomas Gunnarssond9663472020-11-21 16:20:23 +0100329 public MessageHandler,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200330 public sigslot::has_slots<> {
331 public:
332 VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
333 ~VirtualSocket() override;
334
335 SocketAddress GetLocalAddress() const override;
336 SocketAddress GetRemoteAddress() const override;
337
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200338 int Bind(const SocketAddress& addr) override;
339 int Connect(const SocketAddress& addr) override;
340 int Close() override;
341 int Send(const void* pv, size_t cb) override;
342 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
343 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
344 int RecvFrom(void* pv,
345 size_t cb,
346 SocketAddress* paddr,
347 int64_t* timestamp) override;
348 int Listen(int backlog) override;
349 VirtualSocket* Accept(SocketAddress* paddr) override;
350
351 int GetError() const override;
352 void SetError(int error) override;
353 ConnState GetState() const override;
354 int GetOption(Option opt, int* value) override;
355 int SetOption(Option opt, int value) override;
356 void OnMessage(Message* pmsg) override;
357
Niels Möllerc79bd432021-02-16 09:25:52 +0100358 size_t recv_buffer_size() const { return recv_buffer_size_; }
359 size_t send_buffer_size() const { return send_buffer_.size(); }
360 const char* send_buffer_data() const { return send_buffer_.data(); }
361
362 // Used by server sockets to set the local address without binding.
363 void SetLocalAddress(const SocketAddress& addr);
364
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200365 bool was_any() { return was_any_; }
366 void set_was_any(bool was_any) { was_any_ = was_any; }
367
Niels Möllerc79bd432021-02-16 09:25:52 +0100368 void SetToBlocked();
369
370 void UpdateRecv(size_t data_size);
371 void UpdateSend(size_t data_size);
372
373 void MaybeSignalWriteEvent(size_t capacity);
374
375 // Adds a packet to be sent. Returns delay, based on network_size_.
376 uint32_t AddPacket(int64_t cur_time, size_t packet_size);
377
378 int64_t UpdateOrderedDelivery(int64_t ts);
379
380 // Removes stale packets from the network. Returns current size.
381 size_t PurgeNetworkPackets(int64_t cur_time);
382
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200383 private:
384 struct NetworkEntry {
385 size_t size;
386 int64_t done_time;
387 };
388
389 typedef std::deque<SocketAddress> ListenQueue;
390 typedef std::deque<NetworkEntry> NetworkQueue;
391 typedef std::vector<char> SendBuffer;
392 typedef std::list<Packet*> RecvBuffer;
393 typedef std::map<Option, int> OptionsMap;
394
395 int InitiateConnect(const SocketAddress& addr, bool use_delay);
Niels Möllerc413c552021-06-22 10:03:14 +0200396 void CompleteConnect(const SocketAddress& addr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200397 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
398 int SendTcp(const void* pv, size_t cb);
399
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200400 void OnSocketServerReadyToSend();
401
Niels Möller257f81b2021-06-17 16:58:59 +0200402 VirtualSocketServer* const server_;
403 const int type_;
404 const bool async_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200405 ConnState state_;
406 int error_;
407 SocketAddress local_addr_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200408 SocketAddress remote_addr_;
409
410 // Pending sockets which can be Accepted
Niels Möllerc413c552021-06-22 10:03:14 +0200411 std::unique_ptr<ListenQueue> listen_queue_ RTC_GUARDED_BY(mutex_)
412 RTC_PT_GUARDED_BY(mutex_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200413
414 // Data which tcp has buffered for sending
415 SendBuffer send_buffer_;
416 // Set to false if the last attempt to send resulted in EWOULDBLOCK.
417 // Set back to true when the socket can send again.
418 bool ready_to_send_ = true;
419
Niels Möllerc413c552021-06-22 10:03:14 +0200420 // Mutex to protect the recv_buffer and listen_queue_
421 webrtc::Mutex mutex_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200422
423 // Network model that enforces bandwidth and capacity constraints
424 NetworkQueue network_;
425 size_t network_size_;
426 // The scheduled delivery time of the last packet sent on this socket.
427 // It is used to ensure ordered delivery of packets sent on this socket.
428 int64_t last_delivery_time_ = 0;
429
430 // Data which has been received from the network
Niels Möllerc413c552021-06-22 10:03:14 +0200431 RecvBuffer recv_buffer_ RTC_GUARDED_BY(mutex_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200432 // The amount of data which is in flight or in recv_buffer_
433 size_t recv_buffer_size_;
434
435 // Is this socket bound?
436 bool bound_;
437
438 // When we bind a socket to Any, VSS's Bind gives it another address. For
439 // dual-stack sockets, we want to distinguish between sockets that were
440 // explicitly given a particular address and sockets that had one picked
441 // for them by VSS.
442 bool was_any_;
443
444 // Store the options that are set
445 OptionsMap options_map_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200446};
447
448} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449
Steve Anton10542f22019-01-11 09:11:00 -0800450#endif // RTC_BASE_VIRTUAL_SOCKET_SERVER_H_