blob: 77ddb76d722ea9da8444fbf4bc4ef9c06e49cae5 [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;
Niels Möllerea423a52021-08-19 10:13:31 +020029class VirtualSocketServer;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020030class SocketAddressPair;
31
Niels Möllerea423a52021-08-19 10:13:31 +020032// Implements the socket interface using the virtual network. Packets are
33// passed as messages using the message queue of the socket server.
34class VirtualSocket : public Socket,
35 public MessageHandler,
36 public sigslot::has_slots<> {
37 public:
38 VirtualSocket(VirtualSocketServer* server, int family, int type);
39 ~VirtualSocket() override;
40
41 SocketAddress GetLocalAddress() const override;
42 SocketAddress GetRemoteAddress() const override;
43
44 int Bind(const SocketAddress& addr) override;
45 int Connect(const SocketAddress& addr) override;
46 int Close() override;
47 int Send(const void* pv, size_t cb) override;
48 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
49 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
50 int RecvFrom(void* pv,
51 size_t cb,
52 SocketAddress* paddr,
53 int64_t* timestamp) override;
54 int Listen(int backlog) override;
55 VirtualSocket* Accept(SocketAddress* paddr) override;
56
57 int GetError() const override;
58 void SetError(int error) override;
59 ConnState GetState() const override;
60 int GetOption(Option opt, int* value) override;
61 int SetOption(Option opt, int value) override;
62 void OnMessage(Message* pmsg) override;
63
64 size_t recv_buffer_size() const { return recv_buffer_size_; }
65 size_t send_buffer_size() const { return send_buffer_.size(); }
66 const char* send_buffer_data() const { return send_buffer_.data(); }
67
68 // Used by server sockets to set the local address without binding.
69 void SetLocalAddress(const SocketAddress& addr);
70
71 bool was_any() { return was_any_; }
72 void set_was_any(bool was_any) { was_any_ = was_any; }
73
74 void SetToBlocked();
75
76 void UpdateRecv(size_t data_size);
77 void UpdateSend(size_t data_size);
78
79 void MaybeSignalWriteEvent(size_t capacity);
80
81 // Adds a packet to be sent. Returns delay, based on network_size_.
82 uint32_t AddPacket(int64_t cur_time, size_t packet_size);
83
84 int64_t UpdateOrderedDelivery(int64_t ts);
85
86 // Removes stale packets from the network. Returns current size.
87 size_t PurgeNetworkPackets(int64_t cur_time);
88
89 private:
90 struct NetworkEntry {
91 size_t size;
92 int64_t done_time;
93 };
94
95 typedef std::deque<SocketAddress> ListenQueue;
96 typedef std::deque<NetworkEntry> NetworkQueue;
97 typedef std::vector<char> SendBuffer;
98 typedef std::list<Packet*> RecvBuffer;
99 typedef std::map<Option, int> OptionsMap;
100
101 int InitiateConnect(const SocketAddress& addr, bool use_delay);
102 void CompleteConnect(const SocketAddress& addr);
103 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
104 int SendTcp(const void* pv, size_t cb);
105
106 void OnSocketServerReadyToSend();
107
108 VirtualSocketServer* const server_;
109 const int type_;
110 ConnState state_;
111 int error_;
112 SocketAddress local_addr_;
113 SocketAddress remote_addr_;
114
115 // Pending sockets which can be Accepted
116 std::unique_ptr<ListenQueue> listen_queue_ RTC_GUARDED_BY(mutex_)
117 RTC_PT_GUARDED_BY(mutex_);
118
119 // Data which tcp has buffered for sending
120 SendBuffer send_buffer_;
121 // Set to false if the last attempt to send resulted in EWOULDBLOCK.
122 // Set back to true when the socket can send again.
123 bool ready_to_send_ = true;
124
125 // Mutex to protect the recv_buffer and listen_queue_
126 webrtc::Mutex mutex_;
127
128 // Network model that enforces bandwidth and capacity constraints
129 NetworkQueue network_;
130 size_t network_size_;
131 // The scheduled delivery time of the last packet sent on this socket.
132 // It is used to ensure ordered delivery of packets sent on this socket.
133 int64_t last_delivery_time_ = 0;
134
135 // Data which has been received from the network
136 RecvBuffer recv_buffer_ RTC_GUARDED_BY(mutex_);
137 // The amount of data which is in flight or in recv_buffer_
138 size_t recv_buffer_size_;
139
140 // Is this socket bound?
141 bool bound_;
142
143 // When we bind a socket to Any, VSS's Bind gives it another address. For
144 // dual-stack sockets, we want to distinguish between sockets that were
145 // explicitly given a particular address and sockets that had one picked
146 // for them by VSS.
147 bool was_any_;
148
149 // Store the options that are set
150 OptionsMap options_map_;
151};
152
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200153// Simulates a network in the same manner as a loopback interface. The
154// interface can create as many addresses as you want. All of the sockets
155// created by this network will be able to communicate with one another, unless
156// they are bound to addresses from incompatible families.
Niels Möller9bd24572021-04-19 12:18:27 +0200157class VirtualSocketServer : public SocketServer {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200158 public:
159 VirtualSocketServer();
160 // This constructor needs to be used if the test uses a fake clock and
161 // ProcessMessagesUntilIdle, since ProcessMessagesUntilIdle needs a way of
162 // advancing time.
Sebastian Janssond624c392019-04-17 10:36:03 +0200163 explicit VirtualSocketServer(ThreadProcessingFakeClock* fake_clock);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164 ~VirtualSocketServer() override;
165
Niels Möller84d15952021-09-01 10:50:34 +0200166 // The default source address specifies which local address to use when a
167 // socket is bound to the 'any' address, e.g. 0.0.0.0. (If not set, the 'any'
168 // address is used as the source address on outgoing virtual packets, exposed
169 // to recipient's RecvFrom).
170 IPAddress GetDefaultSourceAddress(int family);
171 void SetDefaultSourceAddress(const IPAddress& from_addr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200172
173 // Limits the network bandwidth (maximum bytes per second). Zero means that
174 // all sends occur instantly. Defaults to 0.
175 uint32_t bandwidth() const { return bandwidth_; }
176 void set_bandwidth(uint32_t bandwidth) { bandwidth_ = bandwidth; }
177
178 // Limits the amount of data which can be in flight on the network without
179 // packet loss (on a per sender basis). Defaults to 64 KB.
180 uint32_t network_capacity() const { return network_capacity_; }
181 void set_network_capacity(uint32_t capacity) { network_capacity_ = capacity; }
182
183 // The amount of data which can be buffered by tcp on the sender's side
184 uint32_t send_buffer_capacity() const { return send_buffer_capacity_; }
185 void set_send_buffer_capacity(uint32_t capacity) {
186 send_buffer_capacity_ = capacity;
187 }
188
189 // The amount of data which can be buffered by tcp on the receiver's side
190 uint32_t recv_buffer_capacity() const { return recv_buffer_capacity_; }
191 void set_recv_buffer_capacity(uint32_t capacity) {
192 recv_buffer_capacity_ = capacity;
193 }
194
195 // Controls the (transit) delay for packets sent in the network. This does
196 // not inclue the time required to sit in the send queue. Both of these
197 // values are measured in milliseconds. Defaults to no delay.
198 uint32_t delay_mean() const { return delay_mean_; }
199 uint32_t delay_stddev() const { return delay_stddev_; }
200 uint32_t delay_samples() const { return delay_samples_; }
201 void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
202 void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
203 void set_delay_samples(uint32_t delay_samples) {
204 delay_samples_ = delay_samples;
205 }
206
207 // If the (transit) delay parameters are modified, this method should be
208 // called to recompute the new distribution.
209 void UpdateDelayDistribution();
210
211 // Controls the (uniform) probability that any sent packet is dropped. This
212 // is separate from calculations to drop based on queue size.
213 double drop_probability() { return drop_prob_; }
214 void set_drop_probability(double drop_prob) {
215 RTC_DCHECK_GE(drop_prob, 0.0);
216 RTC_DCHECK_LE(drop_prob, 1.0);
217 drop_prob_ = drop_prob;
218 }
219
Harald Alvestrand3d792e92021-03-10 07:29:28 +0000220 // Controls the maximum UDP payload for the networks simulated
221 // by this server. Any UDP payload sent that is larger than this will
222 // be dropped.
223 size_t max_udp_payload() { return max_udp_payload_; }
224 void set_max_udp_payload(size_t payload_size) {
225 max_udp_payload_ = payload_size;
226 }
227
228 size_t largest_seen_udp_payload() { return largest_seen_udp_payload_; }
229
Artem Titov96e3b992021-07-26 16:03:14 +0200230 // If `blocked` is true, subsequent attempts to send will result in -1 being
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200231 // returned, with the socket error set to EWOULDBLOCK.
232 //
Artem Titov96e3b992021-07-26 16:03:14 +0200233 // If this method is later called with `blocked` set to false, any sockets
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200234 // that previously failed to send with EWOULDBLOCK will emit SignalWriteEvent.
235 //
236 // This can be used to simulate the send buffer on a network interface being
237 // full, and test functionality related to EWOULDBLOCK/SignalWriteEvent.
238 void SetSendingBlocked(bool blocked);
239
240 // SocketFactory:
Niels Möllerea423a52021-08-19 10:13:31 +0200241 VirtualSocket* CreateSocket(int family, int type) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200242
243 // SocketServer:
Sebastian Jansson290de822020-01-09 14:20:23 +0100244 void SetMessageQueue(Thread* queue) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200245 bool Wait(int cms, bool process_io) override;
246 void WakeUp() override;
247
248 void SetDelayOnAddress(const rtc::SocketAddress& address, int delay_ms) {
249 delay_by_ip_[address.ipaddr()] = delay_ms;
250 }
251
deadbeef5c3c1042017-08-04 15:01:57 -0700252 // Used by TurnPortTest and TcpPortTest (for example), to mimic a case where
253 // a proxy returns the local host address instead of the original one the
254 // port was bound against. Please see WebRTC issue 3927 for more detail.
255 //
256 // If SetAlternativeLocalAddress(A, B) is called, then when something
257 // attempts to bind a socket to address A, it will get a socket bound to
258 // address B instead.
259 void SetAlternativeLocalAddress(const rtc::IPAddress& address,
260 const rtc::IPAddress& alternative);
261
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200262 typedef std::pair<double, double> Point;
263 typedef std::vector<Point> Function;
264
Niels Möller983627c2021-02-09 15:12:28 +0100265 static std::unique_ptr<Function> CreateDistribution(uint32_t mean,
266 uint32_t stddev,
267 uint32_t samples);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200268
269 // Similar to Thread::ProcessMessages, but it only processes messages until
270 // there are no immediate messages or pending network traffic. Returns false
271 // if Thread::Stop() was called.
272 bool ProcessMessagesUntilIdle();
273
274 // Sets the next port number to use for testing.
275 void SetNextPortForTesting(uint16_t port);
276
277 // Close a pair of Tcp connections by addresses. Both connections will have
278 // its own OnClose invoked.
279 bool CloseTcpConnections(const SocketAddress& addr_local,
280 const SocketAddress& addr_remote);
281
Taylor Brandstetter389a97c2018-01-03 16:26:06 -0800282 // Number of packets that clients have attempted to send through this virtual
283 // socket server. Intended to be used for test assertions.
284 uint32_t sent_packets() const { return sent_packets_; }
285
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200286 // Assign IP and Port if application's address is unspecified. Also apply
287 // `alternative_address_mapping_`.
288 SocketAddress AssignBindAddress(const SocketAddress& app_addr);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200289
290 // Binds the given socket to the given (fully-defined) address.
291 int Bind(VirtualSocket* socket, const SocketAddress& addr);
292
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200293 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
294
295 // Adds a mapping between this socket pair and the socket.
296 void AddConnection(const SocketAddress& client,
297 const SocketAddress& server,
298 VirtualSocket* socket);
299
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200300 // Connects the given socket to the socket at the given address
Yves Gerey665174f2018-06-19 15:03:05 +0200301 int Connect(VirtualSocket* socket,
302 const SocketAddress& remote_addr,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200303 bool use_delay);
304
305 // Sends a disconnect message to the socket at the given address
306 bool Disconnect(VirtualSocket* socket);
307
Niels Möllerc79bd432021-02-16 09:25:52 +0100308 // Lookup address, and disconnect corresponding socket.
309 bool Disconnect(const SocketAddress& addr);
310
311 // Lookup connection, close corresponding socket.
312 bool Disconnect(const SocketAddress& local_addr,
313 const SocketAddress& remote_addr);
314
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200315 // Sends the given packet to the socket at the given address (if one exists).
Yves Gerey665174f2018-06-19 15:03:05 +0200316 int SendUdp(VirtualSocket* socket,
317 const char* data,
318 size_t data_size,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200319 const SocketAddress& remote_addr);
320
321 // Moves as much data as possible from the sender's buffer to the network
322 void SendTcp(VirtualSocket* socket);
323
Niels Möllerc79bd432021-02-16 09:25:52 +0100324 // Like above, but lookup sender by address.
325 void SendTcp(const SocketAddress& addr);
326
327 // Computes the number of milliseconds required to send a packet of this size.
328 uint32_t SendDelay(uint32_t size);
329
330 // Cancel attempts to connect to a socket that is being closed.
331 void CancelConnects(VirtualSocket* socket);
332
333 // Clear incoming messages for a socket that is being closed.
334 void Clear(VirtualSocket* socket);
335
Niels Möllerc79bd432021-02-16 09:25:52 +0100336 void PostSignalReadEvent(VirtualSocket* socket);
337
338 // Sending was previously blocked, but now isn't.
339 sigslot::signal0<> SignalReadyToSend;
340
341 protected:
342 // Returns a new IP not used before in this network.
343 IPAddress GetNextIP(int family);
344
345 // Find the socket bound to the given address
346 VirtualSocket* LookupBinding(const SocketAddress& addr);
347
348 private:
349 uint16_t GetNextPort();
350
Niels Möllerc79bd432021-02-16 09:25:52 +0100351 // Find the socket pair corresponding to this server address.
352 VirtualSocket* LookupConnection(const SocketAddress& client,
353 const SocketAddress& server);
354
355 void RemoveConnection(const SocketAddress& client,
356 const SocketAddress& server);
357
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200358 // Places a packet on the network.
359 void AddPacketToNetwork(VirtualSocket* socket,
360 VirtualSocket* recipient,
361 int64_t cur_time,
362 const char* data,
363 size_t data_size,
364 size_t header_size,
365 bool ordered);
366
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200367 // If the delay has been set for the address of the socket, returns the set
368 // delay. Otherwise, returns a random transit delay chosen from the
369 // appropriate distribution.
370 uint32_t GetTransitDelay(Socket* socket);
371
Niels Möller983627c2021-02-09 15:12:28 +0100372 // Basic operations on functions.
373 static std::unique_ptr<Function> Accumulate(std::unique_ptr<Function> f);
374 static std::unique_ptr<Function> Invert(std::unique_ptr<Function> f);
375 static std::unique_ptr<Function> Resample(std::unique_ptr<Function> f,
376 double x1,
377 double x2,
378 uint32_t samples);
379 static double Evaluate(const Function* f, double x);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200380
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200381 // Determine if two sockets should be able to communicate.
382 // We don't (currently) specify an address family for sockets; instead,
383 // the currently bound address is used to infer the address family.
384 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
385 // dual-stack capable.
386 // This function tests if two addresses can communicate, as well as the
387 // sockets to which they may be bound (the addresses may or may not yet be
388 // bound to the sockets).
389 // First the addresses are tested (after normalization):
390 // If both have the same family, then communication is OK.
391 // If only one is IPv4 then false, unless the other is bound to ::.
392 // This applies even if the IPv4 address is 0.0.0.0.
393 // The socket arguments are optional; the sockets are checked to see if they
394 // were explicitly bound to IPv6-any ('::'), and if so communication is
395 // permitted.
396 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
397 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
398
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200399 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
400 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
401
402 // May be null if the test doesn't use a fake clock, or it does but doesn't
403 // use ProcessMessagesUntilIdle.
Sebastian Janssond624c392019-04-17 10:36:03 +0200404 ThreadProcessingFakeClock* fake_clock_ = nullptr;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200405
406 // Used to implement Wait/WakeUp.
407 Event wakeup_;
Sebastian Jansson290de822020-01-09 14:20:23 +0100408 Thread* msg_queue_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200409 bool stop_on_idle_;
410 in_addr next_ipv4_;
411 in6_addr next_ipv6_;
412 uint16_t next_port_;
413 AddressMap* bindings_;
414 ConnectionMap* connections_;
415
Niels Möller84d15952021-09-01 10:50:34 +0200416 IPAddress default_source_address_v4_;
417 IPAddress default_source_address_v6_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200418
419 uint32_t bandwidth_;
420 uint32_t network_capacity_;
421 uint32_t send_buffer_capacity_;
422 uint32_t recv_buffer_capacity_;
423 uint32_t delay_mean_;
424 uint32_t delay_stddev_;
425 uint32_t delay_samples_;
426
Taylor Brandstetter389a97c2018-01-03 16:26:06 -0800427 // Used for testing.
428 uint32_t sent_packets_ = 0;
429
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200430 std::map<rtc::IPAddress, int> delay_by_ip_;
deadbeef5c3c1042017-08-04 15:01:57 -0700431 std::map<rtc::IPAddress, rtc::IPAddress> alternative_address_mapping_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200432 std::unique_ptr<Function> delay_dist_;
433
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200434 double drop_prob_;
Harald Alvestrand3d792e92021-03-10 07:29:28 +0000435 // The largest UDP payload permitted on this virtual socket server.
436 // The default is the max size of IPv4 fragmented UDP packet payload:
437 // 65535 bytes - 8 bytes UDP header - 20 bytes IP header.
438 size_t max_udp_payload_ = 65507;
439 // The largest UDP payload seen so far.
440 size_t largest_seen_udp_payload_ = 0;
441
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200442 bool sending_blocked_ = false;
443 RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
444};
445
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200446} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447
Steve Anton10542f22019-01-11 09:11:00 -0800448#endif // RTC_BASE_VIRTUAL_SOCKET_SERVER_H_