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