blob: d42873e18bd7405a923b8f0bfab30ed32ca693a2 [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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "rtc_base/virtual_socket_server.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
13#include <errno.h>
14#include <math.h>
15
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016#include <map>
jbauch555604a2016-04-26 03:13:22 -070017#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018#include <vector>
19
Steve Anton2acd1632019-03-25 13:48:30 -070020#include "absl/algorithm/container.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080022#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/physical_socket_server.h"
25#include "rtc_base/socket_address_pair.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/thread.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028
29namespace rtc {
30#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +020031const in_addr kInitialNextIPv4 = {{{0x01, 0, 0, 0}}};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032#else
33// This value is entirely arbitrary, hence the lack of concern about endianness.
Yves Gerey665174f2018-06-19 15:03:05 +020034const in_addr kInitialNextIPv4 = {0x01000000};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035#endif
36// Starts at ::2 so as to not cause confusion with ::1.
Yves Gerey665174f2018-06-19 15:03:05 +020037const in6_addr kInitialNextIPv6 = {
38 {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}}};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000039
Peter Boström0c4e06b2015-10-07 12:23:21 +020040const uint16_t kFirstEphemeralPort = 49152;
41const uint16_t kLastEphemeralPort = 65535;
42const uint16_t kEphemeralPortCount =
43 kLastEphemeralPort - kFirstEphemeralPort + 1;
44const uint32_t kDefaultNetworkCapacity = 64 * 1024;
45const uint32_t kDefaultTcpBufferSize = 32 * 1024;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046
Peter Boström0c4e06b2015-10-07 12:23:21 +020047const uint32_t UDP_HEADER_SIZE = 28; // IP + UDP headers
48const uint32_t TCP_HEADER_SIZE = 40; // IP + TCP headers
49const uint32_t TCP_MSS = 1400; // Maximum segment size
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050
51// Note: The current algorithm doesn't work for sample sizes smaller than this.
52const int NUM_SAMPLES = 1000;
53
54enum {
55 MSG_ID_PACKET,
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +000056 MSG_ID_ADDRESS_BOUND,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057 MSG_ID_CONNECT,
58 MSG_ID_DISCONNECT,
deadbeefed3b9862017-06-02 10:33:16 -070059 MSG_ID_SIGNALREADEVENT,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000060};
61
62// Packets are passed between sockets as messages. We copy the data just like
63// the kernel does.
64class Packet : public MessageData {
65 public:
66 Packet(const char* data, size_t size, const SocketAddress& from)
Yves Gerey665174f2018-06-19 15:03:05 +020067 : size_(size), consumed_(0), from_(from) {
deadbeef37f5ecf2017-02-27 14:06:41 -080068 RTC_DCHECK(nullptr != data);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069 data_ = new char[size_];
70 memcpy(data_, data, size_);
71 }
72
Yves Gerey665174f2018-06-19 15:03:05 +020073 ~Packet() override { delete[] data_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074
75 const char* data() const { return data_ + consumed_; }
76 size_t size() const { return size_ - consumed_; }
77 const SocketAddress& from() const { return from_; }
78
79 // Remove the first size bytes from the data.
80 void Consume(size_t size) {
Taylor Brandstettere7536412016-09-09 13:16:15 -070081 RTC_DCHECK(size + consumed_ < size_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000082 consumed_ += size;
83 }
84
85 private:
86 char* data_;
87 size_t size_, consumed_;
88 SocketAddress from_;
89};
90
91struct MessageAddress : public MessageData {
Yves Gerey665174f2018-06-19 15:03:05 +020092 explicit MessageAddress(const SocketAddress& a) : addr(a) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093 SocketAddress addr;
94};
95
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +000096VirtualSocket::VirtualSocket(VirtualSocketServer* server,
97 int family,
98 int type,
99 bool async)
100 : server_(server),
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000101 type_(type),
102 async_(async),
103 state_(CS_CLOSED),
104 error_(0),
deadbeef37f5ecf2017-02-27 14:06:41 -0800105 listen_queue_(nullptr),
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000106 network_size_(0),
107 recv_buffer_size_(0),
108 bound_(false),
109 was_any_(false) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700110 RTC_DCHECK((type_ == SOCK_DGRAM) || (type_ == SOCK_STREAM));
111 RTC_DCHECK(async_ ||
112 (type_ != SOCK_STREAM)); // We only support async streams
113 server->SignalReadyToSend.connect(this,
114 &VirtualSocket::OnSocketServerReadyToSend);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000115}
116
117VirtualSocket::~VirtualSocket() {
118 Close();
119
120 for (RecvBuffer::iterator it = recv_buffer_.begin(); it != recv_buffer_.end();
121 ++it) {
122 delete *it;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000123 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000124}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000126SocketAddress VirtualSocket::GetLocalAddress() const {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000127 return local_addr_;
128}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000130SocketAddress VirtualSocket::GetRemoteAddress() const {
131 return remote_addr_;
132}
133
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000134void VirtualSocket::SetLocalAddress(const SocketAddress& addr) {
135 local_addr_ = addr;
136}
137
138int VirtualSocket::Bind(const SocketAddress& addr) {
139 if (!local_addr_.IsNil()) {
140 error_ = EINVAL;
141 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000143 local_addr_ = addr;
144 int result = server_->Bind(this, &local_addr_);
145 if (result != 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146 local_addr_.Clear();
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000147 error_ = EADDRINUSE;
148 } else {
149 bound_ = true;
150 was_any_ = addr.IsAnyIP();
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000151 // Post a message here such that test case could have chance to
152 // process the local address. (i.e. SetAlternativeLocalAddress).
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700153 server_->msg_queue_->Post(RTC_FROM_HERE, this, MSG_ID_ADDRESS_BOUND);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000154 }
155 return result;
156}
157
158int VirtualSocket::Connect(const SocketAddress& addr) {
159 return InitiateConnect(addr, true);
160}
161
162int VirtualSocket::Close() {
163 if (!local_addr_.IsNil() && bound_) {
164 // Remove from the binding table.
165 server_->Unbind(local_addr_, this);
166 bound_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 }
168
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000169 if (SOCK_STREAM == type_) {
170 // Cancel pending sockets
171 if (listen_queue_) {
172 while (!listen_queue_->empty()) {
173 SocketAddress addr = listen_queue_->front();
174
175 // Disconnect listening socket.
176 server_->Disconnect(server_->LookupBinding(addr));
177 listen_queue_->pop_front();
178 }
179 delete listen_queue_;
deadbeef37f5ecf2017-02-27 14:06:41 -0800180 listen_queue_ = nullptr;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000181 }
182 // Disconnect stream sockets
183 if (CS_CONNECTED == state_) {
184 // Disconnect remote socket, check if it is a child of a server socket.
185 VirtualSocket* socket =
186 server_->LookupConnection(local_addr_, remote_addr_);
187 if (!socket) {
188 // Not a server socket child, then see if it is bound.
189 // TODO(tbd): If this is indeed a server socket that has no
190 // children this will cause the server socket to be
191 // closed. This might lead to unexpected results, how to fix this?
192 socket = server_->LookupBinding(remote_addr_);
193 }
194 server_->Disconnect(socket);
195
196 // Remove mapping for both directions.
197 server_->RemoveConnection(remote_addr_, local_addr_);
198 server_->RemoveConnection(local_addr_, remote_addr_);
199 }
200 // Cancel potential connects
201 MessageList msgs;
202 if (server_->msg_queue_) {
203 server_->msg_queue_->Clear(this, MSG_ID_CONNECT, &msgs);
204 }
205 for (MessageList::iterator it = msgs.begin(); it != msgs.end(); ++it) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800206 RTC_DCHECK(nullptr != it->pdata);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000207 MessageAddress* data = static_cast<MessageAddress*>(it->pdata);
208
209 // Lookup remote side.
210 VirtualSocket* socket =
211 server_->LookupConnection(local_addr_, data->addr);
212 if (socket) {
213 // Server socket, remote side is a socket retreived by
214 // accept. Accepted sockets are not bound so we will not
215 // find it by looking in the bindings table.
216 server_->Disconnect(socket);
217 server_->RemoveConnection(local_addr_, data->addr);
218 } else {
219 server_->Disconnect(server_->LookupBinding(data->addr));
220 }
221 delete data;
222 }
223 // Clear incoming packets and disconnect messages
224 if (server_->msg_queue_) {
225 server_->msg_queue_->Clear(this);
226 }
227 }
228
229 state_ = CS_CLOSED;
230 local_addr_.Clear();
231 remote_addr_.Clear();
232 return 0;
233}
234
235int VirtualSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200236 if (CS_CONNECTED != state_) {
237 error_ = ENOTCONN;
238 return -1;
239 }
240 if (SOCK_DGRAM == type_) {
241 return SendUdp(pv, cb, remote_addr_);
242 } else {
243 return SendTcp(pv, cb);
244 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000245}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000247int VirtualSocket::SendTo(const void* pv,
248 size_t cb,
249 const SocketAddress& addr) {
250 if (SOCK_DGRAM == type_) {
251 return SendUdp(pv, cb, addr);
252 } else {
253 if (CS_CONNECTED != state_) {
254 error_ = ENOTCONN;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255 return -1;
256 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000257 return SendTcp(pv, cb);
258 }
259}
260
Stefan Holmer9131efd2016-05-23 18:19:26 +0200261int VirtualSocket::Recv(void* pv, size_t cb, int64_t* timestamp) {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000262 SocketAddress addr;
Stefan Holmer9131efd2016-05-23 18:19:26 +0200263 return RecvFrom(pv, cb, &addr, timestamp);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000264}
265
Stefan Holmer9131efd2016-05-23 18:19:26 +0200266int VirtualSocket::RecvFrom(void* pv,
267 size_t cb,
268 SocketAddress* paddr,
269 int64_t* timestamp) {
270 if (timestamp) {
271 *timestamp = -1;
272 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000273 // If we don't have a packet, then either error or wait for one to arrive.
274 if (recv_buffer_.empty()) {
275 if (async_) {
276 error_ = EAGAIN;
277 return -1;
278 }
279 while (recv_buffer_.empty()) {
280 Message msg;
281 server_->msg_queue_->Get(&msg);
282 server_->msg_queue_->Dispatch(&msg);
283 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284 }
285
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000286 // Return the packet at the front of the queue.
287 Packet* packet = recv_buffer_.front();
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000288 size_t data_read = std::min(cb, packet->size());
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000289 memcpy(pv, packet->data(), data_read);
290 *paddr = packet->from();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000292 if (data_read < packet->size()) {
293 packet->Consume(data_read);
294 } else {
295 recv_buffer_.pop_front();
296 delete packet;
297 }
298
deadbeefed3b9862017-06-02 10:33:16 -0700299 // To behave like a real socket, SignalReadEvent should fire in the next
300 // message loop pass if there's still data buffered.
301 if (!recv_buffer_.empty()) {
302 // Clear the message so it doesn't end up posted multiple times.
303 server_->msg_queue_->Clear(this, MSG_ID_SIGNALREADEVENT);
304 server_->msg_queue_->Post(RTC_FROM_HERE, this, MSG_ID_SIGNALREADEVENT);
305 }
306
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000307 if (SOCK_STREAM == type_) {
308 bool was_full = (recv_buffer_size_ == server_->recv_buffer_capacity_);
309 recv_buffer_size_ -= data_read;
310 if (was_full) {
311 VirtualSocket* sender = server_->LookupBinding(remote_addr_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800312 RTC_DCHECK(nullptr != sender);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000313 server_->SendTcp(sender);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000315 }
316
317 return static_cast<int>(data_read);
318}
319
320int VirtualSocket::Listen(int backlog) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700321 RTC_DCHECK(SOCK_STREAM == type_);
322 RTC_DCHECK(CS_CLOSED == state_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000323 if (local_addr_.IsNil()) {
324 error_ = EINVAL;
325 return -1;
326 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800327 RTC_DCHECK(nullptr == listen_queue_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000328 listen_queue_ = new ListenQueue;
329 state_ = CS_CONNECTING;
330 return 0;
331}
332
333VirtualSocket* VirtualSocket::Accept(SocketAddress* paddr) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800334 if (nullptr == listen_queue_) {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000335 error_ = EINVAL;
deadbeef37f5ecf2017-02-27 14:06:41 -0800336 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000338 while (!listen_queue_->empty()) {
339 VirtualSocket* socket = new VirtualSocket(server_, AF_INET, type_, async_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000341 // Set the new local address to the same as this server socket.
342 socket->SetLocalAddress(local_addr_);
343 // Sockets made from a socket that 'was Any' need to inherit that.
344 socket->set_was_any(was_any_);
345 SocketAddress remote_addr(listen_queue_->front());
346 int result = socket->InitiateConnect(remote_addr, false);
347 listen_queue_->pop_front();
348 if (result != 0) {
349 delete socket;
350 continue;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000352 socket->CompleteConnect(remote_addr, false);
353 if (paddr) {
354 *paddr = remote_addr;
355 }
356 return socket;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000358 error_ = EWOULDBLOCK;
deadbeef37f5ecf2017-02-27 14:06:41 -0800359 return nullptr;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000360}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000362int VirtualSocket::GetError() const {
363 return error_;
364}
365
366void VirtualSocket::SetError(int error) {
367 error_ = error;
368}
369
370Socket::ConnState VirtualSocket::GetState() const {
371 return state_;
372}
373
374int VirtualSocket::GetOption(Option opt, int* value) {
375 OptionsMap::const_iterator it = options_map_.find(opt);
376 if (it == options_map_.end()) {
377 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000378 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000379 *value = it->second;
380 return 0; // 0 is success to emulate getsockopt()
381}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000382
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000383int VirtualSocket::SetOption(Option opt, int value) {
384 options_map_[opt] = value;
385 return 0; // 0 is success to emulate setsockopt()
386}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000387
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000388void VirtualSocket::OnMessage(Message* pmsg) {
389 if (pmsg->message_id == MSG_ID_PACKET) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800390 RTC_DCHECK(nullptr != pmsg->pdata);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000391 Packet* packet = static_cast<Packet*>(pmsg->pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000392
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000393 recv_buffer_.push_back(packet);
394
395 if (async_) {
396 SignalReadEvent(this);
397 }
398 } else if (pmsg->message_id == MSG_ID_CONNECT) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800399 RTC_DCHECK(nullptr != pmsg->pdata);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000400 MessageAddress* data = static_cast<MessageAddress*>(pmsg->pdata);
deadbeef37f5ecf2017-02-27 14:06:41 -0800401 if (listen_queue_ != nullptr) {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000402 listen_queue_->push_back(data->addr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 if (async_) {
404 SignalReadEvent(this);
405 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000406 } else if ((SOCK_STREAM == type_) && (CS_CONNECTING == state_)) {
407 CompleteConnect(data->addr, true);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408 } else {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200409 RTC_LOG(LS_VERBOSE) << "Socket at " << local_addr_.ToString()
410 << " is not listening";
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000411 server_->Disconnect(server_->LookupBinding(data->addr));
412 }
413 delete data;
414 } else if (pmsg->message_id == MSG_ID_DISCONNECT) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700415 RTC_DCHECK(SOCK_STREAM == type_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000416 if (CS_CLOSED != state_) {
417 int error = (CS_CONNECTING == state_) ? ECONNREFUSED : 0;
418 state_ = CS_CLOSED;
419 remote_addr_.Clear();
420 if (async_) {
421 SignalCloseEvent(this, error);
422 }
423 }
guoweis@webrtc.org4fba2932014-12-18 04:45:05 +0000424 } else if (pmsg->message_id == MSG_ID_ADDRESS_BOUND) {
425 SignalAddressReady(this, GetLocalAddress());
deadbeefed3b9862017-06-02 10:33:16 -0700426 } else if (pmsg->message_id == MSG_ID_SIGNALREADEVENT) {
427 if (!recv_buffer_.empty()) {
428 SignalReadEvent(this);
429 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000430 } else {
nisseeb4ca4e2017-01-12 02:24:27 -0800431 RTC_NOTREACHED();
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000432 }
433}
434
435int VirtualSocket::InitiateConnect(const SocketAddress& addr, bool use_delay) {
436 if (!remote_addr_.IsNil()) {
437 error_ = (CS_CONNECTED == state_) ? EISCONN : EINPROGRESS;
438 return -1;
439 }
440 if (local_addr_.IsNil()) {
441 // If there's no local address set, grab a random one in the correct AF.
442 int result = 0;
443 if (addr.ipaddr().family() == AF_INET) {
444 result = Bind(SocketAddress("0.0.0.0", 0));
445 } else if (addr.ipaddr().family() == AF_INET6) {
446 result = Bind(SocketAddress("::", 0));
447 }
448 if (result != 0) {
449 return result;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000450 }
451 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000452 if (type_ == SOCK_DGRAM) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000453 remote_addr_ = addr;
454 state_ = CS_CONNECTED;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000455 } else {
456 int result = server_->Connect(this, addr, use_delay);
457 if (result != 0) {
458 error_ = EHOSTUNREACH;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000459 return -1;
460 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000461 state_ = CS_CONNECTING;
462 }
463 return 0;
464}
465
466void VirtualSocket::CompleteConnect(const SocketAddress& addr, bool notify) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700467 RTC_DCHECK(CS_CONNECTING == state_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000468 remote_addr_ = addr;
469 state_ = CS_CONNECTED;
470 server_->AddConnection(remote_addr_, local_addr_, this);
471 if (async_ && notify) {
472 SignalConnectEvent(this);
473 }
474}
475
476int VirtualSocket::SendUdp(const void* pv,
477 size_t cb,
478 const SocketAddress& addr) {
479 // If we have not been assigned a local port, then get one.
480 if (local_addr_.IsNil()) {
481 local_addr_ = EmptySocketAddressWithFamily(addr.ipaddr().family());
482 int result = server_->Bind(this, &local_addr_);
483 if (result != 0) {
484 local_addr_.Clear();
485 error_ = EADDRINUSE;
486 return result;
487 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000488 }
489
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000490 // Send the data in a message to the appropriate socket.
491 return server_->SendUdp(this, static_cast<const char*>(pv), cb, addr);
492}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000494int VirtualSocket::SendTcp(const void* pv, size_t cb) {
495 size_t capacity = server_->send_buffer_capacity_ - send_buffer_.size();
496 if (0 == capacity) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700497 ready_to_send_ = false;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000498 error_ = EWOULDBLOCK;
499 return -1;
500 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000501 size_t consumed = std::min(cb, capacity);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000502 const char* cpv = static_cast<const char*>(pv);
503 send_buffer_.insert(send_buffer_.end(), cpv, cpv + consumed);
504 server_->SendTcp(this);
505 return static_cast<int>(consumed);
506}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000507
Taylor Brandstettere7536412016-09-09 13:16:15 -0700508void VirtualSocket::OnSocketServerReadyToSend() {
509 if (ready_to_send_) {
510 // This socket didn't encounter EWOULDBLOCK, so there's nothing to do.
511 return;
512 }
513 if (type_ == SOCK_DGRAM) {
514 ready_to_send_ = true;
515 SignalWriteEvent(this);
516 } else {
517 RTC_DCHECK(type_ == SOCK_STREAM);
518 // This will attempt to empty the full send buffer, and will fire
519 // SignalWriteEvent if successful.
520 server_->SendTcp(this);
521 }
522}
523
deadbeef22e08142017-06-12 14:30:28 -0700524VirtualSocketServer::VirtualSocketServer() : VirtualSocketServer(nullptr) {}
525
Sebastian Janssond624c392019-04-17 10:36:03 +0200526VirtualSocketServer::VirtualSocketServer(ThreadProcessingFakeClock* fake_clock)
deadbeef22e08142017-06-12 14:30:28 -0700527 : fake_clock_(fake_clock),
deadbeef37f5ecf2017-02-27 14:06:41 -0800528 msg_queue_(nullptr),
Honghai Zhang82d78622016-05-06 11:29:15 -0700529 stop_on_idle_(false),
Honghai Zhang82d78622016-05-06 11:29:15 -0700530 next_ipv4_(kInitialNextIPv4),
531 next_ipv6_(kInitialNextIPv6),
532 next_port_(kFirstEphemeralPort),
533 bindings_(new AddressMap()),
534 connections_(new ConnectionMap()),
535 bandwidth_(0),
536 network_capacity_(kDefaultNetworkCapacity),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537 send_buffer_capacity_(kDefaultTcpBufferSize),
538 recv_buffer_capacity_(kDefaultTcpBufferSize),
Honghai Zhang82d78622016-05-06 11:29:15 -0700539 delay_mean_(0),
540 delay_stddev_(0),
541 delay_samples_(NUM_SAMPLES),
Honghai Zhang82d78622016-05-06 11:29:15 -0700542 drop_prob_(0.0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543 UpdateDelayDistribution();
544}
545
546VirtualSocketServer::~VirtualSocketServer() {
547 delete bindings_;
548 delete connections_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549}
550
551IPAddress VirtualSocketServer::GetNextIP(int family) {
552 if (family == AF_INET) {
553 IPAddress next_ip(next_ipv4_);
Yves Gerey665174f2018-06-19 15:03:05 +0200554 next_ipv4_.s_addr = HostToNetwork32(NetworkToHost32(next_ipv4_.s_addr) + 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000555 return next_ip;
556 } else if (family == AF_INET6) {
557 IPAddress next_ip(next_ipv6_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200558 uint32_t* as_ints = reinterpret_cast<uint32_t*>(&next_ipv6_.s6_addr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559 as_ints[3] += 1;
560 return next_ip;
561 }
562 return IPAddress();
563}
564
Peter Boström0c4e06b2015-10-07 12:23:21 +0200565uint16_t VirtualSocketServer::GetNextPort() {
566 uint16_t port = next_port_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000567 if (next_port_ < kLastEphemeralPort) {
568 ++next_port_;
569 } else {
570 next_port_ = kFirstEphemeralPort;
571 }
572 return port;
573}
574
Taylor Brandstettere7536412016-09-09 13:16:15 -0700575void VirtualSocketServer::SetSendingBlocked(bool blocked) {
576 if (blocked == sending_blocked_) {
577 // Unchanged; nothing to do.
578 return;
579 }
580 sending_blocked_ = blocked;
581 if (!sending_blocked_) {
582 // Sending was blocked, but is now unblocked. This signal gives sockets a
583 // chance to fire SignalWriteEvent, and for TCP, send buffered data.
584 SignalReadyToSend();
585 }
586}
587
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000588Socket* VirtualSocketServer::CreateSocket(int family, int type) {
589 return CreateSocketInternal(family, type);
590}
591
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000592AsyncSocket* VirtualSocketServer::CreateAsyncSocket(int family, int type) {
593 return CreateSocketInternal(family, type);
594}
595
596VirtualSocket* VirtualSocketServer::CreateSocketInternal(int family, int type) {
tommi5ce1a2a2016-05-14 03:19:31 -0700597 VirtualSocket* socket = new VirtualSocket(this, family, type, true);
598 SignalSocketCreated(socket);
599 return socket;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000600}
601
Sebastian Jansson290de822020-01-09 14:20:23 +0100602void VirtualSocketServer::SetMessageQueue(Thread* msg_queue) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000603 msg_queue_ = msg_queue;
604 if (msg_queue_) {
Yves Gerey665174f2018-06-19 15:03:05 +0200605 msg_queue_->SignalQueueDestroyed.connect(
606 this, &VirtualSocketServer::OnMessageQueueDestroyed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000607 }
608}
609
610bool VirtualSocketServer::Wait(int cmsWait, bool process_io) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700611 RTC_DCHECK(msg_queue_ == Thread::Current());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000612 if (stop_on_idle_ && Thread::Current()->empty()) {
613 return false;
614 }
deadbeef98e186c2017-05-16 18:00:06 -0700615 // Note: we don't need to do anything with |process_io| since we don't have
616 // any real I/O. Received packets come in the form of queued messages, so
Sebastian Jansson290de822020-01-09 14:20:23 +0100617 // Thread will ensure WakeUp is called if another thread sends a
deadbeef98e186c2017-05-16 18:00:06 -0700618 // packet.
619 wakeup_.Wait(cmsWait);
620 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000621}
622
623void VirtualSocketServer::WakeUp() {
deadbeef98e186c2017-05-16 18:00:06 -0700624 wakeup_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000625}
626
deadbeef5c3c1042017-08-04 15:01:57 -0700627void VirtualSocketServer::SetAlternativeLocalAddress(
628 const rtc::IPAddress& address,
629 const rtc::IPAddress& alternative) {
630 alternative_address_mapping_[address] = alternative;
631}
632
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000633bool VirtualSocketServer::ProcessMessagesUntilIdle() {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700634 RTC_DCHECK(msg_queue_ == Thread::Current());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000635 stop_on_idle_ = true;
636 while (!msg_queue_->empty()) {
deadbeef22e08142017-06-12 14:30:28 -0700637 if (fake_clock_) {
638 // If using a fake clock, advance it in millisecond increments until the
Bjorn Mellem6eb03b82017-06-13 15:07:41 -0700639 // queue is empty.
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100640 fake_clock_->AdvanceTime(webrtc::TimeDelta::Millis(1));
deadbeef22e08142017-06-12 14:30:28 -0700641 } else {
642 // Otherwise, run a normal message loop.
643 Message msg;
644 if (msg_queue_->Get(&msg, Thread::kForever)) {
645 msg_queue_->Dispatch(&msg);
646 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000647 }
648 }
649 stop_on_idle_ = false;
650 return !msg_queue_->IsQuitting();
651}
652
Peter Boström0c4e06b2015-10-07 12:23:21 +0200653void VirtualSocketServer::SetNextPortForTesting(uint16_t port) {
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000654 next_port_ = port;
655}
656
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700657bool VirtualSocketServer::CloseTcpConnections(
658 const SocketAddress& addr_local,
659 const SocketAddress& addr_remote) {
660 VirtualSocket* socket = LookupConnection(addr_local, addr_remote);
661 if (!socket) {
662 return false;
663 }
664 // Signal the close event on the local connection first.
665 socket->SignalCloseEvent(socket, 0);
666
667 // Trigger the remote connection's close event.
668 socket->Close();
669
670 return true;
671}
672
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000673int VirtualSocketServer::Bind(VirtualSocket* socket,
674 const SocketAddress& addr) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800675 RTC_DCHECK(nullptr != socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000676 // Address must be completely specified at this point
Taylor Brandstettere7536412016-09-09 13:16:15 -0700677 RTC_DCHECK(!IPIsUnspec(addr.ipaddr()));
678 RTC_DCHECK(addr.port() != 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000679
680 // Normalize the address (turns v6-mapped addresses into v4-addresses).
681 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
682
683 AddressMap::value_type entry(normalized, socket);
684 return bindings_->insert(entry).second ? 0 : -1;
685}
686
687int VirtualSocketServer::Bind(VirtualSocket* socket, SocketAddress* addr) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800688 RTC_DCHECK(nullptr != socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000689
deadbeef5c3c1042017-08-04 15:01:57 -0700690 // Normalize the IP.
guoweis@webrtc.orgd3b453b2015-02-14 00:43:41 +0000691 if (!IPIsUnspec(addr->ipaddr())) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000692 addr->SetIP(addr->ipaddr().Normalized());
693 } else {
nisseeb4ca4e2017-01-12 02:24:27 -0800694 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000695 }
696
deadbeef5c3c1042017-08-04 15:01:57 -0700697 // If the IP appears in |alternative_address_mapping_|, meaning the test has
698 // configured sockets bound to this IP to actually use another IP, replace
699 // the IP here.
700 auto alternative = alternative_address_mapping_.find(addr->ipaddr());
701 if (alternative != alternative_address_mapping_.end()) {
702 addr->SetIP(alternative->second);
703 }
704
705 // Assign a port if not assigned.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000706 if (addr->port() == 0) {
707 for (int i = 0; i < kEphemeralPortCount; ++i) {
708 addr->SetPort(GetNextPort());
709 if (bindings_->find(*addr) == bindings_->end()) {
710 break;
711 }
712 }
713 }
714
715 return Bind(socket, *addr);
716}
717
718VirtualSocket* VirtualSocketServer::LookupBinding(const SocketAddress& addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200719 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000720 AddressMap::iterator it = bindings_->find(normalized);
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700721 if (it != bindings_->end()) {
722 return it->second;
723 }
724
725 IPAddress default_ip = GetDefaultRoute(addr.ipaddr().family());
726 if (!IPIsUnspec(default_ip) && addr.ipaddr() == default_ip) {
727 // If we can't find a binding for the packet which is sent to the interface
728 // corresponding to the default route, it should match a binding with the
729 // correct port to the any address.
730 SocketAddress sock_addr =
731 EmptySocketAddressWithFamily(addr.ipaddr().family());
732 sock_addr.SetPort(addr.port());
733 return LookupBinding(sock_addr);
734 }
735
736 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000737}
738
739int VirtualSocketServer::Unbind(const SocketAddress& addr,
740 VirtualSocket* socket) {
Yves Gerey665174f2018-06-19 15:03:05 +0200741 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
Taylor Brandstettere7536412016-09-09 13:16:15 -0700742 RTC_DCHECK((*bindings_)[normalized] == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000743 bindings_->erase(bindings_->find(normalized));
744 return 0;
745}
746
747void VirtualSocketServer::AddConnection(const SocketAddress& local,
748 const SocketAddress& remote,
749 VirtualSocket* remote_socket) {
750 // Add this socket pair to our routing table. This will allow
751 // multiple clients to connect to the same server address.
Yves Gerey665174f2018-06-19 15:03:05 +0200752 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
753 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000754 SocketAddressPair address_pair(local_normalized, remote_normalized);
Yves Gerey665174f2018-06-19 15:03:05 +0200755 connections_->insert(std::pair<SocketAddressPair, VirtualSocket*>(
756 address_pair, remote_socket));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000757}
758
759VirtualSocket* VirtualSocketServer::LookupConnection(
760 const SocketAddress& local,
761 const SocketAddress& remote) {
Yves Gerey665174f2018-06-19 15:03:05 +0200762 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
763 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000764 SocketAddressPair address_pair(local_normalized, remote_normalized);
765 ConnectionMap::iterator it = connections_->find(address_pair);
deadbeef37f5ecf2017-02-27 14:06:41 -0800766 return (connections_->end() != it) ? it->second : nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000767}
768
769void VirtualSocketServer::RemoveConnection(const SocketAddress& local,
770 const SocketAddress& remote) {
Yves Gerey665174f2018-06-19 15:03:05 +0200771 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
772 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000773 SocketAddressPair address_pair(local_normalized, remote_normalized);
774 connections_->erase(address_pair);
775}
776
777static double Random() {
778 return static_cast<double>(rand()) / RAND_MAX;
779}
780
781int VirtualSocketServer::Connect(VirtualSocket* socket,
782 const SocketAddress& remote_addr,
783 bool use_delay) {
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700784 uint32_t delay = use_delay ? GetTransitDelay(socket) : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000785 VirtualSocket* remote = LookupBinding(remote_addr);
786 if (!CanInteractWith(socket, remote)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100787 RTC_LOG(LS_INFO) << "Address family mismatch between "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200788 << socket->GetLocalAddress().ToString() << " and "
789 << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000790 return -1;
791 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800792 if (remote != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000793 SocketAddress addr = socket->GetLocalAddress();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700794 msg_queue_->PostDelayed(RTC_FROM_HERE, delay, remote, MSG_ID_CONNECT,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000795 new MessageAddress(addr));
796 } else {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200797 RTC_LOG(LS_INFO) << "No one listening at " << remote_addr.ToString();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700798 msg_queue_->PostDelayed(RTC_FROM_HERE, delay, socket, MSG_ID_DISCONNECT);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000799 }
800 return 0;
801}
802
803bool VirtualSocketServer::Disconnect(VirtualSocket* socket) {
804 if (socket) {
Taylor Brandstetter716d07a2016-06-27 14:07:41 -0700805 // If we simulate packets being delayed, we should simulate the
806 // equivalent of a FIN being delayed as well.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700807 uint32_t delay = GetTransitDelay(socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000808 // Remove the mapping.
Taylor Brandstetter716d07a2016-06-27 14:07:41 -0700809 msg_queue_->PostDelayed(RTC_FROM_HERE, delay, socket, MSG_ID_DISCONNECT);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000810 return true;
811 }
812 return false;
813}
814
815int VirtualSocketServer::SendUdp(VirtualSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200816 const char* data,
817 size_t data_size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000818 const SocketAddress& remote_addr) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -0800819 ++sent_packets_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700820 if (sending_blocked_) {
821 CritScope cs(&socket->crit_);
822 socket->ready_to_send_ = false;
823 socket->error_ = EWOULDBLOCK;
824 return -1;
825 }
826
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000827 // See if we want to drop this packet.
828 if (Random() < drop_prob_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100829 RTC_LOG(LS_VERBOSE) << "Dropping packet: bad luck";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830 return static_cast<int>(data_size);
831 }
832
833 VirtualSocket* recipient = LookupBinding(remote_addr);
834 if (!recipient) {
835 // Make a fake recipient for address family checking.
jbauch555604a2016-04-26 03:13:22 -0700836 std::unique_ptr<VirtualSocket> dummy_socket(
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000837 CreateSocketInternal(AF_INET, SOCK_DGRAM));
838 dummy_socket->SetLocalAddress(remote_addr);
839 if (!CanInteractWith(socket, dummy_socket.get())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100840 RTC_LOG(LS_VERBOSE) << "Incompatible address families: "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200841 << socket->GetLocalAddress().ToString() << " and "
842 << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843 return -1;
844 }
Jonas Olssonabbe8412018-04-03 13:40:05 +0200845 RTC_LOG(LS_VERBOSE) << "No one listening at " << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000846 return static_cast<int>(data_size);
847 }
848
849 if (!CanInteractWith(socket, recipient)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_VERBOSE) << "Incompatible address families: "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200851 << socket->GetLocalAddress().ToString() << " and "
852 << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853 return -1;
854 }
855
Taylor Brandstettere7536412016-09-09 13:16:15 -0700856 {
857 CritScope cs(&socket->crit_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000858
Taylor Brandstettere7536412016-09-09 13:16:15 -0700859 int64_t cur_time = TimeMillis();
860 PurgeNetworkPackets(socket, cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000861
Taylor Brandstettere7536412016-09-09 13:16:15 -0700862 // Determine whether we have enough bandwidth to accept this packet. To do
863 // this, we need to update the send queue. Once we know it's current size,
864 // we know whether we can fit this packet.
865 //
866 // NOTE: There are better algorithms for maintaining such a queue (such as
867 // "Derivative Random Drop"); however, this algorithm is a more accurate
868 // simulation of what a normal network would do.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000869
Taylor Brandstettere7536412016-09-09 13:16:15 -0700870 size_t packet_size = data_size + UDP_HEADER_SIZE;
871 if (socket->network_size_ + packet_size > network_capacity_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG(LS_VERBOSE) << "Dropping packet: network capacity exceeded";
Taylor Brandstettere7536412016-09-09 13:16:15 -0700873 return static_cast<int>(data_size);
874 }
875
876 AddPacketToNetwork(socket, recipient, cur_time, data, data_size,
877 UDP_HEADER_SIZE, false);
878
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000879 return static_cast<int>(data_size);
880 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000881}
882
883void VirtualSocketServer::SendTcp(VirtualSocket* socket) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -0800884 ++sent_packets_;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700885 if (sending_blocked_) {
886 // Eventually the socket's buffer will fill and VirtualSocket::SendTcp will
887 // set EWOULDBLOCK.
888 return;
889 }
890
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000891 // TCP can't send more data than will fill up the receiver's buffer.
892 // We track the data that is in the buffer plus data in flight using the
893 // recipient's recv_buffer_size_. Anything beyond that must be stored in the
894 // sender's buffer. We will trigger the buffered data to be sent when data
895 // is read from the recv_buffer.
896
897 // Lookup the local/remote pair in the connections table.
Yves Gerey665174f2018-06-19 15:03:05 +0200898 VirtualSocket* recipient =
899 LookupConnection(socket->local_addr_, socket->remote_addr_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 if (!recipient) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100901 RTC_LOG(LS_VERBOSE) << "Sending data to no one.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000902 return;
903 }
904
905 CritScope cs(&socket->crit_);
906
Honghai Zhang82d78622016-05-06 11:29:15 -0700907 int64_t cur_time = TimeMillis();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000908 PurgeNetworkPackets(socket, cur_time);
909
910 while (true) {
911 size_t available = recv_buffer_capacity_ - recipient->recv_buffer_size_;
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000912 size_t max_data_size =
913 std::min<size_t>(available, TCP_MSS - TCP_HEADER_SIZE);
914 size_t data_size = std::min(socket->send_buffer_.size(), max_data_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915 if (0 == data_size)
916 break;
917
918 AddPacketToNetwork(socket, recipient, cur_time, &socket->send_buffer_[0],
919 data_size, TCP_HEADER_SIZE, true);
920 recipient->recv_buffer_size_ += data_size;
921
922 size_t new_buffer_size = socket->send_buffer_.size() - data_size;
923 // Avoid undefined access beyond the last element of the vector.
924 // This only happens when new_buffer_size is 0.
925 if (data_size < socket->send_buffer_.size()) {
926 // memmove is required for potentially overlapping source/destination.
927 memmove(&socket->send_buffer_[0], &socket->send_buffer_[data_size],
928 new_buffer_size);
929 }
930 socket->send_buffer_.resize(new_buffer_size);
931 }
932
Taylor Brandstettere7536412016-09-09 13:16:15 -0700933 if (!socket->ready_to_send_ &&
934 (socket->send_buffer_.size() < send_buffer_capacity_)) {
935 socket->ready_to_send_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000936 socket->SignalWriteEvent(socket);
937 }
938}
939
940void VirtualSocketServer::AddPacketToNetwork(VirtualSocket* sender,
941 VirtualSocket* recipient,
Honghai Zhang82d78622016-05-06 11:29:15 -0700942 int64_t cur_time,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000943 const char* data,
944 size_t data_size,
945 size_t header_size,
946 bool ordered) {
947 VirtualSocket::NetworkEntry entry;
948 entry.size = data_size + header_size;
949
950 sender->network_size_ += entry.size;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200951 uint32_t send_delay = SendDelay(static_cast<uint32_t>(sender->network_size_));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000952 entry.done_time = cur_time + send_delay;
953 sender->network_.push_back(entry);
954
955 // Find the delay for crossing the many virtual hops of the network.
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700956 uint32_t transit_delay = GetTransitDelay(sender);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000957
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700958 // When the incoming packet is from a binding of the any address, translate it
959 // to the default route here such that the recipient will see the default
960 // route.
961 SocketAddress sender_addr = sender->local_addr_;
962 IPAddress default_ip = GetDefaultRoute(sender_addr.ipaddr().family());
963 if (sender_addr.IsAnyIP() && !IPIsUnspec(default_ip)) {
964 sender_addr.SetIP(default_ip);
965 }
966
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000967 // Post the packet as a message to be delivered (on our own thread)
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700968 Packet* p = new Packet(data, data_size, sender_addr);
969
Honghai Zhang82d78622016-05-06 11:29:15 -0700970 int64_t ts = TimeAfter(send_delay + transit_delay);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000971 if (ordered) {
972 // Ensure that new packets arrive after previous ones
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700973 ts = std::max(ts, sender->last_delivery_time_);
974 // A socket should not have both ordered and unordered delivery, so its last
975 // delivery time only needs to be updated when it has ordered delivery.
976 sender->last_delivery_time_ = ts;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000977 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700978 msg_queue_->PostAt(RTC_FROM_HERE, ts, recipient, MSG_ID_PACKET, p);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000979}
980
981void VirtualSocketServer::PurgeNetworkPackets(VirtualSocket* socket,
Honghai Zhang82d78622016-05-06 11:29:15 -0700982 int64_t cur_time) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000983 while (!socket->network_.empty() &&
984 (socket->network_.front().done_time <= cur_time)) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700985 RTC_DCHECK(socket->network_size_ >= socket->network_.front().size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986 socket->network_size_ -= socket->network_.front().size;
987 socket->network_.pop_front();
988 }
989}
990
Peter Boström0c4e06b2015-10-07 12:23:21 +0200991uint32_t VirtualSocketServer::SendDelay(uint32_t size) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000992 if (bandwidth_ == 0)
993 return 0;
994 else
995 return 1000 * size / bandwidth_;
996}
997
998#if 0
999void PrintFunction(std::vector<std::pair<double, double> >* f) {
1000 return;
1001 double sum = 0;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001002 for (uint32_t i = 0; i < f->size(); ++i) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001003 std::cout << (*f)[i].first << '\t' << (*f)[i].second << std::endl;
1004 sum += (*f)[i].second;
1005 }
1006 if (!f->empty()) {
1007 const double mean = sum / f->size();
1008 double sum_sq_dev = 0;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001009 for (uint32_t i = 0; i < f->size(); ++i) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001010 double dev = (*f)[i].second - mean;
1011 sum_sq_dev += dev * dev;
1012 }
1013 std::cout << "Mean = " << mean << " StdDev = "
1014 << sqrt(sum_sq_dev / f->size()) << std::endl;
1015 }
1016}
1017#endif // <unused>
1018
1019void VirtualSocketServer::UpdateDelayDistribution() {
Yves Gerey665174f2018-06-19 15:03:05 +02001020 Function* dist =
1021 CreateDistribution(delay_mean_, delay_stddev_, delay_samples_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001022 // We take a lock just to make sure we don't leak memory.
1023 {
1024 CritScope cs(&delay_crit_);
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001025 delay_dist_.reset(dist);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001026 }
1027}
1028
1029static double PI = 4 * atan(1.0);
1030
1031static double Normal(double x, double mean, double stddev) {
1032 double a = (x - mean) * (x - mean) / (2 * stddev * stddev);
1033 return exp(-a) / (stddev * sqrt(2 * PI));
1034}
1035
1036#if 0 // static unused gives a warning
1037static double Pareto(double x, double min, double k) {
1038 if (x < min)
1039 return 0;
1040 else
1041 return k * std::pow(min, k) / std::pow(x, k+1);
1042}
1043#endif
1044
1045VirtualSocketServer::Function* VirtualSocketServer::CreateDistribution(
Peter Boström0c4e06b2015-10-07 12:23:21 +02001046 uint32_t mean,
1047 uint32_t stddev,
1048 uint32_t samples) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001049 Function* f = new Function();
1050
1051 if (0 == stddev) {
1052 f->push_back(Point(mean, 1.0));
1053 } else {
1054 double start = 0;
1055 if (mean >= 4 * static_cast<double>(stddev))
1056 start = mean - 4 * static_cast<double>(stddev);
1057 double end = mean + 4 * static_cast<double>(stddev);
1058
Peter Boström0c4e06b2015-10-07 12:23:21 +02001059 for (uint32_t i = 0; i < samples; i++) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001060 double x = start + (end - start) * i / (samples - 1);
1061 double y = Normal(x, mean, stddev);
1062 f->push_back(Point(x, y));
1063 }
1064 }
1065 return Resample(Invert(Accumulate(f)), 0, 1, samples);
1066}
1067
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001068uint32_t VirtualSocketServer::GetTransitDelay(Socket* socket) {
1069 // Use the delay based on the address if it is set.
1070 auto iter = delay_by_ip_.find(socket->GetLocalAddress().ipaddr());
1071 if (iter != delay_by_ip_.end()) {
1072 return static_cast<uint32_t>(iter->second);
1073 }
1074 // Otherwise, use the delay from the distribution distribution.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001075 size_t index = rand() % delay_dist_->size();
1076 double delay = (*delay_dist_)[index].second;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001077 // RTC_LOG_F(LS_INFO) << "random[" << index << "] = " << delay;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001078 return static_cast<uint32_t>(delay);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001079}
1080
1081struct FunctionDomainCmp {
1082 bool operator()(const VirtualSocketServer::Point& p1,
Yves Gerey665174f2018-06-19 15:03:05 +02001083 const VirtualSocketServer::Point& p2) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001084 return p1.first < p2.first;
1085 }
1086 bool operator()(double v1, const VirtualSocketServer::Point& p2) {
1087 return v1 < p2.first;
1088 }
1089 bool operator()(const VirtualSocketServer::Point& p1, double v2) {
1090 return p1.first < v2;
1091 }
1092};
1093
1094VirtualSocketServer::Function* VirtualSocketServer::Accumulate(Function* f) {
Taylor Brandstettere7536412016-09-09 13:16:15 -07001095 RTC_DCHECK(f->size() >= 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001096 double v = 0;
1097 for (Function::size_type i = 0; i < f->size() - 1; ++i) {
1098 double dx = (*f)[i + 1].first - (*f)[i].first;
1099 double avgy = ((*f)[i + 1].second + (*f)[i].second) / 2;
1100 (*f)[i].second = v;
1101 v = v + dx * avgy;
1102 }
Yves Gerey665174f2018-06-19 15:03:05 +02001103 (*f)[f->size() - 1].second = v;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001104 return f;
1105}
1106
1107VirtualSocketServer::Function* VirtualSocketServer::Invert(Function* f) {
1108 for (Function::size_type i = 0; i < f->size(); ++i)
1109 std::swap((*f)[i].first, (*f)[i].second);
1110
Steve Anton2acd1632019-03-25 13:48:30 -07001111 absl::c_sort(*f, FunctionDomainCmp());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001112 return f;
1113}
1114
Peter Boström0c4e06b2015-10-07 12:23:21 +02001115VirtualSocketServer::Function* VirtualSocketServer::Resample(Function* f,
1116 double x1,
1117 double x2,
1118 uint32_t samples) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001119 Function* g = new Function();
1120
1121 for (size_t i = 0; i < samples; i++) {
1122 double x = x1 + (x2 - x1) * i / (samples - 1);
1123 double y = Evaluate(f, x);
1124 g->push_back(Point(x, y));
1125 }
1126
1127 delete f;
1128 return g;
1129}
1130
1131double VirtualSocketServer::Evaluate(Function* f, double x) {
Steve Anton2acd1632019-03-25 13:48:30 -07001132 Function::iterator iter = absl::c_lower_bound(*f, x, FunctionDomainCmp());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133 if (iter == f->begin()) {
1134 return (*f)[0].second;
1135 } else if (iter == f->end()) {
Taylor Brandstettere7536412016-09-09 13:16:15 -07001136 RTC_DCHECK(f->size() >= 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001137 return (*f)[f->size() - 1].second;
1138 } else if (iter->first == x) {
1139 return iter->second;
1140 } else {
1141 double x1 = (iter - 1)->first;
1142 double y1 = (iter - 1)->second;
1143 double x2 = iter->first;
1144 double y2 = iter->second;
1145 return y1 + (y2 - y1) * (x - x1) / (x2 - x1);
1146 }
1147}
1148
1149bool VirtualSocketServer::CanInteractWith(VirtualSocket* local,
1150 VirtualSocket* remote) {
1151 if (!local || !remote) {
1152 return false;
1153 }
1154 IPAddress local_ip = local->GetLocalAddress().ipaddr();
1155 IPAddress remote_ip = remote->GetLocalAddress().ipaddr();
1156 IPAddress local_normalized = local_ip.Normalized();
1157 IPAddress remote_normalized = remote_ip.Normalized();
1158 // Check if the addresses are the same family after Normalization (turns
1159 // mapped IPv6 address into IPv4 addresses).
1160 // This will stop unmapped V6 addresses from talking to mapped V6 addresses.
1161 if (local_normalized.family() == remote_normalized.family()) {
1162 return true;
1163 }
1164
1165 // If ip1 is IPv4 and ip2 is :: and ip2 is not IPV6_V6ONLY.
1166 int remote_v6_only = 0;
1167 remote->GetOption(Socket::OPT_IPV6_V6ONLY, &remote_v6_only);
1168 if (local_ip.family() == AF_INET && !remote_v6_only && IPIsAny(remote_ip)) {
1169 return true;
1170 }
1171 // Same check, backwards.
1172 int local_v6_only = 0;
1173 local->GetOption(Socket::OPT_IPV6_V6ONLY, &local_v6_only);
1174 if (remote_ip.family() == AF_INET && !local_v6_only && IPIsAny(local_ip)) {
1175 return true;
1176 }
1177
1178 // Check to see if either socket was explicitly bound to IPv6-any.
1179 // These sockets can talk with anyone.
1180 if (local_ip.family() == AF_INET6 && local->was_any()) {
1181 return true;
1182 }
1183 if (remote_ip.family() == AF_INET6 && remote->was_any()) {
1184 return true;
1185 }
1186
1187 return false;
1188}
1189
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001190IPAddress VirtualSocketServer::GetDefaultRoute(int family) {
1191 if (family == AF_INET) {
1192 return default_route_v4_;
1193 }
1194 if (family == AF_INET6) {
1195 return default_route_v6_;
1196 }
1197 return IPAddress();
1198}
1199void VirtualSocketServer::SetDefaultRoute(const IPAddress& from_addr) {
henrikg91d6ede2015-09-17 00:24:34 -07001200 RTC_DCHECK(!IPIsAny(from_addr));
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001201 if (from_addr.family() == AF_INET) {
1202 default_route_v4_ = from_addr;
1203 } else if (from_addr.family() == AF_INET6) {
1204 default_route_v6_ = from_addr;
1205 }
1206}
1207
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001208} // namespace rtc