blob: 6e5eeb28c784b86b4be721ecfd091c04dd7cc59e [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"
Markus Handell2cfc1af2022-08-19 08:16:48 +000021#include "api/units/time_delta.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/checks.h"
Markus Handell2cfc1af2022-08-19 08:16:48 +000023#include "rtc_base/event.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/fake_clock.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/physical_socket_server.h"
27#include "rtc_base/socket_address_pair.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/thread.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000030
31namespace rtc {
32#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +020033const in_addr kInitialNextIPv4 = {{{0x01, 0, 0, 0}}};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034#else
35// This value is entirely arbitrary, hence the lack of concern about endianness.
Yves Gerey665174f2018-06-19 15:03:05 +020036const in_addr kInitialNextIPv4 = {0x01000000};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000037#endif
38// Starts at ::2 so as to not cause confusion with ::1.
Yves Gerey665174f2018-06-19 15:03:05 +020039const in6_addr kInitialNextIPv6 = {
40 {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}}};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041
Peter Boström0c4e06b2015-10-07 12:23:21 +020042const uint16_t kFirstEphemeralPort = 49152;
43const uint16_t kLastEphemeralPort = 65535;
44const uint16_t kEphemeralPortCount =
45 kLastEphemeralPort - kFirstEphemeralPort + 1;
46const uint32_t kDefaultNetworkCapacity = 64 * 1024;
47const uint32_t kDefaultTcpBufferSize = 32 * 1024;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048
Peter Boström0c4e06b2015-10-07 12:23:21 +020049const uint32_t UDP_HEADER_SIZE = 28; // IP + UDP headers
50const uint32_t TCP_HEADER_SIZE = 40; // IP + TCP headers
51const uint32_t TCP_MSS = 1400; // Maximum segment size
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052
53// Note: The current algorithm doesn't work for sample sizes smaller than this.
54const int NUM_SAMPLES = 1000;
55
56enum {
57 MSG_ID_PACKET,
58 MSG_ID_CONNECT,
59 MSG_ID_DISCONNECT,
deadbeefed3b9862017-06-02 10:33:16 -070060 MSG_ID_SIGNALREADEVENT,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061};
62
63// Packets are passed between sockets as messages. We copy the data just like
64// the kernel does.
65class Packet : public MessageData {
66 public:
67 Packet(const char* data, size_t size, const SocketAddress& from)
Yves Gerey665174f2018-06-19 15:03:05 +020068 : size_(size), consumed_(0), from_(from) {
deadbeef37f5ecf2017-02-27 14:06:41 -080069 RTC_DCHECK(nullptr != data);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070 data_ = new char[size_];
71 memcpy(data_, data, size_);
72 }
73
Yves Gerey665174f2018-06-19 15:03:05 +020074 ~Packet() override { delete[] data_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000075
76 const char* data() const { return data_ + consumed_; }
77 size_t size() const { return size_ - consumed_; }
78 const SocketAddress& from() const { return from_; }
79
80 // Remove the first size bytes from the data.
81 void Consume(size_t size) {
Taylor Brandstettere7536412016-09-09 13:16:15 -070082 RTC_DCHECK(size + consumed_ < size_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083 consumed_ += size;
84 }
85
86 private:
87 char* data_;
88 size_t size_, consumed_;
89 SocketAddress from_;
90};
91
92struct MessageAddress : public MessageData {
Yves Gerey665174f2018-06-19 15:03:05 +020093 explicit MessageAddress(const SocketAddress& a) : addr(a) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094 SocketAddress addr;
95};
96
Niels Möllerea423a52021-08-19 10:13:31 +020097VirtualSocket::VirtualSocket(VirtualSocketServer* server, int family, int type)
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +000098 : server_(server),
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +000099 type_(type),
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000100 state_(CS_CLOSED),
101 error_(0),
deadbeef37f5ecf2017-02-27 14:06:41 -0800102 listen_queue_(nullptr),
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000103 network_size_(0),
104 recv_buffer_size_(0),
105 bound_(false),
106 was_any_(false) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700107 RTC_DCHECK((type_ == SOCK_DGRAM) || (type_ == SOCK_STREAM));
Taylor Brandstettere7536412016-09-09 13:16:15 -0700108 server->SignalReadyToSend.connect(this,
109 &VirtualSocket::OnSocketServerReadyToSend);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000110}
111
112VirtualSocket::~VirtualSocket() {
113 Close();
114
115 for (RecvBuffer::iterator it = recv_buffer_.begin(); it != recv_buffer_.end();
116 ++it) {
117 delete *it;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000118 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000119}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000120
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000121SocketAddress VirtualSocket::GetLocalAddress() const {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000122 return local_addr_;
123}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000124
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000125SocketAddress VirtualSocket::GetRemoteAddress() const {
126 return remote_addr_;
127}
128
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000129void VirtualSocket::SetLocalAddress(const SocketAddress& addr) {
130 local_addr_ = addr;
131}
132
133int VirtualSocket::Bind(const SocketAddress& addr) {
134 if (!local_addr_.IsNil()) {
135 error_ = EINVAL;
136 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 }
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200138 local_addr_ = server_->AssignBindAddress(addr);
139 int result = server_->Bind(this, local_addr_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000140 if (result != 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 local_addr_.Clear();
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000142 error_ = EADDRINUSE;
143 } else {
144 bound_ = true;
145 was_any_ = addr.IsAnyIP();
146 }
147 return result;
148}
149
150int VirtualSocket::Connect(const SocketAddress& addr) {
151 return InitiateConnect(addr, true);
152}
153
154int VirtualSocket::Close() {
155 if (!local_addr_.IsNil() && bound_) {
156 // Remove from the binding table.
157 server_->Unbind(local_addr_, this);
158 bound_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000159 }
160
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000161 if (SOCK_STREAM == type_) {
Niels Möllerc413c552021-06-22 10:03:14 +0200162 webrtc::MutexLock lock(&mutex_);
Niels Möller257f81b2021-06-17 16:58:59 +0200163
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000164 // Cancel pending sockets
165 if (listen_queue_) {
166 while (!listen_queue_->empty()) {
167 SocketAddress addr = listen_queue_->front();
168
169 // Disconnect listening socket.
Niels Möllerc79bd432021-02-16 09:25:52 +0100170 server_->Disconnect(addr);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000171 listen_queue_->pop_front();
172 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800173 listen_queue_ = nullptr;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000174 }
175 // Disconnect stream sockets
176 if (CS_CONNECTED == state_) {
Niels Möllerc79bd432021-02-16 09:25:52 +0100177 server_->Disconnect(local_addr_, remote_addr_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000178 }
179 // Cancel potential connects
Niels Möllerc79bd432021-02-16 09:25:52 +0100180 server_->CancelConnects(this);
Tomas Gunnarssond9663472020-11-21 16:20:23 +0100181 }
182
183 // Clear incoming packets and disconnect messages
Niels Möllerc79bd432021-02-16 09:25:52 +0100184 server_->Clear(this);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000185
186 state_ = CS_CLOSED;
187 local_addr_.Clear();
188 remote_addr_.Clear();
189 return 0;
190}
191
192int VirtualSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200193 if (CS_CONNECTED != state_) {
194 error_ = ENOTCONN;
195 return -1;
196 }
197 if (SOCK_DGRAM == type_) {
198 return SendUdp(pv, cb, remote_addr_);
199 } else {
200 return SendTcp(pv, cb);
201 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000202}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000203
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000204int VirtualSocket::SendTo(const void* pv,
205 size_t cb,
206 const SocketAddress& addr) {
207 if (SOCK_DGRAM == type_) {
208 return SendUdp(pv, cb, addr);
209 } else {
210 if (CS_CONNECTED != state_) {
211 error_ = ENOTCONN;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000212 return -1;
213 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000214 return SendTcp(pv, cb);
215 }
216}
217
Stefan Holmer9131efd2016-05-23 18:19:26 +0200218int VirtualSocket::Recv(void* pv, size_t cb, int64_t* timestamp) {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000219 SocketAddress addr;
Stefan Holmer9131efd2016-05-23 18:19:26 +0200220 return RecvFrom(pv, cb, &addr, timestamp);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000221}
222
Stefan Holmer9131efd2016-05-23 18:19:26 +0200223int VirtualSocket::RecvFrom(void* pv,
224 size_t cb,
225 SocketAddress* paddr,
226 int64_t* timestamp) {
227 if (timestamp) {
228 *timestamp = -1;
229 }
Niels Möller257f81b2021-06-17 16:58:59 +0200230
Niels Möllerc413c552021-06-22 10:03:14 +0200231 webrtc::MutexLock lock(&mutex_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000232 // If we don't have a packet, then either error or wait for one to arrive.
233 if (recv_buffer_.empty()) {
Niels Möllerea423a52021-08-19 10:13:31 +0200234 error_ = EAGAIN;
235 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236 }
237
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000238 // Return the packet at the front of the queue.
239 Packet* packet = recv_buffer_.front();
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000240 size_t data_read = std::min(cb, packet->size());
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000241 memcpy(pv, packet->data(), data_read);
242 *paddr = packet->from();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000243
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000244 if (data_read < packet->size()) {
245 packet->Consume(data_read);
246 } else {
247 recv_buffer_.pop_front();
248 delete packet;
249 }
250
deadbeefed3b9862017-06-02 10:33:16 -0700251 // To behave like a real socket, SignalReadEvent should fire in the next
252 // message loop pass if there's still data buffered.
253 if (!recv_buffer_.empty()) {
Niels Möllerc79bd432021-02-16 09:25:52 +0100254 server_->PostSignalReadEvent(this);
deadbeefed3b9862017-06-02 10:33:16 -0700255 }
256
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000257 if (SOCK_STREAM == type_) {
Niels Möllerc79bd432021-02-16 09:25:52 +0100258 bool was_full = (recv_buffer_size_ == server_->recv_buffer_capacity());
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000259 recv_buffer_size_ -= data_read;
260 if (was_full) {
Niels Möllerc79bd432021-02-16 09:25:52 +0100261 server_->SendTcp(remote_addr_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000263 }
264
265 return static_cast<int>(data_read);
266}
267
268int VirtualSocket::Listen(int backlog) {
Niels Möllerc413c552021-06-22 10:03:14 +0200269 webrtc::MutexLock lock(&mutex_);
Taylor Brandstettere7536412016-09-09 13:16:15 -0700270 RTC_DCHECK(SOCK_STREAM == type_);
271 RTC_DCHECK(CS_CLOSED == state_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000272 if (local_addr_.IsNil()) {
273 error_ = EINVAL;
274 return -1;
275 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800276 RTC_DCHECK(nullptr == listen_queue_);
Niels Möllerc413c552021-06-22 10:03:14 +0200277 listen_queue_ = std::make_unique<ListenQueue>();
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000278 state_ = CS_CONNECTING;
279 return 0;
280}
281
282VirtualSocket* VirtualSocket::Accept(SocketAddress* paddr) {
Niels Möllerc413c552021-06-22 10:03:14 +0200283 webrtc::MutexLock lock(&mutex_);
deadbeef37f5ecf2017-02-27 14:06:41 -0800284 if (nullptr == listen_queue_) {
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000285 error_ = EINVAL;
deadbeef37f5ecf2017-02-27 14:06:41 -0800286 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000288 while (!listen_queue_->empty()) {
Niels Möllerea423a52021-08-19 10:13:31 +0200289 VirtualSocket* socket = new VirtualSocket(server_, AF_INET, type_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000291 // Set the new local address to the same as this server socket.
292 socket->SetLocalAddress(local_addr_);
293 // Sockets made from a socket that 'was Any' need to inherit that.
294 socket->set_was_any(was_any_);
295 SocketAddress remote_addr(listen_queue_->front());
296 int result = socket->InitiateConnect(remote_addr, false);
297 listen_queue_->pop_front();
298 if (result != 0) {
299 delete socket;
300 continue;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301 }
Niels Möllerc413c552021-06-22 10:03:14 +0200302 socket->CompleteConnect(remote_addr);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000303 if (paddr) {
304 *paddr = remote_addr;
305 }
306 return socket;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000308 error_ = EWOULDBLOCK;
deadbeef37f5ecf2017-02-27 14:06:41 -0800309 return nullptr;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000310}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000312int VirtualSocket::GetError() const {
313 return error_;
314}
315
316void VirtualSocket::SetError(int error) {
317 error_ = error;
318}
319
320Socket::ConnState VirtualSocket::GetState() const {
321 return state_;
322}
323
324int VirtualSocket::GetOption(Option opt, int* value) {
325 OptionsMap::const_iterator it = options_map_.find(opt);
326 if (it == options_map_.end()) {
327 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000329 *value = it->second;
330 return 0; // 0 is success to emulate getsockopt()
331}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000332
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000333int VirtualSocket::SetOption(Option opt, int value) {
334 options_map_[opt] = value;
335 return 0; // 0 is success to emulate setsockopt()
336}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000338void VirtualSocket::OnMessage(Message* pmsg) {
Niels Möller257f81b2021-06-17 16:58:59 +0200339 bool signal_read_event = false;
340 bool signal_close_event = false;
Niels Möllerc413c552021-06-22 10:03:14 +0200341 bool signal_connect_event = false;
Niels Möller257f81b2021-06-17 16:58:59 +0200342 int error_to_signal = 0;
343 {
Niels Möllerc413c552021-06-22 10:03:14 +0200344 webrtc::MutexLock lock(&mutex_);
Niels Möller257f81b2021-06-17 16:58:59 +0200345 if (pmsg->message_id == MSG_ID_PACKET) {
346 RTC_DCHECK(nullptr != pmsg->pdata);
347 Packet* packet = static_cast<Packet*>(pmsg->pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348
Niels Möller257f81b2021-06-17 16:58:59 +0200349 recv_buffer_.push_back(packet);
Niels Möllerea423a52021-08-19 10:13:31 +0200350 signal_read_event = true;
Niels Möller257f81b2021-06-17 16:58:59 +0200351 } else if (pmsg->message_id == MSG_ID_CONNECT) {
352 RTC_DCHECK(nullptr != pmsg->pdata);
353 MessageAddress* data = static_cast<MessageAddress*>(pmsg->pdata);
354 if (listen_queue_ != nullptr) {
355 listen_queue_->push_back(data->addr);
Niels Möllerea423a52021-08-19 10:13:31 +0200356 signal_read_event = true;
Niels Möller257f81b2021-06-17 16:58:59 +0200357 } else if ((SOCK_STREAM == type_) && (CS_CONNECTING == state_)) {
Niels Möllerc413c552021-06-22 10:03:14 +0200358 CompleteConnect(data->addr);
Niels Möllerea423a52021-08-19 10:13:31 +0200359 signal_connect_event = true;
Niels Möller257f81b2021-06-17 16:58:59 +0200360 } else {
361 RTC_LOG(LS_VERBOSE)
362 << "Socket at " << local_addr_.ToString() << " is not listening";
363 server_->Disconnect(data->addr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000364 }
Niels Möller257f81b2021-06-17 16:58:59 +0200365 delete data;
366 } else if (pmsg->message_id == MSG_ID_DISCONNECT) {
367 RTC_DCHECK(SOCK_STREAM == type_);
368 if (CS_CLOSED != state_) {
369 error_to_signal = (CS_CONNECTING == state_) ? ECONNREFUSED : 0;
370 state_ = CS_CLOSED;
371 remote_addr_.Clear();
Niels Möllerea423a52021-08-19 10:13:31 +0200372 signal_close_event = true;
Niels Möller257f81b2021-06-17 16:58:59 +0200373 }
374 } else if (pmsg->message_id == MSG_ID_SIGNALREADEVENT) {
375 signal_read_event = !recv_buffer_.empty();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376 } else {
Artem Titovd3251962021-11-15 16:57:07 +0100377 RTC_DCHECK_NOTREACHED();
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000378 }
Niels Möller257f81b2021-06-17 16:58:59 +0200379 }
Niels Möllerc413c552021-06-22 10:03:14 +0200380 // Signal events without holding `mutex_`, to avoid recursive locking, as well
381 // as issues with sigslot and lock order.
Niels Möller257f81b2021-06-17 16:58:59 +0200382 if (signal_read_event) {
383 SignalReadEvent(this);
384 }
385 if (signal_close_event) {
386 SignalCloseEvent(this, error_to_signal);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000387 }
Niels Möllerc413c552021-06-22 10:03:14 +0200388 if (signal_connect_event) {
389 SignalConnectEvent(this);
390 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000391}
392
393int VirtualSocket::InitiateConnect(const SocketAddress& addr, bool use_delay) {
394 if (!remote_addr_.IsNil()) {
395 error_ = (CS_CONNECTED == state_) ? EISCONN : EINPROGRESS;
396 return -1;
397 }
398 if (local_addr_.IsNil()) {
399 // If there's no local address set, grab a random one in the correct AF.
400 int result = 0;
401 if (addr.ipaddr().family() == AF_INET) {
402 result = Bind(SocketAddress("0.0.0.0", 0));
403 } else if (addr.ipaddr().family() == AF_INET6) {
404 result = Bind(SocketAddress("::", 0));
405 }
406 if (result != 0) {
407 return result;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408 }
409 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000410 if (type_ == SOCK_DGRAM) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000411 remote_addr_ = addr;
412 state_ = CS_CONNECTED;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000413 } else {
414 int result = server_->Connect(this, addr, use_delay);
415 if (result != 0) {
416 error_ = EHOSTUNREACH;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000417 return -1;
418 }
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000419 state_ = CS_CONNECTING;
420 }
421 return 0;
422}
423
Niels Möllerc413c552021-06-22 10:03:14 +0200424void VirtualSocket::CompleteConnect(const SocketAddress& addr) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700425 RTC_DCHECK(CS_CONNECTING == state_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000426 remote_addr_ = addr;
427 state_ = CS_CONNECTED;
428 server_->AddConnection(remote_addr_, local_addr_, this);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000429}
430
431int VirtualSocket::SendUdp(const void* pv,
432 size_t cb,
433 const SocketAddress& addr) {
434 // If we have not been assigned a local port, then get one.
435 if (local_addr_.IsNil()) {
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200436 local_addr_ = server_->AssignBindAddress(
437 EmptySocketAddressWithFamily(addr.ipaddr().family()));
438 int result = server_->Bind(this, local_addr_);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000439 if (result != 0) {
440 local_addr_.Clear();
441 error_ = EADDRINUSE;
442 return result;
443 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444 }
445
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000446 // Send the data in a message to the appropriate socket.
447 return server_->SendUdp(this, static_cast<const char*>(pv), cb, addr);
448}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000450int VirtualSocket::SendTcp(const void* pv, size_t cb) {
Niels Möllerc79bd432021-02-16 09:25:52 +0100451 size_t capacity = server_->send_buffer_capacity() - send_buffer_.size();
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000452 if (0 == capacity) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700453 ready_to_send_ = false;
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000454 error_ = EWOULDBLOCK;
455 return -1;
456 }
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000457 size_t consumed = std::min(cb, capacity);
guoweis@webrtc.org0eb6eec2014-12-17 22:03:33 +0000458 const char* cpv = static_cast<const char*>(pv);
459 send_buffer_.insert(send_buffer_.end(), cpv, cpv + consumed);
460 server_->SendTcp(this);
461 return static_cast<int>(consumed);
462}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000463
Taylor Brandstettere7536412016-09-09 13:16:15 -0700464void VirtualSocket::OnSocketServerReadyToSend() {
465 if (ready_to_send_) {
466 // This socket didn't encounter EWOULDBLOCK, so there's nothing to do.
467 return;
468 }
469 if (type_ == SOCK_DGRAM) {
470 ready_to_send_ = true;
471 SignalWriteEvent(this);
472 } else {
473 RTC_DCHECK(type_ == SOCK_STREAM);
474 // This will attempt to empty the full send buffer, and will fire
475 // SignalWriteEvent if successful.
476 server_->SendTcp(this);
477 }
478}
479
Niels Möllerc79bd432021-02-16 09:25:52 +0100480void VirtualSocket::SetToBlocked() {
Niels Möllerc413c552021-06-22 10:03:14 +0200481 webrtc::MutexLock lock(&mutex_);
Niels Möllerc79bd432021-02-16 09:25:52 +0100482 ready_to_send_ = false;
483 error_ = EWOULDBLOCK;
484}
485
486void VirtualSocket::UpdateRecv(size_t data_size) {
487 recv_buffer_size_ += data_size;
488}
489
490void VirtualSocket::UpdateSend(size_t data_size) {
491 size_t new_buffer_size = send_buffer_.size() - data_size;
492 // Avoid undefined access beyond the last element of the vector.
493 // This only happens when new_buffer_size is 0.
494 if (data_size < send_buffer_.size()) {
495 // memmove is required for potentially overlapping source/destination.
496 memmove(&send_buffer_[0], &send_buffer_[data_size], new_buffer_size);
497 }
498 send_buffer_.resize(new_buffer_size);
499}
500
501void VirtualSocket::MaybeSignalWriteEvent(size_t capacity) {
502 if (!ready_to_send_ && (send_buffer_.size() < capacity)) {
503 ready_to_send_ = true;
504 SignalWriteEvent(this);
505 }
506}
507
508uint32_t VirtualSocket::AddPacket(int64_t cur_time, size_t packet_size) {
509 network_size_ += packet_size;
510 uint32_t send_delay =
511 server_->SendDelay(static_cast<uint32_t>(network_size_));
512
513 NetworkEntry entry;
514 entry.size = packet_size;
515 entry.done_time = cur_time + send_delay;
516 network_.push_back(entry);
517
518 return send_delay;
519}
520
521int64_t VirtualSocket::UpdateOrderedDelivery(int64_t ts) {
522 // Ensure that new packets arrive after previous ones
523 ts = std::max(ts, last_delivery_time_);
524 // A socket should not have both ordered and unordered delivery, so its last
525 // delivery time only needs to be updated when it has ordered delivery.
526 last_delivery_time_ = ts;
527 return ts;
528}
529
530size_t VirtualSocket::PurgeNetworkPackets(int64_t cur_time) {
Niels Möllerc413c552021-06-22 10:03:14 +0200531 webrtc::MutexLock lock(&mutex_);
Niels Möllerc79bd432021-02-16 09:25:52 +0100532
533 while (!network_.empty() && (network_.front().done_time <= cur_time)) {
534 RTC_DCHECK(network_size_ >= network_.front().size);
535 network_size_ -= network_.front().size;
536 network_.pop_front();
537 }
538 return network_size_;
539}
540
deadbeef22e08142017-06-12 14:30:28 -0700541VirtualSocketServer::VirtualSocketServer() : VirtualSocketServer(nullptr) {}
542
Sebastian Janssond624c392019-04-17 10:36:03 +0200543VirtualSocketServer::VirtualSocketServer(ThreadProcessingFakeClock* fake_clock)
deadbeef22e08142017-06-12 14:30:28 -0700544 : fake_clock_(fake_clock),
deadbeef37f5ecf2017-02-27 14:06:41 -0800545 msg_queue_(nullptr),
Honghai Zhang82d78622016-05-06 11:29:15 -0700546 stop_on_idle_(false),
Honghai Zhang82d78622016-05-06 11:29:15 -0700547 next_ipv4_(kInitialNextIPv4),
548 next_ipv6_(kInitialNextIPv6),
549 next_port_(kFirstEphemeralPort),
550 bindings_(new AddressMap()),
551 connections_(new ConnectionMap()),
552 bandwidth_(0),
553 network_capacity_(kDefaultNetworkCapacity),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554 send_buffer_capacity_(kDefaultTcpBufferSize),
555 recv_buffer_capacity_(kDefaultTcpBufferSize),
Honghai Zhang82d78622016-05-06 11:29:15 -0700556 delay_mean_(0),
557 delay_stddev_(0),
558 delay_samples_(NUM_SAMPLES),
Honghai Zhang82d78622016-05-06 11:29:15 -0700559 drop_prob_(0.0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000560 UpdateDelayDistribution();
561}
562
563VirtualSocketServer::~VirtualSocketServer() {
564 delete bindings_;
565 delete connections_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000566}
567
568IPAddress VirtualSocketServer::GetNextIP(int family) {
569 if (family == AF_INET) {
570 IPAddress next_ip(next_ipv4_);
Yves Gerey665174f2018-06-19 15:03:05 +0200571 next_ipv4_.s_addr = HostToNetwork32(NetworkToHost32(next_ipv4_.s_addr) + 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000572 return next_ip;
573 } else if (family == AF_INET6) {
574 IPAddress next_ip(next_ipv6_);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200575 uint32_t* as_ints = reinterpret_cast<uint32_t*>(&next_ipv6_.s6_addr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000576 as_ints[3] += 1;
577 return next_ip;
578 }
579 return IPAddress();
580}
581
Peter Boström0c4e06b2015-10-07 12:23:21 +0200582uint16_t VirtualSocketServer::GetNextPort() {
583 uint16_t port = next_port_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000584 if (next_port_ < kLastEphemeralPort) {
585 ++next_port_;
586 } else {
587 next_port_ = kFirstEphemeralPort;
588 }
589 return port;
590}
591
Taylor Brandstettere7536412016-09-09 13:16:15 -0700592void VirtualSocketServer::SetSendingBlocked(bool blocked) {
Florent Castellif94c0532021-11-16 13:29:53 +0100593 {
594 webrtc::MutexLock lock(&mutex_);
595 if (blocked == sending_blocked_) {
596 // Unchanged; nothing to do.
597 return;
598 }
599 sending_blocked_ = blocked;
Taylor Brandstettere7536412016-09-09 13:16:15 -0700600 }
Florent Castellif94c0532021-11-16 13:29:53 +0100601 if (!blocked) {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700602 // Sending was blocked, but is now unblocked. This signal gives sockets a
603 // chance to fire SignalWriteEvent, and for TCP, send buffered data.
604 SignalReadyToSend();
605 }
606}
607
Niels Möllerea423a52021-08-19 10:13:31 +0200608VirtualSocket* VirtualSocketServer::CreateSocket(int family, int type) {
609 return new VirtualSocket(this, family, type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000610}
611
Sebastian Jansson290de822020-01-09 14:20:23 +0100612void VirtualSocketServer::SetMessageQueue(Thread* msg_queue) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000613 msg_queue_ = msg_queue;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000614}
615
Markus Handell9a21c492022-08-25 11:40:13 +0000616bool VirtualSocketServer::Wait(webrtc::TimeDelta max_wait_duration,
617 bool process_io) {
Tommiccc9d972022-03-24 08:12:36 +0100618 RTC_DCHECK_RUN_ON(msg_queue_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000619 if (stop_on_idle_ && Thread::Current()->empty()) {
620 return false;
621 }
Artem Titov96e3b992021-07-26 16:03:14 +0200622 // Note: we don't need to do anything with `process_io` since we don't have
deadbeef98e186c2017-05-16 18:00:06 -0700623 // any real I/O. Received packets come in the form of queued messages, so
Sebastian Jansson290de822020-01-09 14:20:23 +0100624 // Thread will ensure WakeUp is called if another thread sends a
deadbeef98e186c2017-05-16 18:00:06 -0700625 // packet.
Markus Handell9a21c492022-08-25 11:40:13 +0000626 wakeup_.Wait(max_wait_duration);
deadbeef98e186c2017-05-16 18:00:06 -0700627 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000628}
629
630void VirtualSocketServer::WakeUp() {
deadbeef98e186c2017-05-16 18:00:06 -0700631 wakeup_.Set();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000632}
633
deadbeef5c3c1042017-08-04 15:01:57 -0700634void VirtualSocketServer::SetAlternativeLocalAddress(
635 const rtc::IPAddress& address,
636 const rtc::IPAddress& alternative) {
637 alternative_address_mapping_[address] = alternative;
638}
639
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000640bool VirtualSocketServer::ProcessMessagesUntilIdle() {
Tommiccc9d972022-03-24 08:12:36 +0100641 RTC_DCHECK_RUN_ON(msg_queue_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000642 stop_on_idle_ = true;
643 while (!msg_queue_->empty()) {
deadbeef22e08142017-06-12 14:30:28 -0700644 if (fake_clock_) {
645 // If using a fake clock, advance it in millisecond increments until the
Bjorn Mellem6eb03b82017-06-13 15:07:41 -0700646 // queue is empty.
Danil Chapovalov0c626af2020-02-10 11:16:00 +0100647 fake_clock_->AdvanceTime(webrtc::TimeDelta::Millis(1));
deadbeef22e08142017-06-12 14:30:28 -0700648 } else {
649 // Otherwise, run a normal message loop.
Danil Chapovalov207f8532022-08-24 12:19:46 +0200650 msg_queue_->ProcessMessages(Thread::kForever);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000651 }
652 }
653 stop_on_idle_ = false;
654 return !msg_queue_->IsQuitting();
655}
656
Peter Boström0c4e06b2015-10-07 12:23:21 +0200657void VirtualSocketServer::SetNextPortForTesting(uint16_t port) {
jiayl@webrtc.org22406fc2014-09-09 15:44:05 +0000658 next_port_ = port;
659}
660
Guo-wei Shiehbe508a12015-04-06 12:48:47 -0700661bool VirtualSocketServer::CloseTcpConnections(
662 const SocketAddress& addr_local,
663 const SocketAddress& addr_remote) {
664 VirtualSocket* socket = LookupConnection(addr_local, addr_remote);
665 if (!socket) {
666 return false;
667 }
668 // Signal the close event on the local connection first.
669 socket->SignalCloseEvent(socket, 0);
670
671 // Trigger the remote connection's close event.
672 socket->Close();
673
674 return true;
675}
676
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000677int VirtualSocketServer::Bind(VirtualSocket* socket,
678 const SocketAddress& addr) {
deadbeef37f5ecf2017-02-27 14:06:41 -0800679 RTC_DCHECK(nullptr != socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000680 // Address must be completely specified at this point
Taylor Brandstettere7536412016-09-09 13:16:15 -0700681 RTC_DCHECK(!IPIsUnspec(addr.ipaddr()));
682 RTC_DCHECK(addr.port() != 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000683
684 // Normalize the address (turns v6-mapped addresses into v4-addresses).
685 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
686
687 AddressMap::value_type entry(normalized, socket);
Niels Möllerd44532a2021-02-18 14:38:14 +0100688 return bindings_->insert(entry).second ? 0 : -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000689}
690
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200691SocketAddress VirtualSocketServer::AssignBindAddress(
692 const SocketAddress& app_addr) {
693 RTC_DCHECK(!IPIsUnspec(app_addr.ipaddr()));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000694
deadbeef5c3c1042017-08-04 15:01:57 -0700695 // Normalize the IP.
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200696 SocketAddress addr;
697 addr.SetIP(app_addr.ipaddr().Normalized());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000698
Artem Titov96e3b992021-07-26 16:03:14 +0200699 // If the IP appears in `alternative_address_mapping_`, meaning the test has
deadbeef5c3c1042017-08-04 15:01:57 -0700700 // configured sockets bound to this IP to actually use another IP, replace
701 // the IP here.
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200702 auto alternative = alternative_address_mapping_.find(addr.ipaddr());
deadbeef5c3c1042017-08-04 15:01:57 -0700703 if (alternative != alternative_address_mapping_.end()) {
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200704 addr.SetIP(alternative->second);
deadbeef5c3c1042017-08-04 15:01:57 -0700705 }
706
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200707 if (app_addr.port() != 0) {
708 addr.SetPort(app_addr.port());
709 } else {
710 // Assign a port.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000711 for (int i = 0; i < kEphemeralPortCount; ++i) {
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200712 addr.SetPort(GetNextPort());
713 if (bindings_->find(addr) == bindings_->end()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000714 break;
715 }
716 }
717 }
718
Niels Möllerc2d8f1e2021-08-24 15:49:34 +0200719 return addr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000720}
721
722VirtualSocket* VirtualSocketServer::LookupBinding(const SocketAddress& addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200723 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000724 AddressMap::iterator it = bindings_->find(normalized);
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700725 if (it != bindings_->end()) {
726 return it->second;
727 }
728
Niels Möller84d15952021-09-01 10:50:34 +0200729 IPAddress default_ip = GetDefaultSourceAddress(addr.ipaddr().family());
Guo-wei Shieh38f88932015-08-13 22:24:02 -0700730 if (!IPIsUnspec(default_ip) && addr.ipaddr() == default_ip) {
731 // If we can't find a binding for the packet which is sent to the interface
732 // corresponding to the default route, it should match a binding with the
733 // correct port to the any address.
734 SocketAddress sock_addr =
735 EmptySocketAddressWithFamily(addr.ipaddr().family());
736 sock_addr.SetPort(addr.port());
737 return LookupBinding(sock_addr);
738 }
739
740 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000741}
742
743int VirtualSocketServer::Unbind(const SocketAddress& addr,
744 VirtualSocket* socket) {
Yves Gerey665174f2018-06-19 15:03:05 +0200745 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
Taylor Brandstettere7536412016-09-09 13:16:15 -0700746 RTC_DCHECK((*bindings_)[normalized] == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000747 bindings_->erase(bindings_->find(normalized));
748 return 0;
749}
750
751void VirtualSocketServer::AddConnection(const SocketAddress& local,
752 const SocketAddress& remote,
753 VirtualSocket* remote_socket) {
754 // Add this socket pair to our routing table. This will allow
755 // multiple clients to connect to the same server address.
Yves Gerey665174f2018-06-19 15:03:05 +0200756 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
757 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000758 SocketAddressPair address_pair(local_normalized, remote_normalized);
Yves Gerey665174f2018-06-19 15:03:05 +0200759 connections_->insert(std::pair<SocketAddressPair, VirtualSocket*>(
760 address_pair, remote_socket));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000761}
762
763VirtualSocket* VirtualSocketServer::LookupConnection(
764 const SocketAddress& local,
765 const SocketAddress& remote) {
Yves Gerey665174f2018-06-19 15:03:05 +0200766 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
767 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000768 SocketAddressPair address_pair(local_normalized, remote_normalized);
769 ConnectionMap::iterator it = connections_->find(address_pair);
deadbeef37f5ecf2017-02-27 14:06:41 -0800770 return (connections_->end() != it) ? it->second : nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000771}
772
773void VirtualSocketServer::RemoveConnection(const SocketAddress& local,
774 const SocketAddress& remote) {
Yves Gerey665174f2018-06-19 15:03:05 +0200775 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
776 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000777 SocketAddressPair address_pair(local_normalized, remote_normalized);
778 connections_->erase(address_pair);
779}
780
781static double Random() {
782 return static_cast<double>(rand()) / RAND_MAX;
783}
784
785int VirtualSocketServer::Connect(VirtualSocket* socket,
786 const SocketAddress& remote_addr,
787 bool use_delay) {
Tommiccc9d972022-03-24 08:12:36 +0100788 RTC_DCHECK(msg_queue_);
789
Honghai Zhangc67e0f52016-09-19 16:57:37 -0700790 uint32_t delay = use_delay ? GetTransitDelay(socket) : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000791 VirtualSocket* remote = LookupBinding(remote_addr);
792 if (!CanInteractWith(socket, remote)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_INFO) << "Address family mismatch between "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200794 << socket->GetLocalAddress().ToString() << " and "
795 << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000796 return -1;
797 }
deadbeef37f5ecf2017-02-27 14:06:41 -0800798 if (remote != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000799 SocketAddress addr = socket->GetLocalAddress();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700800 msg_queue_->PostDelayed(RTC_FROM_HERE, delay, remote, MSG_ID_CONNECT,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000801 new MessageAddress(addr));
802 } else {
Jonas Olssonabbe8412018-04-03 13:40:05 +0200803 RTC_LOG(LS_INFO) << "No one listening at " << remote_addr.ToString();
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700804 msg_queue_->PostDelayed(RTC_FROM_HERE, delay, socket, MSG_ID_DISCONNECT);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000805 }
806 return 0;
807}
808
809bool VirtualSocketServer::Disconnect(VirtualSocket* socket) {
Tommiccc9d972022-03-24 08:12:36 +0100810 if (!socket || !msg_queue_)
811 return false;
812
813 // If we simulate packets being delayed, we should simulate the
814 // equivalent of a FIN being delayed as well.
815 uint32_t delay = GetTransitDelay(socket);
816 // Remove the mapping.
817 msg_queue_->PostDelayed(RTC_FROM_HERE, delay, socket, MSG_ID_DISCONNECT);
818 return true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000819}
820
Niels Möllerc79bd432021-02-16 09:25:52 +0100821bool VirtualSocketServer::Disconnect(const SocketAddress& addr) {
822 return Disconnect(LookupBinding(addr));
823}
824
825bool VirtualSocketServer::Disconnect(const SocketAddress& local_addr,
826 const SocketAddress& remote_addr) {
827 // Disconnect remote socket, check if it is a child of a server socket.
828 VirtualSocket* socket = LookupConnection(local_addr, remote_addr);
829 if (!socket) {
830 // Not a server socket child, then see if it is bound.
831 // TODO(tbd): If this is indeed a server socket that has no
832 // children this will cause the server socket to be
833 // closed. This might lead to unexpected results, how to fix this?
834 socket = LookupBinding(remote_addr);
835 }
836 Disconnect(socket);
837
838 // Remove mapping for both directions.
839 RemoveConnection(remote_addr, local_addr);
840 RemoveConnection(local_addr, remote_addr);
841 return socket != nullptr;
842}
843
844void VirtualSocketServer::CancelConnects(VirtualSocket* socket) {
845 MessageList msgs;
846 if (msg_queue_) {
847 msg_queue_->Clear(socket, MSG_ID_CONNECT, &msgs);
848 }
849 for (MessageList::iterator it = msgs.begin(); it != msgs.end(); ++it) {
850 RTC_DCHECK(nullptr != it->pdata);
851 MessageAddress* data = static_cast<MessageAddress*>(it->pdata);
852 SocketAddress local_addr = socket->GetLocalAddress();
853 // Lookup remote side.
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200854 VirtualSocket* lookup_socket = LookupConnection(local_addr, data->addr);
855 if (lookup_socket) {
Niels Möllerc79bd432021-02-16 09:25:52 +0100856 // Server socket, remote side is a socket retreived by
857 // accept. Accepted sockets are not bound so we will not
858 // find it by looking in the bindings table.
Mirko Bonadei54c90f22021-10-03 11:26:11 +0200859 Disconnect(lookup_socket);
Niels Möllerc79bd432021-02-16 09:25:52 +0100860 RemoveConnection(local_addr, data->addr);
861 } else {
862 Disconnect(data->addr);
863 }
864 delete data;
865 }
866}
867
868void VirtualSocketServer::Clear(VirtualSocket* socket) {
869 // Clear incoming packets and disconnect messages
870 if (msg_queue_) {
871 msg_queue_->Clear(socket);
872 }
873}
874
Niels Möllerc79bd432021-02-16 09:25:52 +0100875void VirtualSocketServer::PostSignalReadEvent(VirtualSocket* socket) {
Tommiccc9d972022-03-24 08:12:36 +0100876 if (!msg_queue_)
877 return;
878
Niels Möllerc79bd432021-02-16 09:25:52 +0100879 // Clear the message so it doesn't end up posted multiple times.
880 msg_queue_->Clear(socket, MSG_ID_SIGNALREADEVENT);
881 msg_queue_->Post(RTC_FROM_HERE, socket, MSG_ID_SIGNALREADEVENT);
882}
883
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884int VirtualSocketServer::SendUdp(VirtualSocket* socket,
Yves Gerey665174f2018-06-19 15:03:05 +0200885 const char* data,
886 size_t data_size,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000887 const SocketAddress& remote_addr) {
Florent Castellif94c0532021-11-16 13:29:53 +0100888 {
889 webrtc::MutexLock lock(&mutex_);
890 ++sent_packets_;
891 if (sending_blocked_) {
892 socket->SetToBlocked();
893 return -1;
Harald Alvestrand3d792e92021-03-10 07:29:28 +0000894 }
Harald Alvestrand3d792e92021-03-10 07:29:28 +0000895
Florent Castellif94c0532021-11-16 13:29:53 +0100896 // See if we want to drop this packet.
897 if (data_size > max_udp_payload_) {
898 RTC_LOG(LS_VERBOSE) << "Dropping too large UDP payload of size "
899 << data_size << ", UDP payload limit is "
900 << max_udp_payload_;
901 // Return as if send was successful; packet disappears.
902 return data_size;
903 }
Harald Alvestrand3d792e92021-03-10 07:29:28 +0000904
Florent Castellif94c0532021-11-16 13:29:53 +0100905 if (Random() < drop_prob_) {
906 RTC_LOG(LS_VERBOSE) << "Dropping packet: bad luck";
907 return static_cast<int>(data_size);
908 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909 }
910
911 VirtualSocket* recipient = LookupBinding(remote_addr);
912 if (!recipient) {
913 // Make a fake recipient for address family checking.
jbauch555604a2016-04-26 03:13:22 -0700914 std::unique_ptr<VirtualSocket> dummy_socket(
Niels Möllerea423a52021-08-19 10:13:31 +0200915 CreateSocket(AF_INET, SOCK_DGRAM));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000916 dummy_socket->SetLocalAddress(remote_addr);
917 if (!CanInteractWith(socket, dummy_socket.get())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100918 RTC_LOG(LS_VERBOSE) << "Incompatible address families: "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200919 << socket->GetLocalAddress().ToString() << " and "
920 << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000921 return -1;
922 }
Jonas Olssonabbe8412018-04-03 13:40:05 +0200923 RTC_LOG(LS_VERBOSE) << "No one listening at " << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000924 return static_cast<int>(data_size);
925 }
926
927 if (!CanInteractWith(socket, recipient)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100928 RTC_LOG(LS_VERBOSE) << "Incompatible address families: "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200929 << socket->GetLocalAddress().ToString() << " and "
930 << remote_addr.ToString();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000931 return -1;
932 }
933
Taylor Brandstettere7536412016-09-09 13:16:15 -0700934 {
Taylor Brandstettere7536412016-09-09 13:16:15 -0700935 int64_t cur_time = TimeMillis();
Niels Möllerc79bd432021-02-16 09:25:52 +0100936 size_t network_size = socket->PurgeNetworkPackets(cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000937
Taylor Brandstettere7536412016-09-09 13:16:15 -0700938 // Determine whether we have enough bandwidth to accept this packet. To do
939 // this, we need to update the send queue. Once we know it's current size,
940 // we know whether we can fit this packet.
941 //
942 // NOTE: There are better algorithms for maintaining such a queue (such as
943 // "Derivative Random Drop"); however, this algorithm is a more accurate
944 // simulation of what a normal network would do.
Florent Castellif94c0532021-11-16 13:29:53 +0100945 {
946 webrtc::MutexLock lock(&mutex_);
947 size_t packet_size = data_size + UDP_HEADER_SIZE;
948 if (network_size + packet_size > network_capacity_) {
949 RTC_LOG(LS_VERBOSE) << "Dropping packet: network capacity exceeded";
950 return static_cast<int>(data_size);
951 }
Taylor Brandstettere7536412016-09-09 13:16:15 -0700952 }
953
954 AddPacketToNetwork(socket, recipient, cur_time, data, data_size,
955 UDP_HEADER_SIZE, false);
956
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000957 return static_cast<int>(data_size);
958 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000959}
960
961void VirtualSocketServer::SendTcp(VirtualSocket* socket) {
Florent Castellif94c0532021-11-16 13:29:53 +0100962 {
963 webrtc::MutexLock lock(&mutex_);
964 ++sent_packets_;
965 if (sending_blocked_) {
966 // Eventually the socket's buffer will fill and VirtualSocket::SendTcp
967 // will set EWOULDBLOCK.
968 return;
969 }
Taylor Brandstettere7536412016-09-09 13:16:15 -0700970 }
971
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972 // TCP can't send more data than will fill up the receiver's buffer.
973 // We track the data that is in the buffer plus data in flight using the
974 // recipient's recv_buffer_size_. Anything beyond that must be stored in the
975 // sender's buffer. We will trigger the buffered data to be sent when data
976 // is read from the recv_buffer.
977
978 // Lookup the local/remote pair in the connections table.
Yves Gerey665174f2018-06-19 15:03:05 +0200979 VirtualSocket* recipient =
Niels Möllerc79bd432021-02-16 09:25:52 +0100980 LookupConnection(socket->GetLocalAddress(), socket->GetRemoteAddress());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000981 if (!recipient) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100982 RTC_LOG(LS_VERBOSE) << "Sending data to no one.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000983 return;
984 }
985
Honghai Zhang82d78622016-05-06 11:29:15 -0700986 int64_t cur_time = TimeMillis();
Niels Möllerc79bd432021-02-16 09:25:52 +0100987 socket->PurgeNetworkPackets(cur_time);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000988
989 while (true) {
Florent Castellif94c0532021-11-16 13:29:53 +0100990 size_t available = recv_buffer_capacity() - recipient->recv_buffer_size();
andresp@webrtc.orgff689be2015-02-12 11:54:26 +0000991 size_t max_data_size =
992 std::min<size_t>(available, TCP_MSS - TCP_HEADER_SIZE);
Niels Möllerc79bd432021-02-16 09:25:52 +0100993 size_t data_size = std::min(socket->send_buffer_size(), max_data_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000994 if (0 == data_size)
995 break;
996
Niels Möllerc79bd432021-02-16 09:25:52 +0100997 AddPacketToNetwork(socket, recipient, cur_time, socket->send_buffer_data(),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000998 data_size, TCP_HEADER_SIZE, true);
Niels Möllerc79bd432021-02-16 09:25:52 +0100999 recipient->UpdateRecv(data_size);
1000 socket->UpdateSend(data_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 }
1002
Florent Castellif94c0532021-11-16 13:29:53 +01001003 socket->MaybeSignalWriteEvent(send_buffer_capacity());
Niels Möllerc79bd432021-02-16 09:25:52 +01001004}
1005
1006void VirtualSocketServer::SendTcp(const SocketAddress& addr) {
1007 VirtualSocket* sender = LookupBinding(addr);
1008 RTC_DCHECK(nullptr != sender);
1009 SendTcp(sender);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001010}
1011
1012void VirtualSocketServer::AddPacketToNetwork(VirtualSocket* sender,
1013 VirtualSocket* recipient,
Honghai Zhang82d78622016-05-06 11:29:15 -07001014 int64_t cur_time,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001015 const char* data,
1016 size_t data_size,
1017 size_t header_size,
1018 bool ordered) {
Tommiccc9d972022-03-24 08:12:36 +01001019 RTC_DCHECK(msg_queue_);
Niels Möllerc79bd432021-02-16 09:25:52 +01001020 uint32_t send_delay = sender->AddPacket(cur_time, data_size + header_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001021
1022 // Find the delay for crossing the many virtual hops of the network.
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001023 uint32_t transit_delay = GetTransitDelay(sender);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001024
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001025 // When the incoming packet is from a binding of the any address, translate it
1026 // to the default route here such that the recipient will see the default
1027 // route.
Niels Möllerc79bd432021-02-16 09:25:52 +01001028 SocketAddress sender_addr = sender->GetLocalAddress();
Niels Möller84d15952021-09-01 10:50:34 +02001029 IPAddress default_ip = GetDefaultSourceAddress(sender_addr.ipaddr().family());
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001030 if (sender_addr.IsAnyIP() && !IPIsUnspec(default_ip)) {
1031 sender_addr.SetIP(default_ip);
1032 }
1033
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001034 // Post the packet as a message to be delivered (on our own thread)
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001035 Packet* p = new Packet(data, data_size, sender_addr);
1036
Honghai Zhang82d78622016-05-06 11:29:15 -07001037 int64_t ts = TimeAfter(send_delay + transit_delay);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001038 if (ordered) {
Niels Möllerc79bd432021-02-16 09:25:52 +01001039 ts = sender->UpdateOrderedDelivery(ts);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001040 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001041 msg_queue_->PostAt(RTC_FROM_HERE, ts, recipient, MSG_ID_PACKET, p);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001042}
1043
Peter Boström0c4e06b2015-10-07 12:23:21 +02001044uint32_t VirtualSocketServer::SendDelay(uint32_t size) {
Florent Castellif94c0532021-11-16 13:29:53 +01001045 webrtc::MutexLock lock(&mutex_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001046 if (bandwidth_ == 0)
1047 return 0;
1048 else
1049 return 1000 * size / bandwidth_;
1050}
1051
1052#if 0
1053void PrintFunction(std::vector<std::pair<double, double> >* f) {
1054 return;
1055 double sum = 0;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001056 for (uint32_t i = 0; i < f->size(); ++i) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001057 std::cout << (*f)[i].first << '\t' << (*f)[i].second << std::endl;
1058 sum += (*f)[i].second;
1059 }
1060 if (!f->empty()) {
1061 const double mean = sum / f->size();
1062 double sum_sq_dev = 0;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001063 for (uint32_t i = 0; i < f->size(); ++i) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001064 double dev = (*f)[i].second - mean;
1065 sum_sq_dev += dev * dev;
1066 }
1067 std::cout << "Mean = " << mean << " StdDev = "
1068 << sqrt(sum_sq_dev / f->size()) << std::endl;
1069 }
1070}
1071#endif // <unused>
1072
1073void VirtualSocketServer::UpdateDelayDistribution() {
Florent Castellif94c0532021-11-16 13:29:53 +01001074 webrtc::MutexLock lock(&mutex_);
Niels Möller983627c2021-02-09 15:12:28 +01001075 delay_dist_ = CreateDistribution(delay_mean_, delay_stddev_, delay_samples_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001076}
1077
1078static double PI = 4 * atan(1.0);
1079
1080static double Normal(double x, double mean, double stddev) {
1081 double a = (x - mean) * (x - mean) / (2 * stddev * stddev);
1082 return exp(-a) / (stddev * sqrt(2 * PI));
1083}
1084
1085#if 0 // static unused gives a warning
1086static double Pareto(double x, double min, double k) {
1087 if (x < min)
1088 return 0;
1089 else
1090 return k * std::pow(min, k) / std::pow(x, k+1);
1091}
1092#endif
1093
Niels Möller983627c2021-02-09 15:12:28 +01001094std::unique_ptr<VirtualSocketServer::Function>
1095VirtualSocketServer::CreateDistribution(uint32_t mean,
1096 uint32_t stddev,
1097 uint32_t samples) {
1098 auto f = std::make_unique<Function>();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001099
1100 if (0 == stddev) {
1101 f->push_back(Point(mean, 1.0));
1102 } else {
1103 double start = 0;
1104 if (mean >= 4 * static_cast<double>(stddev))
1105 start = mean - 4 * static_cast<double>(stddev);
1106 double end = mean + 4 * static_cast<double>(stddev);
1107
Peter Boström0c4e06b2015-10-07 12:23:21 +02001108 for (uint32_t i = 0; i < samples; i++) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001109 double x = start + (end - start) * i / (samples - 1);
1110 double y = Normal(x, mean, stddev);
1111 f->push_back(Point(x, y));
1112 }
1113 }
Niels Möller983627c2021-02-09 15:12:28 +01001114 return Resample(Invert(Accumulate(std::move(f))), 0, 1, samples);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001115}
1116
Honghai Zhangc67e0f52016-09-19 16:57:37 -07001117uint32_t VirtualSocketServer::GetTransitDelay(Socket* socket) {
1118 // Use the delay based on the address if it is set.
1119 auto iter = delay_by_ip_.find(socket->GetLocalAddress().ipaddr());
1120 if (iter != delay_by_ip_.end()) {
1121 return static_cast<uint32_t>(iter->second);
1122 }
1123 // Otherwise, use the delay from the distribution distribution.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124 size_t index = rand() % delay_dist_->size();
1125 double delay = (*delay_dist_)[index].second;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001126 // RTC_LOG_F(LS_INFO) << "random[" << index << "] = " << delay;
Peter Boström0c4e06b2015-10-07 12:23:21 +02001127 return static_cast<uint32_t>(delay);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001128}
1129
1130struct FunctionDomainCmp {
1131 bool operator()(const VirtualSocketServer::Point& p1,
Yves Gerey665174f2018-06-19 15:03:05 +02001132 const VirtualSocketServer::Point& p2) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133 return p1.first < p2.first;
1134 }
1135 bool operator()(double v1, const VirtualSocketServer::Point& p2) {
1136 return v1 < p2.first;
1137 }
1138 bool operator()(const VirtualSocketServer::Point& p1, double v2) {
1139 return p1.first < v2;
1140 }
1141};
1142
Niels Möller983627c2021-02-09 15:12:28 +01001143std::unique_ptr<VirtualSocketServer::Function> VirtualSocketServer::Accumulate(
1144 std::unique_ptr<Function> f) {
Taylor Brandstettere7536412016-09-09 13:16:15 -07001145 RTC_DCHECK(f->size() >= 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001146 double v = 0;
1147 for (Function::size_type i = 0; i < f->size() - 1; ++i) {
1148 double dx = (*f)[i + 1].first - (*f)[i].first;
1149 double avgy = ((*f)[i + 1].second + (*f)[i].second) / 2;
1150 (*f)[i].second = v;
1151 v = v + dx * avgy;
1152 }
Yves Gerey665174f2018-06-19 15:03:05 +02001153 (*f)[f->size() - 1].second = v;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001154 return f;
1155}
1156
Niels Möller983627c2021-02-09 15:12:28 +01001157std::unique_ptr<VirtualSocketServer::Function> VirtualSocketServer::Invert(
1158 std::unique_ptr<Function> f) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001159 for (Function::size_type i = 0; i < f->size(); ++i)
1160 std::swap((*f)[i].first, (*f)[i].second);
1161
Steve Anton2acd1632019-03-25 13:48:30 -07001162 absl::c_sort(*f, FunctionDomainCmp());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001163 return f;
1164}
1165
Niels Möller983627c2021-02-09 15:12:28 +01001166std::unique_ptr<VirtualSocketServer::Function> VirtualSocketServer::Resample(
1167 std::unique_ptr<Function> f,
1168 double x1,
1169 double x2,
1170 uint32_t samples) {
1171 auto g = std::make_unique<Function>();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001172
1173 for (size_t i = 0; i < samples; i++) {
1174 double x = x1 + (x2 - x1) * i / (samples - 1);
Niels Möller983627c2021-02-09 15:12:28 +01001175 double y = Evaluate(f.get(), x);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001176 g->push_back(Point(x, y));
1177 }
1178
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179 return g;
1180}
1181
Niels Möller983627c2021-02-09 15:12:28 +01001182double VirtualSocketServer::Evaluate(const Function* f, double x) {
1183 Function::const_iterator iter =
1184 absl::c_lower_bound(*f, x, FunctionDomainCmp());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001185 if (iter == f->begin()) {
1186 return (*f)[0].second;
1187 } else if (iter == f->end()) {
Taylor Brandstettere7536412016-09-09 13:16:15 -07001188 RTC_DCHECK(f->size() >= 1);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001189 return (*f)[f->size() - 1].second;
1190 } else if (iter->first == x) {
1191 return iter->second;
1192 } else {
1193 double x1 = (iter - 1)->first;
1194 double y1 = (iter - 1)->second;
1195 double x2 = iter->first;
1196 double y2 = iter->second;
1197 return y1 + (y2 - y1) * (x - x1) / (x2 - x1);
1198 }
1199}
1200
1201bool VirtualSocketServer::CanInteractWith(VirtualSocket* local,
1202 VirtualSocket* remote) {
1203 if (!local || !remote) {
1204 return false;
1205 }
1206 IPAddress local_ip = local->GetLocalAddress().ipaddr();
1207 IPAddress remote_ip = remote->GetLocalAddress().ipaddr();
1208 IPAddress local_normalized = local_ip.Normalized();
1209 IPAddress remote_normalized = remote_ip.Normalized();
1210 // Check if the addresses are the same family after Normalization (turns
1211 // mapped IPv6 address into IPv4 addresses).
1212 // This will stop unmapped V6 addresses from talking to mapped V6 addresses.
1213 if (local_normalized.family() == remote_normalized.family()) {
1214 return true;
1215 }
1216
1217 // If ip1 is IPv4 and ip2 is :: and ip2 is not IPV6_V6ONLY.
1218 int remote_v6_only = 0;
1219 remote->GetOption(Socket::OPT_IPV6_V6ONLY, &remote_v6_only);
1220 if (local_ip.family() == AF_INET && !remote_v6_only && IPIsAny(remote_ip)) {
1221 return true;
1222 }
1223 // Same check, backwards.
1224 int local_v6_only = 0;
1225 local->GetOption(Socket::OPT_IPV6_V6ONLY, &local_v6_only);
1226 if (remote_ip.family() == AF_INET && !local_v6_only && IPIsAny(local_ip)) {
1227 return true;
1228 }
1229
1230 // Check to see if either socket was explicitly bound to IPv6-any.
1231 // These sockets can talk with anyone.
1232 if (local_ip.family() == AF_INET6 && local->was_any()) {
1233 return true;
1234 }
1235 if (remote_ip.family() == AF_INET6 && remote->was_any()) {
1236 return true;
1237 }
1238
1239 return false;
1240}
1241
Niels Möller84d15952021-09-01 10:50:34 +02001242IPAddress VirtualSocketServer::GetDefaultSourceAddress(int family) {
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001243 if (family == AF_INET) {
Niels Möller84d15952021-09-01 10:50:34 +02001244 return default_source_address_v4_;
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001245 }
1246 if (family == AF_INET6) {
Niels Möller84d15952021-09-01 10:50:34 +02001247 return default_source_address_v6_;
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001248 }
1249 return IPAddress();
1250}
Niels Möller84d15952021-09-01 10:50:34 +02001251void VirtualSocketServer::SetDefaultSourceAddress(const IPAddress& from_addr) {
henrikg91d6ede2015-09-17 00:24:34 -07001252 RTC_DCHECK(!IPIsAny(from_addr));
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001253 if (from_addr.family() == AF_INET) {
Niels Möller84d15952021-09-01 10:50:34 +02001254 default_source_address_v4_ = from_addr;
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001255 } else if (from_addr.family() == AF_INET6) {
Niels Möller84d15952021-09-01 10:50:34 +02001256 default_source_address_v6_ = from_addr;
Guo-wei Shieh38f88932015-08-13 22:24:02 -07001257 }
1258}
1259
Florent Castellif94c0532021-11-16 13:29:53 +01001260void VirtualSocketServer::set_bandwidth(uint32_t bandwidth) {
1261 webrtc::MutexLock lock(&mutex_);
1262 bandwidth_ = bandwidth;
1263}
1264void VirtualSocketServer::set_network_capacity(uint32_t capacity) {
1265 webrtc::MutexLock lock(&mutex_);
1266 network_capacity_ = capacity;
1267}
1268
1269uint32_t VirtualSocketServer::send_buffer_capacity() const {
1270 webrtc::MutexLock lock(&mutex_);
1271 return send_buffer_capacity_;
1272}
1273void VirtualSocketServer::set_send_buffer_capacity(uint32_t capacity) {
1274 webrtc::MutexLock lock(&mutex_);
1275 send_buffer_capacity_ = capacity;
1276}
1277
1278uint32_t VirtualSocketServer::recv_buffer_capacity() const {
1279 webrtc::MutexLock lock(&mutex_);
1280 return recv_buffer_capacity_;
1281}
1282void VirtualSocketServer::set_recv_buffer_capacity(uint32_t capacity) {
1283 webrtc::MutexLock lock(&mutex_);
1284 recv_buffer_capacity_ = capacity;
1285}
1286
1287void VirtualSocketServer::set_delay_mean(uint32_t delay_mean) {
1288 webrtc::MutexLock lock(&mutex_);
1289 delay_mean_ = delay_mean;
1290}
1291void VirtualSocketServer::set_delay_stddev(uint32_t delay_stddev) {
1292 webrtc::MutexLock lock(&mutex_);
1293 delay_stddev_ = delay_stddev;
1294}
1295void VirtualSocketServer::set_delay_samples(uint32_t delay_samples) {
1296 webrtc::MutexLock lock(&mutex_);
1297 delay_samples_ = delay_samples;
1298}
1299
1300void VirtualSocketServer::set_drop_probability(double drop_prob) {
1301 RTC_DCHECK_GE(drop_prob, 0.0);
1302 RTC_DCHECK_LE(drop_prob, 1.0);
1303
1304 webrtc::MutexLock lock(&mutex_);
1305 drop_prob_ = drop_prob;
1306}
1307
1308void VirtualSocketServer::set_max_udp_payload(size_t payload_size) {
1309 webrtc::MutexLock lock(&mutex_);
1310 max_udp_payload_ = payload_size;
1311}
1312
1313uint32_t VirtualSocketServer::sent_packets() const {
1314 webrtc::MutexLock lock(&mutex_);
1315 return sent_packets_;
1316}
1317
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001318} // namespace rtc