blob: 0ab2af29fbc9da07fcfa54f7a7eda470b0a7f232 [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
11#ifndef WEBRTC_BASE_VIRTUALSOCKETSERVER_H_
12#define WEBRTC_BASE_VIRTUALSOCKETSERVER_H_
13
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#include <deque>
15#include <map>
16
kwiberg22487b22016-09-13 01:17:10 -070017#include "webrtc/base/checks.h"
kwiberg4485ffb2016-04-26 08:14:39 -070018#include "webrtc/base/constructormagic.h"
deadbeef98e186c2017-05-16 18:00:06 -070019#include "webrtc/base/event.h"
deadbeef22e08142017-06-12 14:30:28 -070020#include "webrtc/base/fakeclock.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include "webrtc/base/messagequeue.h"
22#include "webrtc/base/socketserver.h"
23
24namespace rtc {
25
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +000026class Packet;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027class VirtualSocket;
28class SocketAddressPair;
29
30// Simulates a network in the same manner as a loopback interface. The
31// interface can create as many addresses as you want. All of the sockets
32// created by this network will be able to communicate with one another, unless
33// they are bound to addresses from incompatible families.
34class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
35 public:
deadbeef98e186c2017-05-16 18:00:06 -070036 VirtualSocketServer();
deadbeef22e08142017-06-12 14:30:28 -070037 // This constructor needs to be used if the test uses a fake clock and
38 // ProcessMessagesUntilIdle, since ProcessMessagesUntilIdle needs a way of
39 // advancing time.
40 explicit VirtualSocketServer(FakeClock* fake_clock);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000041 ~VirtualSocketServer() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042
Guo-wei Shieh38f88932015-08-13 22:24:02 -070043 // The default route indicates which local address to use when a socket is
44 // bound to the 'any' address, e.g. 0.0.0.0.
45 IPAddress GetDefaultRoute(int family);
46 void SetDefaultRoute(const IPAddress& from_addr);
47
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048 // Limits the network bandwidth (maximum bytes per second). Zero means that
49 // all sends occur instantly. Defaults to 0.
Peter Boström0c4e06b2015-10-07 12:23:21 +020050 uint32_t bandwidth() const { return bandwidth_; }
51 void set_bandwidth(uint32_t bandwidth) { bandwidth_ = bandwidth; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052
53 // Limits the amount of data which can be in flight on the network without
54 // packet loss (on a per sender basis). Defaults to 64 KB.
Peter Boström0c4e06b2015-10-07 12:23:21 +020055 uint32_t network_capacity() const { return network_capacity_; }
56 void set_network_capacity(uint32_t capacity) { network_capacity_ = capacity; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057
58 // The amount of data which can be buffered by tcp on the sender's side
Peter Boström0c4e06b2015-10-07 12:23:21 +020059 uint32_t send_buffer_capacity() const { return send_buffer_capacity_; }
60 void set_send_buffer_capacity(uint32_t capacity) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061 send_buffer_capacity_ = capacity;
62 }
63
64 // The amount of data which can be buffered by tcp on the receiver's side
Peter Boström0c4e06b2015-10-07 12:23:21 +020065 uint32_t recv_buffer_capacity() const { return recv_buffer_capacity_; }
66 void set_recv_buffer_capacity(uint32_t capacity) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000067 recv_buffer_capacity_ = capacity;
68 }
69
70 // Controls the (transit) delay for packets sent in the network. This does
71 // not inclue the time required to sit in the send queue. Both of these
72 // values are measured in milliseconds. Defaults to no delay.
Peter Boström0c4e06b2015-10-07 12:23:21 +020073 uint32_t delay_mean() const { return delay_mean_; }
74 uint32_t delay_stddev() const { return delay_stddev_; }
75 uint32_t delay_samples() const { return delay_samples_; }
76 void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
77 void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
78 void set_delay_samples(uint32_t delay_samples) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079 delay_samples_ = delay_samples;
80 }
81
82 // If the (transit) delay parameters are modified, this method should be
83 // called to recompute the new distribution.
84 void UpdateDelayDistribution();
85
86 // Controls the (uniform) probability that any sent packet is dropped. This
87 // is separate from calculations to drop based on queue size.
88 double drop_probability() { return drop_prob_; }
89 void set_drop_probability(double drop_prob) {
kwiberg22487b22016-09-13 01:17:10 -070090 RTC_DCHECK_GE(drop_prob, 0.0);
91 RTC_DCHECK_LE(drop_prob, 1.0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092 drop_prob_ = drop_prob;
93 }
94
Taylor Brandstettere7536412016-09-09 13:16:15 -070095 // If |blocked| is true, subsequent attempts to send will result in -1 being
96 // returned, with the socket error set to EWOULDBLOCK.
97 //
98 // If this method is later called with |blocked| set to false, any sockets
99 // that previously failed to send with EWOULDBLOCK will emit SignalWriteEvent.
100 //
101 // This can be used to simulate the send buffer on a network interface being
102 // full, and test functionality related to EWOULDBLOCK/SignalWriteEvent.
103 void SetSendingBlocked(bool blocked);
104
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105 // SocketFactory:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000106 Socket* CreateSocket(int type) override;
107 Socket* CreateSocket(int family, int type) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000108
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000109 AsyncSocket* CreateAsyncSocket(int type) override;
110 AsyncSocket* CreateAsyncSocket(int family, int type) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111
112 // SocketServer:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000113 void SetMessageQueue(MessageQueue* queue) override;
114 bool Wait(int cms, bool process_io) override;
115 void WakeUp() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700117 void SetDelayOnAddress(const rtc::SocketAddress& address, int delay_ms) {
118 delay_by_ip_[address.ipaddr()] = delay_ms;
119 }
120
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121 typedef std::pair<double, double> Point;
122 typedef std::vector<Point> Function;
123
Peter Boström0c4e06b2015-10-07 12:23:21 +0200124 static Function* CreateDistribution(uint32_t mean,
125 uint32_t stddev,
126 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000127
128 // Similar to Thread::ProcessMessages, but it only processes messages until
129 // there are no immediate messages or pending network traffic. Returns false
130 // if Thread::Stop() was called.
131 bool ProcessMessagesUntilIdle();
132
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000133 // Sets the next port number to use for testing.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200134 void SetNextPortForTesting(uint16_t port);
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000135
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700136 // Close a pair of Tcp connections by addresses. Both connections will have
137 // its own OnClose invoked.
138 bool CloseTcpConnections(const SocketAddress& addr_local,
139 const SocketAddress& addr_remote);
140
tommi5ce1a2a2016-05-14 03:19:31 -0700141 // For testing purpose only. Fired when a client socket is created.
142 sigslot::signal1<VirtualSocket*> SignalSocketCreated;
143
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 protected:
145 // Returns a new IP not used before in this network.
146 IPAddress GetNextIP(int family);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200147 uint16_t GetNextPort();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148
149 VirtualSocket* CreateSocketInternal(int family, int type);
150
151 // Binds the given socket to addr, assigning and IP and Port if necessary
152 int Bind(VirtualSocket* socket, SocketAddress* addr);
153
154 // Binds the given socket to the given (fully-defined) address.
155 int Bind(VirtualSocket* socket, const SocketAddress& addr);
156
157 // Find the socket bound to the given address
158 VirtualSocket* LookupBinding(const SocketAddress& addr);
159
160 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
161
162 // Adds a mapping between this socket pair and the socket.
163 void AddConnection(const SocketAddress& client,
164 const SocketAddress& server,
165 VirtualSocket* socket);
166
167 // Find the socket pair corresponding to this server address.
168 VirtualSocket* LookupConnection(const SocketAddress& client,
169 const SocketAddress& server);
170
171 void RemoveConnection(const SocketAddress& client,
172 const SocketAddress& server);
173
174 // Connects the given socket to the socket at the given address
175 int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
176 bool use_delay);
177
178 // Sends a disconnect message to the socket at the given address
179 bool Disconnect(VirtualSocket* socket);
180
181 // Sends the given packet to the socket at the given address (if one exists).
182 int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
183 const SocketAddress& remote_addr);
184
185 // Moves as much data as possible from the sender's buffer to the network
186 void SendTcp(VirtualSocket* socket);
187
188 // Places a packet on the network.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200189 void AddPacketToNetwork(VirtualSocket* socket,
190 VirtualSocket* recipient,
Honghai Zhang82d78622016-05-06 11:29:15 -0700191 int64_t cur_time,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200192 const char* data,
193 size_t data_size,
194 size_t header_size,
195 bool ordered);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196
197 // Removes stale packets from the network
Honghai Zhang82d78622016-05-06 11:29:15 -0700198 void PurgeNetworkPackets(VirtualSocket* socket, int64_t cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199
200 // Computes the number of milliseconds required to send a packet of this size.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200201 uint32_t SendDelay(uint32_t size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700203 // If the delay has been set for the address of the socket, returns the set
204 // delay. Otherwise, returns a random transit delay chosen from the
205 // appropriate distribution.
206 uint32_t GetTransitDelay(Socket* socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000207
208 // Basic operations on functions. Those that return a function also take
209 // ownership of the function given (and hence, may modify or delete it).
210 static Function* Accumulate(Function* f);
211 static Function* Invert(Function* f);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 static Function* Resample(Function* f,
213 double x1,
214 double x2,
215 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000216 static double Evaluate(Function* f, double x);
217
deadbeef37f5ecf2017-02-27 14:06:41 -0800218 // Null out our message queue if it goes away. Necessary in the case where
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219 // our lifetime is greater than that of the thread we are using, since we
220 // try to send Close messages for all connected sockets when we shutdown.
deadbeef37f5ecf2017-02-27 14:06:41 -0800221 void OnMessageQueueDestroyed() { msg_queue_ = nullptr; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222
223 // Determine if two sockets should be able to communicate.
224 // We don't (currently) specify an address family for sockets; instead,
225 // the currently bound address is used to infer the address family.
226 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
227 // dual-stack capable.
228 // This function tests if two addresses can communicate, as well as the
229 // sockets to which they may be bound (the addresses may or may not yet be
230 // bound to the sockets).
231 // First the addresses are tested (after normalization):
232 // If both have the same family, then communication is OK.
233 // If only one is IPv4 then false, unless the other is bound to ::.
234 // This applies even if the IPv4 address is 0.0.0.0.
235 // The socket arguments are optional; the sockets are checked to see if they
236 // were explicitly bound to IPv6-any ('::'), and if so communication is
237 // permitted.
238 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
239 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
240
241 private:
242 friend class VirtualSocket;
243
Taylor Brandstettere7536412016-09-09 13:16:15 -0700244 // Sending was previously blocked, but now isn't.
245 sigslot::signal0<> SignalReadyToSend;
246
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
248 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
249
deadbeef22e08142017-06-12 14:30:28 -0700250 // May be null if the test doesn't use a fake clock, or it does but doesn't
251 // use ProcessMessagesUntilIdle.
252 FakeClock* fake_clock_ = nullptr;
253
deadbeef98e186c2017-05-16 18:00:06 -0700254 // Used to implement Wait/WakeUp.
255 Event wakeup_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 MessageQueue* msg_queue_;
257 bool stop_on_idle_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258 in_addr next_ipv4_;
259 in6_addr next_ipv6_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200260 uint16_t next_port_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 AddressMap* bindings_;
262 ConnectionMap* connections_;
263
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700264 IPAddress default_route_v4_;
265 IPAddress default_route_v6_;
266
Peter Boström0c4e06b2015-10-07 12:23:21 +0200267 uint32_t bandwidth_;
268 uint32_t network_capacity_;
269 uint32_t send_buffer_capacity_;
270 uint32_t recv_buffer_capacity_;
271 uint32_t delay_mean_;
272 uint32_t delay_stddev_;
273 uint32_t delay_samples_;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700274
275 std::map<rtc::IPAddress, int> delay_by_ip_;
276 std::unique_ptr<Function> delay_dist_;
277
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 CriticalSection delay_crit_;
279
280 double drop_prob_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700281 bool sending_blocked_ = false;
henrikg3c089d72015-09-16 05:37:44 -0700282 RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283};
284
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000285// Implements the socket interface using the virtual network. Packets are
286// passed as messages using the message queue of the socket server.
Taylor Brandstettere7536412016-09-09 13:16:15 -0700287class VirtualSocket : public AsyncSocket,
288 public MessageHandler,
289 public sigslot::has_slots<> {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000290 public:
291 VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000292 ~VirtualSocket() override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000293
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000294 SocketAddress GetLocalAddress() const override;
295 SocketAddress GetRemoteAddress() const override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000296
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000297 // Used by TurnPortTest to mimic a case where proxy returns local host address
298 // instead of the original one TurnPort was bound against. Please see WebRTC
299 // issue 3927 for more detail.
300 void SetAlternativeLocalAddress(const SocketAddress& addr);
301
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000302 int Bind(const SocketAddress& addr) override;
303 int Connect(const SocketAddress& addr) override;
304 int Close() override;
305 int Send(const void* pv, size_t cb) override;
306 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
Stefan Holmer9131efd2016-05-23 18:19:26 +0200307 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
308 int RecvFrom(void* pv,
309 size_t cb,
310 SocketAddress* paddr,
311 int64_t* timestamp) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000312 int Listen(int backlog) override;
313 VirtualSocket* Accept(SocketAddress* paddr) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000314
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000315 int GetError() const override;
316 void SetError(int error) override;
317 ConnState GetState() const override;
318 int GetOption(Option opt, int* value) override;
319 int SetOption(Option opt, int value) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000320 void OnMessage(Message* pmsg) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000321
322 bool was_any() { return was_any_; }
323 void set_was_any(bool was_any) { was_any_ = was_any; }
324
325 // For testing purpose only. Fired when client socket is bound to an address.
326 sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
327
328 private:
329 struct NetworkEntry {
330 size_t size;
Honghai Zhang82d78622016-05-06 11:29:15 -0700331 int64_t done_time;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000332 };
333
334 typedef std::deque<SocketAddress> ListenQueue;
335 typedef std::deque<NetworkEntry> NetworkQueue;
336 typedef std::vector<char> SendBuffer;
337 typedef std::list<Packet*> RecvBuffer;
338 typedef std::map<Option, int> OptionsMap;
339
340 int InitiateConnect(const SocketAddress& addr, bool use_delay);
341 void CompleteConnect(const SocketAddress& addr, bool notify);
342 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
343 int SendTcp(const void* pv, size_t cb);
344
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700345 // Used by server sockets to set the local address without binding.
346 void SetLocalAddress(const SocketAddress& addr);
347
Taylor Brandstettere7536412016-09-09 13:16:15 -0700348 void OnSocketServerReadyToSend();
349
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000350 VirtualSocketServer* server_;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000351 int type_;
352 bool async_;
353 ConnState state_;
354 int error_;
355 SocketAddress local_addr_;
356 SocketAddress alternative_local_addr_;
357 SocketAddress remote_addr_;
358
359 // Pending sockets which can be Accepted
360 ListenQueue* listen_queue_;
361
362 // Data which tcp has buffered for sending
363 SendBuffer send_buffer_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700364 // Set to false if the last attempt to send resulted in EWOULDBLOCK.
365 // Set back to true when the socket can send again.
366 bool ready_to_send_ = true;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000367
368 // Critical section to protect the recv_buffer and queue_
369 CriticalSection crit_;
370
371 // Network model that enforces bandwidth and capacity constraints
372 NetworkQueue network_;
373 size_t network_size_;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700374 // The scheduled delivery time of the last packet sent on this socket.
375 // It is used to ensure ordered delivery of packets sent on this socket.
376 int64_t last_delivery_time_ = 0;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000377
378 // Data which has been received from the network
379 RecvBuffer recv_buffer_;
380 // The amount of data which is in flight or in recv_buffer_
381 size_t recv_buffer_size_;
382
383 // Is this socket bound?
384 bool bound_;
385
386 // When we bind a socket to Any, VSS's Bind gives it another address. For
387 // dual-stack sockets, we want to distinguish between sockets that were
388 // explicitly given a particular address and sockets that had one picked
389 // for them by VSS.
390 bool was_any_;
391
392 // Store the options that are set
393 OptionsMap options_map_;
394
395 friend class VirtualSocketServer;
396};
397
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000398} // namespace rtc
399
400#endif // WEBRTC_BASE_VIRTUALSOCKETSERVER_H_