blob: cecce924cb368c765c89f563d5905695d2cc8177 [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
14#include <assert.h>
15
16#include <deque>
17#include <map>
18
19#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);
37 virtual ~VirtualSocketServer();
38
39 SocketServer* socketserver() { return server_; }
40
41 // Limits the network bandwidth (maximum bytes per second). Zero means that
42 // all sends occur instantly. Defaults to 0.
43 uint32 bandwidth() const { return bandwidth_; }
44 void set_bandwidth(uint32 bandwidth) { bandwidth_ = bandwidth; }
45
46 // Limits the amount of data which can be in flight on the network without
47 // packet loss (on a per sender basis). Defaults to 64 KB.
48 uint32 network_capacity() const { return network_capacity_; }
49 void set_network_capacity(uint32 capacity) {
50 network_capacity_ = capacity;
51 }
52
53 // The amount of data which can be buffered by tcp on the sender's side
54 uint32 send_buffer_capacity() const { return send_buffer_capacity_; }
55 void set_send_buffer_capacity(uint32 capacity) {
56 send_buffer_capacity_ = capacity;
57 }
58
59 // The amount of data which can be buffered by tcp on the receiver's side
60 uint32 recv_buffer_capacity() const { return recv_buffer_capacity_; }
61 void set_recv_buffer_capacity(uint32 capacity) {
62 recv_buffer_capacity_ = capacity;
63 }
64
65 // Controls the (transit) delay for packets sent in the network. This does
66 // not inclue the time required to sit in the send queue. Both of these
67 // values are measured in milliseconds. Defaults to no delay.
68 uint32 delay_mean() const { return delay_mean_; }
69 uint32 delay_stddev() const { return delay_stddev_; }
70 uint32 delay_samples() const { return delay_samples_; }
71 void set_delay_mean(uint32 delay_mean) { delay_mean_ = delay_mean; }
72 void set_delay_stddev(uint32 delay_stddev) {
73 delay_stddev_ = delay_stddev;
74 }
75 void set_delay_samples(uint32 delay_samples) {
76 delay_samples_ = delay_samples;
77 }
78
79 // If the (transit) delay parameters are modified, this method should be
80 // called to recompute the new distribution.
81 void UpdateDelayDistribution();
82
83 // Controls the (uniform) probability that any sent packet is dropped. This
84 // is separate from calculations to drop based on queue size.
85 double drop_probability() { return drop_prob_; }
86 void set_drop_probability(double drop_prob) {
87 assert((0 <= drop_prob) && (drop_prob <= 1));
88 drop_prob_ = drop_prob;
89 }
90
91 // SocketFactory:
92 virtual Socket* CreateSocket(int type);
93 virtual Socket* CreateSocket(int family, int type);
94
95 virtual AsyncSocket* CreateAsyncSocket(int type);
96 virtual AsyncSocket* CreateAsyncSocket(int family, int type);
97
98 // SocketServer:
99 virtual void SetMessageQueue(MessageQueue* queue);
100 virtual bool Wait(int cms, bool process_io);
101 virtual void WakeUp();
102
103 typedef std::pair<double, double> Point;
104 typedef std::vector<Point> Function;
105
106 static Function* CreateDistribution(uint32 mean, uint32 stddev,
107 uint32 samples);
108
109 // Similar to Thread::ProcessMessages, but it only processes messages until
110 // there are no immediate messages or pending network traffic. Returns false
111 // if Thread::Stop() was called.
112 bool ProcessMessagesUntilIdle();
113
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000114 // Sets the next port number to use for testing.
115 void SetNextPortForTesting(uint16 port);
116
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117 protected:
118 // Returns a new IP not used before in this network.
119 IPAddress GetNextIP(int family);
120 uint16 GetNextPort();
121
122 VirtualSocket* CreateSocketInternal(int family, int type);
123
124 // Binds the given socket to addr, assigning and IP and Port if necessary
125 int Bind(VirtualSocket* socket, SocketAddress* addr);
126
127 // Binds the given socket to the given (fully-defined) address.
128 int Bind(VirtualSocket* socket, const SocketAddress& addr);
129
130 // Find the socket bound to the given address
131 VirtualSocket* LookupBinding(const SocketAddress& addr);
132
133 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
134
135 // Adds a mapping between this socket pair and the socket.
136 void AddConnection(const SocketAddress& client,
137 const SocketAddress& server,
138 VirtualSocket* socket);
139
140 // Find the socket pair corresponding to this server address.
141 VirtualSocket* LookupConnection(const SocketAddress& client,
142 const SocketAddress& server);
143
144 void RemoveConnection(const SocketAddress& client,
145 const SocketAddress& server);
146
147 // Connects the given socket to the socket at the given address
148 int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
149 bool use_delay);
150
151 // Sends a disconnect message to the socket at the given address
152 bool Disconnect(VirtualSocket* socket);
153
154 // Sends the given packet to the socket at the given address (if one exists).
155 int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
156 const SocketAddress& remote_addr);
157
158 // Moves as much data as possible from the sender's buffer to the network
159 void SendTcp(VirtualSocket* socket);
160
161 // Places a packet on the network.
162 void AddPacketToNetwork(VirtualSocket* socket, VirtualSocket* recipient,
163 uint32 cur_time, const char* data, size_t data_size,
164 size_t header_size, bool ordered);
165
166 // Removes stale packets from the network
167 void PurgeNetworkPackets(VirtualSocket* socket, uint32 cur_time);
168
169 // Computes the number of milliseconds required to send a packet of this size.
170 uint32 SendDelay(uint32 size);
171
172 // Returns a random transit delay chosen from the appropriate distribution.
173 uint32 GetRandomTransitDelay();
174
175 // Basic operations on functions. Those that return a function also take
176 // ownership of the function given (and hence, may modify or delete it).
177 static Function* Accumulate(Function* f);
178 static Function* Invert(Function* f);
179 static Function* Resample(Function* f, double x1, double x2, uint32 samples);
180 static double Evaluate(Function* f, double x);
181
182 // NULL out our message queue if it goes away. Necessary in the case where
183 // our lifetime is greater than that of the thread we are using, since we
184 // try to send Close messages for all connected sockets when we shutdown.
185 void OnMessageQueueDestroyed() { msg_queue_ = NULL; }
186
187 // Determine if two sockets should be able to communicate.
188 // We don't (currently) specify an address family for sockets; instead,
189 // the currently bound address is used to infer the address family.
190 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
191 // dual-stack capable.
192 // This function tests if two addresses can communicate, as well as the
193 // sockets to which they may be bound (the addresses may or may not yet be
194 // bound to the sockets).
195 // First the addresses are tested (after normalization):
196 // If both have the same family, then communication is OK.
197 // If only one is IPv4 then false, unless the other is bound to ::.
198 // This applies even if the IPv4 address is 0.0.0.0.
199 // The socket arguments are optional; the sockets are checked to see if they
200 // were explicitly bound to IPv6-any ('::'), and if so communication is
201 // permitted.
202 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
203 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
204
205 private:
206 friend class VirtualSocket;
207
208 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
209 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
210
211 SocketServer* server_;
212 bool server_owned_;
213 MessageQueue* msg_queue_;
214 bool stop_on_idle_;
215 uint32 network_delay_;
216 in_addr next_ipv4_;
217 in6_addr next_ipv6_;
218 uint16 next_port_;
219 AddressMap* bindings_;
220 ConnectionMap* connections_;
221
222 uint32 bandwidth_;
223 uint32 network_capacity_;
224 uint32 send_buffer_capacity_;
225 uint32 recv_buffer_capacity_;
226 uint32 delay_mean_;
227 uint32 delay_stddev_;
228 uint32 delay_samples_;
229 Function* delay_dist_;
230 CriticalSection delay_crit_;
231
232 double drop_prob_;
233 DISALLOW_EVIL_CONSTRUCTORS(VirtualSocketServer);
234};
235
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000236// Implements the socket interface using the virtual network. Packets are
237// passed as messages using the message queue of the socket server.
238class VirtualSocket : public AsyncSocket, public MessageHandler {
239 public:
240 VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
241 virtual ~VirtualSocket();
242
243 virtual SocketAddress GetLocalAddress() const;
244 virtual SocketAddress GetRemoteAddress() const;
245
246 // Used by server sockets to set the local address without binding.
247 void SetLocalAddress(const SocketAddress& addr);
248
249 virtual int Bind(const SocketAddress& addr);
250 virtual int Connect(const SocketAddress& addr);
251 virtual int Close();
252 virtual int Send(const void* pv, size_t cb);
253 virtual int SendTo(const void* pv, size_t cb, const SocketAddress& addr);
254 virtual int Recv(void* pv, size_t cb);
255 virtual int RecvFrom(void* pv, size_t cb, SocketAddress* paddr);
256 virtual int Listen(int backlog);
257 virtual VirtualSocket* Accept(SocketAddress* paddr);
258
259 virtual int GetError() const;
260 virtual void SetError(int error);
261 virtual ConnState GetState() const;
262 virtual int GetOption(Option opt, int* value);
263 virtual int SetOption(Option opt, int value);
264 virtual int EstimateMTU(uint16* mtu);
265 void OnMessage(Message* pmsg);
266
267 bool was_any() { return was_any_; }
268 void set_was_any(bool was_any) { was_any_ = was_any; }
269
270 // For testing purpose only. Fired when client socket is bound to an address.
271 sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
272
273 private:
274 struct NetworkEntry {
275 size_t size;
276 uint32 done_time;
277 };
278
279 typedef std::deque<SocketAddress> ListenQueue;
280 typedef std::deque<NetworkEntry> NetworkQueue;
281 typedef std::vector<char> SendBuffer;
282 typedef std::list<Packet*> RecvBuffer;
283 typedef std::map<Option, int> OptionsMap;
284
285 int InitiateConnect(const SocketAddress& addr, bool use_delay);
286 void CompleteConnect(const SocketAddress& addr, bool notify);
287 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
288 int SendTcp(const void* pv, size_t cb);
289
290 VirtualSocketServer* server_;
291 int family_;
292 int type_;
293 bool async_;
294 ConnState state_;
295 int error_;
296 SocketAddress local_addr_;
297 SocketAddress alternative_local_addr_;
298 SocketAddress remote_addr_;
299
300 // Pending sockets which can be Accepted
301 ListenQueue* listen_queue_;
302
303 // Data which tcp has buffered for sending
304 SendBuffer send_buffer_;
305 bool write_enabled_;
306
307 // Critical section to protect the recv_buffer and queue_
308 CriticalSection crit_;
309
310 // Network model that enforces bandwidth and capacity constraints
311 NetworkQueue network_;
312 size_t network_size_;
313
314 // Data which has been received from the network
315 RecvBuffer recv_buffer_;
316 // The amount of data which is in flight or in recv_buffer_
317 size_t recv_buffer_size_;
318
319 // Is this socket bound?
320 bool bound_;
321
322 // When we bind a socket to Any, VSS's Bind gives it another address. For
323 // dual-stack sockets, we want to distinguish between sockets that were
324 // explicitly given a particular address and sockets that had one picked
325 // for them by VSS.
326 bool was_any_;
327
328 // Store the options that are set
329 OptionsMap options_map_;
330
331 friend class VirtualSocketServer;
332};
333
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334} // namespace rtc
335
336#endif // WEBRTC_BASE_VIRTUALSOCKETSERVER_H_