blob: a750ab95d3f1c24186a3b63355c98c226239eb19 [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
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700115 void SetDelayOnAddress(const rtc::SocketAddress& address, int delay_ms) {
116 delay_by_ip_[address.ipaddr()] = delay_ms;
117 }
118
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119 typedef std::pair<double, double> Point;
120 typedef std::vector<Point> Function;
121
Peter Boström0c4e06b2015-10-07 12:23:21 +0200122 static Function* CreateDistribution(uint32_t mean,
123 uint32_t stddev,
124 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125
126 // Similar to Thread::ProcessMessages, but it only processes messages until
127 // there are no immediate messages or pending network traffic. Returns false
128 // if Thread::Stop() was called.
129 bool ProcessMessagesUntilIdle();
130
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000131 // Sets the next port number to use for testing.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200132 void SetNextPortForTesting(uint16_t port);
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000133
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700134 // Close a pair of Tcp connections by addresses. Both connections will have
135 // its own OnClose invoked.
136 bool CloseTcpConnections(const SocketAddress& addr_local,
137 const SocketAddress& addr_remote);
138
tommi5ce1a2a2016-05-14 03:19:31 -0700139 // For testing purpose only. Fired when a client socket is created.
140 sigslot::signal1<VirtualSocket*> SignalSocketCreated;
141
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 protected:
143 // Returns a new IP not used before in this network.
144 IPAddress GetNextIP(int family);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200145 uint16_t GetNextPort();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146
147 VirtualSocket* CreateSocketInternal(int family, int type);
148
149 // Binds the given socket to addr, assigning and IP and Port if necessary
150 int Bind(VirtualSocket* socket, SocketAddress* addr);
151
152 // Binds the given socket to the given (fully-defined) address.
153 int Bind(VirtualSocket* socket, const SocketAddress& addr);
154
155 // Find the socket bound to the given address
156 VirtualSocket* LookupBinding(const SocketAddress& addr);
157
158 int Unbind(const SocketAddress& addr, VirtualSocket* socket);
159
160 // Adds a mapping between this socket pair and the socket.
161 void AddConnection(const SocketAddress& client,
162 const SocketAddress& server,
163 VirtualSocket* socket);
164
165 // Find the socket pair corresponding to this server address.
166 VirtualSocket* LookupConnection(const SocketAddress& client,
167 const SocketAddress& server);
168
169 void RemoveConnection(const SocketAddress& client,
170 const SocketAddress& server);
171
172 // Connects the given socket to the socket at the given address
173 int Connect(VirtualSocket* socket, const SocketAddress& remote_addr,
174 bool use_delay);
175
176 // Sends a disconnect message to the socket at the given address
177 bool Disconnect(VirtualSocket* socket);
178
179 // Sends the given packet to the socket at the given address (if one exists).
180 int SendUdp(VirtualSocket* socket, const char* data, size_t data_size,
181 const SocketAddress& remote_addr);
182
183 // Moves as much data as possible from the sender's buffer to the network
184 void SendTcp(VirtualSocket* socket);
185
186 // Places a packet on the network.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200187 void AddPacketToNetwork(VirtualSocket* socket,
188 VirtualSocket* recipient,
Honghai Zhang82d78622016-05-06 11:29:15 -0700189 int64_t cur_time,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200190 const char* data,
191 size_t data_size,
192 size_t header_size,
193 bool ordered);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000194
195 // Removes stale packets from the network
Honghai Zhang82d78622016-05-06 11:29:15 -0700196 void PurgeNetworkPackets(VirtualSocket* socket, int64_t cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000197
198 // Computes the number of milliseconds required to send a packet of this size.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200199 uint32_t SendDelay(uint32_t size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000200
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700201 // If the delay has been set for the address of the socket, returns the set
202 // delay. Otherwise, returns a random transit delay chosen from the
203 // appropriate distribution.
204 uint32_t GetTransitDelay(Socket* socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205
206 // Basic operations on functions. Those that return a function also take
207 // ownership of the function given (and hence, may modify or delete it).
208 static Function* Accumulate(Function* f);
209 static Function* Invert(Function* f);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200210 static Function* Resample(Function* f,
211 double x1,
212 double x2,
213 uint32_t samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214 static double Evaluate(Function* f, double x);
215
deadbeef37f5ecf2017-02-27 14:06:41 -0800216 // Null out our message queue if it goes away. Necessary in the case where
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000217 // our lifetime is greater than that of the thread we are using, since we
218 // try to send Close messages for all connected sockets when we shutdown.
deadbeef37f5ecf2017-02-27 14:06:41 -0800219 void OnMessageQueueDestroyed() { msg_queue_ = nullptr; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
221 // Determine if two sockets should be able to communicate.
222 // We don't (currently) specify an address family for sockets; instead,
223 // the currently bound address is used to infer the address family.
224 // Any socket that is not explicitly bound to an IPv4 address is assumed to be
225 // dual-stack capable.
226 // This function tests if two addresses can communicate, as well as the
227 // sockets to which they may be bound (the addresses may or may not yet be
228 // bound to the sockets).
229 // First the addresses are tested (after normalization):
230 // If both have the same family, then communication is OK.
231 // If only one is IPv4 then false, unless the other is bound to ::.
232 // This applies even if the IPv4 address is 0.0.0.0.
233 // The socket arguments are optional; the sockets are checked to see if they
234 // were explicitly bound to IPv6-any ('::'), and if so communication is
235 // permitted.
236 // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
237 static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
238
239 private:
240 friend class VirtualSocket;
241
Taylor Brandstettere7536412016-09-09 13:16:15 -0700242 // Sending was previously blocked, but now isn't.
243 sigslot::signal0<> SignalReadyToSend;
244
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000245 typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
246 typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
247
248 SocketServer* server_;
249 bool server_owned_;
250 MessageQueue* msg_queue_;
251 bool stop_on_idle_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000252 in_addr next_ipv4_;
253 in6_addr next_ipv6_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200254 uint16_t next_port_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 AddressMap* bindings_;
256 ConnectionMap* connections_;
257
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700258 IPAddress default_route_v4_;
259 IPAddress default_route_v6_;
260
Peter Boström0c4e06b2015-10-07 12:23:21 +0200261 uint32_t bandwidth_;
262 uint32_t network_capacity_;
263 uint32_t send_buffer_capacity_;
264 uint32_t recv_buffer_capacity_;
265 uint32_t delay_mean_;
266 uint32_t delay_stddev_;
267 uint32_t delay_samples_;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700268
269 std::map<rtc::IPAddress, int> delay_by_ip_;
270 std::unique_ptr<Function> delay_dist_;
271
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272 CriticalSection delay_crit_;
273
274 double drop_prob_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700275 bool sending_blocked_ = false;
henrikg3c089d72015-09-16 05:37:44 -0700276 RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277};
278
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000279// Implements the socket interface using the virtual network. Packets are
280// passed as messages using the message queue of the socket server.
Taylor Brandstettere7536412016-09-09 13:16:15 -0700281class VirtualSocket : public AsyncSocket,
282 public MessageHandler,
283 public sigslot::has_slots<> {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000284 public:
285 VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000286 ~VirtualSocket() override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000287
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000288 SocketAddress GetLocalAddress() const override;
289 SocketAddress GetRemoteAddress() const override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000290
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000291 // Used by TurnPortTest to mimic a case where proxy returns local host address
292 // instead of the original one TurnPort was bound against. Please see WebRTC
293 // issue 3927 for more detail.
294 void SetAlternativeLocalAddress(const SocketAddress& addr);
295
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000296 int Bind(const SocketAddress& addr) override;
297 int Connect(const SocketAddress& addr) override;
298 int Close() override;
299 int Send(const void* pv, size_t cb) override;
300 int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
Stefan Holmer9131efd2016-05-23 18:19:26 +0200301 int Recv(void* pv, size_t cb, int64_t* timestamp) override;
302 int RecvFrom(void* pv,
303 size_t cb,
304 SocketAddress* paddr,
305 int64_t* timestamp) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000306 int Listen(int backlog) override;
307 VirtualSocket* Accept(SocketAddress* paddr) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000308
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000309 int GetError() const override;
310 void SetError(int error) override;
311 ConnState GetState() const override;
312 int GetOption(Option opt, int* value) override;
313 int SetOption(Option opt, int value) override;
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000314 void OnMessage(Message* pmsg) override;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000315
316 bool was_any() { return was_any_; }
317 void set_was_any(bool was_any) { was_any_ = was_any; }
318
319 // For testing purpose only. Fired when client socket is bound to an address.
320 sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
321
322 private:
323 struct NetworkEntry {
324 size_t size;
Honghai Zhang82d78622016-05-06 11:29:15 -0700325 int64_t done_time;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000326 };
327
328 typedef std::deque<SocketAddress> ListenQueue;
329 typedef std::deque<NetworkEntry> NetworkQueue;
330 typedef std::vector<char> SendBuffer;
331 typedef std::list<Packet*> RecvBuffer;
332 typedef std::map<Option, int> OptionsMap;
333
334 int InitiateConnect(const SocketAddress& addr, bool use_delay);
335 void CompleteConnect(const SocketAddress& addr, bool notify);
336 int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
337 int SendTcp(const void* pv, size_t cb);
338
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700339 // Used by server sockets to set the local address without binding.
340 void SetLocalAddress(const SocketAddress& addr);
341
Taylor Brandstettere7536412016-09-09 13:16:15 -0700342 void OnSocketServerReadyToSend();
343
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000344 VirtualSocketServer* server_;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000345 int type_;
346 bool async_;
347 ConnState state_;
348 int error_;
349 SocketAddress local_addr_;
350 SocketAddress alternative_local_addr_;
351 SocketAddress remote_addr_;
352
353 // Pending sockets which can be Accepted
354 ListenQueue* listen_queue_;
355
356 // Data which tcp has buffered for sending
357 SendBuffer send_buffer_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700358 // Set to false if the last attempt to send resulted in EWOULDBLOCK.
359 // Set back to true when the socket can send again.
360 bool ready_to_send_ = true;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000361
362 // Critical section to protect the recv_buffer and queue_
363 CriticalSection crit_;
364
365 // Network model that enforces bandwidth and capacity constraints
366 NetworkQueue network_;
367 size_t network_size_;
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700368 // The scheduled delivery time of the last packet sent on this socket.
369 // It is used to ensure ordered delivery of packets sent on this socket.
370 int64_t last_delivery_time_ = 0;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000371
372 // Data which has been received from the network
373 RecvBuffer recv_buffer_;
374 // The amount of data which is in flight or in recv_buffer_
375 size_t recv_buffer_size_;
376
377 // Is this socket bound?
378 bool bound_;
379
380 // When we bind a socket to Any, VSS's Bind gives it another address. For
381 // dual-stack sockets, we want to distinguish between sockets that were
382 // explicitly given a particular address and sockets that had one picked
383 // for them by VSS.
384 bool was_any_;
385
386 // Store the options that are set
387 OptionsMap options_map_;
388
389 friend class VirtualSocketServer;
390};
391
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000392} // namespace rtc
393
394#endif // WEBRTC_BASE_VIRTUALSOCKETSERVER_H_