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