blob: 8673d40f839f02a16a7471b9f8d46fd4ca7fce8f [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
kwiberg4485ffb2016-04-26 08:14:39 -070019#include "webrtc/base/constructormagic.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#include "webrtc/base/messagequeue.h"
21#include "webrtc/base/socketserver.h"
22
23namespace rtc {
24
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +000025class Packet;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026class VirtualSocket;
27class SocketAddressPair;
28
29// Simulates a network in the same manner as a loopback interface. The
30// interface can create as many addresses as you want. All of the sockets
31// created by this network will be able to communicate with one another, unless
32// they are bound to addresses from incompatible families.
33class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
34 public:
35 // TODO: Add "owned" parameter.
36 // If "owned" is set, the supplied socketserver will be deleted later.
37 explicit VirtualSocketServer(SocketServer* ss);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000038 ~VirtualSocketServer() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039
40 SocketServer* socketserver() { return server_; }
41
Guo-wei Shieh38f88932015-08-13 22:24:02 -070042 // The default route indicates which local address to use when a socket is
43 // bound to the 'any' address, e.g. 0.0.0.0.
44 IPAddress GetDefaultRoute(int family);
45 void SetDefaultRoute(const IPAddress& from_addr);
46
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000047 // Limits the network bandwidth (maximum bytes per second). Zero means that
48 // all sends occur instantly. Defaults to 0.
Peter Boström0c4e06b2015-10-07 12:23:21 +020049 uint32_t bandwidth() const { return bandwidth_; }
50 void set_bandwidth(uint32_t bandwidth) { bandwidth_ = bandwidth; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000051
52 // Limits the amount of data which can be in flight on the network without
53 // packet loss (on a per sender basis). Defaults to 64 KB.
Peter Boström0c4e06b2015-10-07 12:23:21 +020054 uint32_t network_capacity() const { return network_capacity_; }
55 void set_network_capacity(uint32_t capacity) { network_capacity_ = capacity; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000056
57 // The amount of data which can be buffered by tcp on the sender's side
Peter Boström0c4e06b2015-10-07 12:23:21 +020058 uint32_t send_buffer_capacity() const { return send_buffer_capacity_; }
59 void set_send_buffer_capacity(uint32_t capacity) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060 send_buffer_capacity_ = capacity;
61 }
62
63 // The amount of data which can be buffered by tcp on the receiver's side
Peter Boström0c4e06b2015-10-07 12:23:21 +020064 uint32_t recv_buffer_capacity() const { return recv_buffer_capacity_; }
65 void set_recv_buffer_capacity(uint32_t capacity) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066 recv_buffer_capacity_ = capacity;
67 }
68
69 // Controls the (transit) delay for packets sent in the network. This does
70 // not inclue the time required to sit in the send queue. Both of these
71 // values are measured in milliseconds. Defaults to no delay.
Peter Boström0c4e06b2015-10-07 12:23:21 +020072 uint32_t delay_mean() const { return delay_mean_; }
73 uint32_t delay_stddev() const { return delay_stddev_; }
74 uint32_t delay_samples() const { return delay_samples_; }
75 void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
76 void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
77 void set_delay_samples(uint32_t delay_samples) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078 delay_samples_ = delay_samples;
79 }
80
81 // If the (transit) delay parameters are modified, this method should be
82 // called to recompute the new distribution.
83 void UpdateDelayDistribution();
84
85 // Controls the (uniform) probability that any sent packet is dropped. This
86 // is separate from calculations to drop based on queue size.
87 double drop_probability() { return drop_prob_; }
88 void set_drop_probability(double drop_prob) {
89 assert((0 <= drop_prob) && (drop_prob <= 1));
90 drop_prob_ = drop_prob;
91 }
92
93 // SocketFactory:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000094 Socket* CreateSocket(int type) override;
95 Socket* CreateSocket(int family, int type) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000096
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000097 AsyncSocket* CreateAsyncSocket(int type) override;
98 AsyncSocket* CreateAsyncSocket(int family, int type) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000099
100 // SocketServer:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000101 void SetMessageQueue(MessageQueue* queue) override;
102 bool Wait(int cms, bool process_io) override;
103 void WakeUp() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000104
105 typedef std::pair<double, double> Point;
106 typedef std::vector<Point> Function;
107
Peter Boström0c4e06b2015-10-07 12:23:21 +0200108 static Function* CreateDistribution(uint32_t mean,
109 uint32_t stddev,
110 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000111
112 // Similar to Thread::ProcessMessages, but it only processes messages until
113 // there are no immediate messages or pending network traffic. Returns false
114 // if Thread::Stop() was called.
115 bool ProcessMessagesUntilIdle();
116
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000117 // Sets the next port number to use for testing.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200118 void SetNextPortForTesting(uint16_t port);
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000119
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700120 // Close a pair of Tcp connections by addresses. Both connections will have
121 // its own OnClose invoked.
122 bool CloseTcpConnections(const SocketAddress& addr_local,
123 const SocketAddress& addr_remote);
124
tommi5ce1a2a2016-05-14 03:19:31 -0700125 // For testing purpose only. Fired when a client socket is created.
126 sigslot::signal1<VirtualSocket*> SignalSocketCreated;
127
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128 protected:
129 // Returns a new IP not used before in this network.
130 IPAddress GetNextIP(int family);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200131 uint16_t GetNextPort();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132
133 VirtualSocket* CreateSocketInternal(int family, int type);
134
135 // Binds the given socket to addr, assigning and IP and Port if necessary
136 int Bind(VirtualSocket* socket, SocketAddress* addr);
137
138 // Binds the given socket to the given (fully-defined) address.
139 int Bind(VirtualSocket* socket, const SocketAddress& addr);
140
141 // Find the socket bound to the given address
142 VirtualSocket* LookupBinding(const SocketAddress& addr);
143
144 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
145
146 // Adds a mapping between this socket pair and the socket.
147 void AddConnection(const SocketAddress& client,
148 const SocketAddress& server,
149 VirtualSocket* socket);
150
151 // Find the socket pair corresponding to this server address.
152 VirtualSocket* LookupConnection(const SocketAddress& client,
153 const SocketAddress& server);
154
155 void RemoveConnection(const SocketAddress& client,
156 const SocketAddress& server);
157
158 // Connects the given socket to the socket at the given address
159 int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
160 bool use_delay);
161
162 // Sends a disconnect message to the socket at the given address
163 bool Disconnect(VirtualSocket* socket);
164
165 // Sends the given packet to the socket at the given address (if one exists).
166 int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
167 const SocketAddress& remote_addr);
168
169 // Moves as much data as possible from the sender's buffer to the network
170 void SendTcp(VirtualSocket* socket);
171
172 // Places a packet on the network.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200173 void AddPacketToNetwork(VirtualSocket* socket,
174 VirtualSocket* recipient,
Honghai Zhang82d78622016-05-06 11:29:15 -0700175 int64_t cur_time,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200176 const char* data,
177 size_t data_size,
178 size_t header_size,
179 bool ordered);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180
181 // Removes stale packets from the network
Honghai Zhang82d78622016-05-06 11:29:15 -0700182 void PurgeNetworkPackets(VirtualSocket* socket, int64_t cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183
184 // Computes the number of milliseconds required to send a packet of this size.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200185 uint32_t SendDelay(uint32_t size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000186
187 // Returns a random transit delay chosen from the appropriate distribution.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200188 uint32_t GetRandomTransitDelay();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000189
190 // Basic operations on functions. Those that return a function also take
191 // ownership of the function given (and hence, may modify or delete it).
192 static Function* Accumulate(Function* f);
193 static Function* Invert(Function* f);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200194 static Function* Resample(Function* f,
195 double x1,
196 double x2,
197 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 static double Evaluate(Function* f, double x);
199
200 // NULL out our message queue if it goes away. Necessary in the case where
201 // our lifetime is greater than that of the thread we are using, since we
202 // try to send Close messages for all connected sockets when we shutdown.
203 void OnMessageQueueDestroyed() { msg_queue_ = NULL; }
204
205 // Determine if two sockets should be able to communicate.
206 // We don't (currently) specify an address family for sockets; instead,
207 // the currently bound address is used to infer the address family.
208 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
209 // dual-stack capable.
210 // This function tests if two addresses can communicate, as well as the
211 // sockets to which they may be bound (the addresses may or may not yet be
212 // bound to the sockets).
213 // First the addresses are tested (after normalization):
214 // If both have the same family, then communication is OK.
215 // If only one is IPv4 then false, unless the other is bound to ::.
216 // This applies even if the IPv4 address is 0.0.0.0.
217 // The socket arguments are optional; the sockets are checked to see if they
218 // were explicitly bound to IPv6-any ('::'), and if so communication is
219 // permitted.
220 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
221 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
222
223 private:
224 friend class VirtualSocket;
225
226 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
227 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
228
229 SocketServer* server_;
230 bool server_owned_;
231 MessageQueue* msg_queue_;
232 bool stop_on_idle_;
Honghai Zhang82d78622016-05-06 11:29:15 -0700233 int64_t network_delay_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234 in_addr next_ipv4_;
235 in6_addr next_ipv6_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200236 uint16_t next_port_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000237 AddressMap* bindings_;
238 ConnectionMap* connections_;
239
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700240 IPAddress default_route_v4_;
241 IPAddress default_route_v6_;
242
Peter Boström0c4e06b2015-10-07 12:23:21 +0200243 uint32_t bandwidth_;
244 uint32_t network_capacity_;
245 uint32_t send_buffer_capacity_;
246 uint32_t recv_buffer_capacity_;
247 uint32_t delay_mean_;
248 uint32_t delay_stddev_;
249 uint32_t delay_samples_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 Function* delay_dist_;
251 CriticalSection delay_crit_;
252
253 double drop_prob_;
henrikg3c089d72015-09-16 05:37:44 -0700254 RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255};
256
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000257// Implements the socket interface using the virtual network. Packets are
258// passed as messages using the message queue of the socket server.
259class VirtualSocket : public AsyncSocket, public MessageHandler {
260 public:
261 VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000262 ~VirtualSocket() override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000263
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000264 SocketAddress GetLocalAddress() const override;
265 SocketAddress GetRemoteAddress() const override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000266
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000267 // Used by TurnPortTest to mimic a case where proxy returns local host address
268 // instead of the original one TurnPort was bound against. Please see WebRTC
269 // issue 3927 for more detail.
270 void SetAlternativeLocalAddress(const SocketAddress& addr);
271
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000272 int Bind(const SocketAddress& addr) override;
273 int Connect(const SocketAddress& addr) override;
274 int Close() override;
275 int Send(const void* pv, size_t cb) override;
276 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
Stefan Holmer9131efd2016-05-23 18:19:26 +0200277 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
278 int RecvFrom(void* pv,
279 size_t cb,
280 SocketAddress* paddr,
281 int64_t* timestamp) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000282 int Listen(int backlog) override;
283 VirtualSocket* Accept(SocketAddress* paddr) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000284
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000285 int GetError() const override;
286 void SetError(int error) override;
287 ConnState GetState() const override;
288 int GetOption(Option opt, int* value) override;
289 int SetOption(Option opt, int value) override;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200290 int EstimateMTU(uint16_t* mtu) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000291 void OnMessage(Message* pmsg) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000292
293 bool was_any() { return was_any_; }
294 void set_was_any(bool was_any) { was_any_ = was_any; }
295
296 // For testing purpose only. Fired when client socket is bound to an address.
297 sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
298
299 private:
300 struct NetworkEntry {
301 size_t size;
Honghai Zhang82d78622016-05-06 11:29:15 -0700302 int64_t done_time;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000303 };
304
305 typedef std::deque<SocketAddress> ListenQueue;
306 typedef std::deque<NetworkEntry> NetworkQueue;
307 typedef std::vector<char> SendBuffer;
308 typedef std::list<Packet*> RecvBuffer;
309 typedef std::map<Option, int> OptionsMap;
310
311 int InitiateConnect(const SocketAddress& addr, bool use_delay);
312 void CompleteConnect(const SocketAddress& addr, bool notify);
313 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
314 int SendTcp(const void* pv, size_t cb);
315
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700316 // Used by server sockets to set the local address without binding.
317 void SetLocalAddress(const SocketAddress& addr);
318
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000319 VirtualSocketServer* server_;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000320 int type_;
321 bool async_;
322 ConnState state_;
323 int error_;
324 SocketAddress local_addr_;
325 SocketAddress alternative_local_addr_;
326 SocketAddress remote_addr_;
327
328 // Pending sockets which can be Accepted
329 ListenQueue* listen_queue_;
330
331 // Data which tcp has buffered for sending
332 SendBuffer send_buffer_;
333 bool write_enabled_;
334
335 // Critical section to protect the recv_buffer and queue_
336 CriticalSection crit_;
337
338 // Network model that enforces bandwidth and capacity constraints
339 NetworkQueue network_;
340 size_t network_size_;
341
342 // Data which has been received from the network
343 RecvBuffer recv_buffer_;
344 // The amount of data which is in flight or in recv_buffer_
345 size_t recv_buffer_size_;
346
347 // Is this socket bound?
348 bool bound_;
349
350 // When we bind a socket to Any, VSS's Bind gives it another address. For
351 // dual-stack sockets, we want to distinguish between sockets that were
352 // explicitly given a particular address and sockets that had one picked
353 // for them by VSS.
354 bool was_any_;
355
356 // Store the options that are set
357 OptionsMap options_map_;
358
359 friend class VirtualSocketServer;
360};
361
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000362} // namespace rtc
363
364#endif // WEBRTC_BASE_VIRTUALSOCKETSERVER_H_