blob: cce0279d32e2a786970ab9370545ea46e9033e22 [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"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include "webrtc/base/messagequeue.h"
20#include "webrtc/base/socketserver.h"
21
22namespace rtc {
23
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +000024class Packet;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025class VirtualSocket;
26class SocketAddressPair;
27
28// Simulates a network in the same manner as a loopback interface. The
29// interface can create as many addresses as you want. All of the sockets
30// created by this network will be able to communicate with one another, unless
31// they are bound to addresses from incompatible families.
32class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
33 public:
34 // TODO: Add "owned" parameter.
35 // If "owned" is set, the supplied socketserver will be deleted later.
36 explicit VirtualSocketServer(SocketServer* ss);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000037 ~VirtualSocketServer() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000038
39 SocketServer* socketserver() { return server_; }
40
Guo-wei Shieh38f88932015-08-13 22:24:02 -070041 // The default route indicates which local address to use when a socket is
42 // bound to the 'any' address, e.g. 0.0.0.0.
43 IPAddress GetDefaultRoute(int family);
44 void SetDefaultRoute(const IPAddress& from_addr);
45
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046 // Limits the network bandwidth (maximum bytes per second). Zero means that
47 // all sends occur instantly. Defaults to 0.
Peter Boström0c4e06b2015-10-07 12:23:21 +020048 uint32_t bandwidth() const { return bandwidth_; }
49 void set_bandwidth(uint32_t bandwidth) { bandwidth_ = bandwidth; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050
51 // Limits the amount of data which can be in flight on the network without
52 // packet loss (on a per sender basis). Defaults to 64 KB.
Peter Boström0c4e06b2015-10-07 12:23:21 +020053 uint32_t network_capacity() const { return network_capacity_; }
54 void set_network_capacity(uint32_t capacity) { network_capacity_ = capacity; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055
56 // The amount of data which can be buffered by tcp on the sender's side
Peter Boström0c4e06b2015-10-07 12:23:21 +020057 uint32_t send_buffer_capacity() const { return send_buffer_capacity_; }
58 void set_send_buffer_capacity(uint32_t capacity) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 send_buffer_capacity_ = capacity;
60 }
61
62 // The amount of data which can be buffered by tcp on the receiver's side
Peter Boström0c4e06b2015-10-07 12:23:21 +020063 uint32_t recv_buffer_capacity() const { return recv_buffer_capacity_; }
64 void set_recv_buffer_capacity(uint32_t capacity) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065 recv_buffer_capacity_ = capacity;
66 }
67
68 // Controls the (transit) delay for packets sent in the network. This does
69 // not inclue the time required to sit in the send queue. Both of these
70 // values are measured in milliseconds. Defaults to no delay.
Peter Boström0c4e06b2015-10-07 12:23:21 +020071 uint32_t delay_mean() const { return delay_mean_; }
72 uint32_t delay_stddev() const { return delay_stddev_; }
73 uint32_t delay_samples() const { return delay_samples_; }
74 void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
75 void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
76 void set_delay_samples(uint32_t delay_samples) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000077 delay_samples_ = delay_samples;
78 }
79
80 // If the (transit) delay parameters are modified, this method should be
81 // called to recompute the new distribution.
82 void UpdateDelayDistribution();
83
84 // Controls the (uniform) probability that any sent packet is dropped. This
85 // is separate from calculations to drop based on queue size.
86 double drop_probability() { return drop_prob_; }
87 void set_drop_probability(double drop_prob) {
kwiberg22487b22016-09-13 01:17:10 -070088 RTC_DCHECK_GE(drop_prob, 0.0);
89 RTC_DCHECK_LE(drop_prob, 1.0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090 drop_prob_ = drop_prob;
91 }
92
Taylor Brandstettere7536412016-09-09 13:16:15 -070093 // If |blocked| is true, subsequent attempts to send will result in -1 being
94 // returned, with the socket error set to EWOULDBLOCK.
95 //
96 // If this method is later called with |blocked| set to false, any sockets
97 // that previously failed to send with EWOULDBLOCK will emit SignalWriteEvent.
98 //
99 // This can be used to simulate the send buffer on a network interface being
100 // full, and test functionality related to EWOULDBLOCK/SignalWriteEvent.
101 void SetSendingBlocked(bool blocked);
102
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103 // SocketFactory:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000104 Socket* CreateSocket(int type) override;
105 Socket* CreateSocket(int family, int type) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000107 AsyncSocket* CreateAsyncSocket(int type) override;
108 AsyncSocket* CreateAsyncSocket(int family, int type) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000109
110 // SocketServer:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000111 void SetMessageQueue(MessageQueue* queue) override;
112 bool Wait(int cms, bool process_io) override;
113 void WakeUp() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000114
115 typedef std::pair<double, double> Point;
116 typedef std::vector<Point> Function;
117
Peter Boström0c4e06b2015-10-07 12:23:21 +0200118 static Function* CreateDistribution(uint32_t mean,
119 uint32_t stddev,
120 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121
122 // Similar to Thread::ProcessMessages, but it only processes messages until
123 // there are no immediate messages or pending network traffic. Returns false
124 // if Thread::Stop() was called.
125 bool ProcessMessagesUntilIdle();
126
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000127 // Sets the next port number to use for testing.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200128 void SetNextPortForTesting(uint16_t port);
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000129
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700130 // Close a pair of Tcp connections by addresses. Both connections will have
131 // its own OnClose invoked.
132 bool CloseTcpConnections(const SocketAddress& addr_local,
133 const SocketAddress& addr_remote);
134
tommi5ce1a2a2016-05-14 03:19:31 -0700135 // For testing purpose only. Fired when a client socket is created.
136 sigslot::signal1<VirtualSocket*> SignalSocketCreated;
137
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 protected:
139 // Returns a new IP not used before in this network.
140 IPAddress GetNextIP(int family);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200141 uint16_t GetNextPort();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142
143 VirtualSocket* CreateSocketInternal(int family, int type);
144
145 // Binds the given socket to addr, assigning and IP and Port if necessary
146 int Bind(VirtualSocket* socket, SocketAddress* addr);
147
148 // Binds the given socket to the given (fully-defined) address.
149 int Bind(VirtualSocket* socket, const SocketAddress& addr);
150
151 // Find the socket bound to the given address
152 VirtualSocket* LookupBinding(const SocketAddress& addr);
153
154 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
155
156 // Adds a mapping between this socket pair and the socket.
157 void AddConnection(const SocketAddress& client,
158 const SocketAddress& server,
159 VirtualSocket* socket);
160
161 // Find the socket pair corresponding to this server address.
162 VirtualSocket* LookupConnection(const SocketAddress& client,
163 const SocketAddress& server);
164
165 void RemoveConnection(const SocketAddress& client,
166 const SocketAddress& server);
167
168 // Connects the given socket to the socket at the given address
169 int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
170 bool use_delay);
171
172 // Sends a disconnect message to the socket at the given address
173 bool Disconnect(VirtualSocket* socket);
174
175 // Sends the given packet to the socket at the given address (if one exists).
176 int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
177 const SocketAddress& remote_addr);
178
179 // Moves as much data as possible from the sender's buffer to the network
180 void SendTcp(VirtualSocket* socket);
181
182 // Places a packet on the network.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200183 void AddPacketToNetwork(VirtualSocket* socket,
184 VirtualSocket* recipient,
Honghai Zhang82d78622016-05-06 11:29:15 -0700185 int64_t cur_time,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200186 const char* data,
187 size_t data_size,
188 size_t header_size,
189 bool ordered);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190
191 // Removes stale packets from the network
Honghai Zhang82d78622016-05-06 11:29:15 -0700192 void PurgeNetworkPackets(VirtualSocket* socket, int64_t cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193
194 // Computes the number of milliseconds required to send a packet of this size.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200195 uint32_t SendDelay(uint32_t size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196
197 // Returns a random transit delay chosen from the appropriate distribution.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200198 uint32_t GetRandomTransitDelay();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199
200 // Basic operations on functions. Those that return a function also take
201 // ownership of the function given (and hence, may modify or delete it).
202 static Function* Accumulate(Function* f);
203 static Function* Invert(Function* f);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200204 static Function* Resample(Function* f,
205 double x1,
206 double x2,
207 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000208 static double Evaluate(Function* f, double x);
209
210 // NULL out our message queue if it goes away. Necessary in the case where
211 // our lifetime is greater than that of the thread we are using, since we
212 // try to send Close messages for all connected sockets when we shutdown.
213 void OnMessageQueueDestroyed() { msg_queue_ = NULL; }
214
215 // Determine if two sockets should be able to communicate.
216 // We don't (currently) specify an address family for sockets; instead,
217 // the currently bound address is used to infer the address family.
218 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
219 // dual-stack capable.
220 // This function tests if two addresses can communicate, as well as the
221 // sockets to which they may be bound (the addresses may or may not yet be
222 // bound to the sockets).
223 // First the addresses are tested (after normalization):
224 // If both have the same family, then communication is OK.
225 // If only one is IPv4 then false, unless the other is bound to ::.
226 // This applies even if the IPv4 address is 0.0.0.0.
227 // The socket arguments are optional; the sockets are checked to see if they
228 // were explicitly bound to IPv6-any ('::'), and if so communication is
229 // permitted.
230 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
231 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
232
233 private:
234 friend class VirtualSocket;
235
Taylor Brandstettere7536412016-09-09 13:16:15 -0700236 // Sending was previously blocked, but now isn't.
237 sigslot::signal0<> SignalReadyToSend;
238
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
240 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
241
242 SocketServer* server_;
243 bool server_owned_;
244 MessageQueue* msg_queue_;
245 bool stop_on_idle_;
Honghai Zhang82d78622016-05-06 11:29:15 -0700246 int64_t network_delay_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 in_addr next_ipv4_;
248 in6_addr next_ipv6_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200249 uint16_t next_port_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 AddressMap* bindings_;
251 ConnectionMap* connections_;
252
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700253 IPAddress default_route_v4_;
254 IPAddress default_route_v6_;
255
Peter Boström0c4e06b2015-10-07 12:23:21 +0200256 uint32_t bandwidth_;
257 uint32_t network_capacity_;
258 uint32_t send_buffer_capacity_;
259 uint32_t recv_buffer_capacity_;
260 uint32_t delay_mean_;
261 uint32_t delay_stddev_;
262 uint32_t delay_samples_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000263 Function* delay_dist_;
264 CriticalSection delay_crit_;
265
266 double drop_prob_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700267 bool sending_blocked_ = false;
henrikg3c089d72015-09-16 05:37:44 -0700268 RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269};
270
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000271// Implements the socket interface using the virtual network. Packets are
272// passed as messages using the message queue of the socket server.
Taylor Brandstettere7536412016-09-09 13:16:15 -0700273class VirtualSocket : public AsyncSocket,
274 public MessageHandler,
275 public sigslot::has_slots<> {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000276 public:
277 VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000278 ~VirtualSocket() override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000279
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000280 SocketAddress GetLocalAddress() const override;
281 SocketAddress GetRemoteAddress() const override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000282
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000283 // Used by TurnPortTest to mimic a case where proxy returns local host address
284 // instead of the original one TurnPort was bound against. Please see WebRTC
285 // issue 3927 for more detail.
286 void SetAlternativeLocalAddress(const SocketAddress& addr);
287
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000288 int Bind(const SocketAddress& addr) override;
289 int Connect(const SocketAddress& addr) override;
290 int Close() override;
291 int Send(const void* pv, size_t cb) override;
292 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
Stefan Holmer9131efd2016-05-23 18:19:26 +0200293 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
294 int RecvFrom(void* pv,
295 size_t cb,
296 SocketAddress* paddr,
297 int64_t* timestamp) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000298 int Listen(int backlog) override;
299 VirtualSocket* Accept(SocketAddress* paddr) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000300
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000301 int GetError() const override;
302 void SetError(int error) override;
303 ConnState GetState() const override;
304 int GetOption(Option opt, int* value) override;
305 int SetOption(Option opt, int value) override;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200306 int EstimateMTU(uint16_t* mtu) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000307 void OnMessage(Message* pmsg) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000308
309 bool was_any() { return was_any_; }
310 void set_was_any(bool was_any) { was_any_ = was_any; }
311
312 // For testing purpose only. Fired when client socket is bound to an address.
313 sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
314
315 private:
316 struct NetworkEntry {
317 size_t size;
Honghai Zhang82d78622016-05-06 11:29:15 -0700318 int64_t done_time;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000319 };
320
321 typedef std::deque<SocketAddress> ListenQueue;
322 typedef std::deque<NetworkEntry> NetworkQueue;
323 typedef std::vector<char> SendBuffer;
324 typedef std::list<Packet*> RecvBuffer;
325 typedef std::map<Option, int> OptionsMap;
326
327 int InitiateConnect(const SocketAddress& addr, bool use_delay);
328 void CompleteConnect(const SocketAddress& addr, bool notify);
329 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
330 int SendTcp(const void* pv, size_t cb);
331
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700332 // Used by server sockets to set the local address without binding.
333 void SetLocalAddress(const SocketAddress& addr);
334
Taylor Brandstettere7536412016-09-09 13:16:15 -0700335 void OnSocketServerReadyToSend();
336
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000337 VirtualSocketServer* server_;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000338 int type_;
339 bool async_;
340 ConnState state_;
341 int error_;
342 SocketAddress local_addr_;
343 SocketAddress alternative_local_addr_;
344 SocketAddress remote_addr_;
345
346 // Pending sockets which can be Accepted
347 ListenQueue* listen_queue_;
348
349 // Data which tcp has buffered for sending
350 SendBuffer send_buffer_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700351 // Set to false if the last attempt to send resulted in EWOULDBLOCK.
352 // Set back to true when the socket can send again.
353 bool ready_to_send_ = true;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000354
355 // Critical section to protect the recv_buffer and queue_
356 CriticalSection crit_;
357
358 // Network model that enforces bandwidth and capacity constraints
359 NetworkQueue network_;
360 size_t network_size_;
361
362 // Data which has been received from the network
363 RecvBuffer recv_buffer_;
364 // The amount of data which is in flight or in recv_buffer_
365 size_t recv_buffer_size_;
366
367 // Is this socket bound?
368 bool bound_;
369
370 // When we bind a socket to Any, VSS's Bind gives it another address. For
371 // dual-stack sockets, we want to distinguish between sockets that were
372 // explicitly given a particular address and sockets that had one picked
373 // for them by VSS.
374 bool was_any_;
375
376 // Store the options that are set
377 OptionsMap options_map_;
378
379 friend class VirtualSocketServer;
380};
381
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000382} // namespace rtc
383
384#endif // WEBRTC_BASE_VIRTUALSOCKETSERVER_H_