1 /*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "rtc_base/virtual_socket_server.h"
12
13 #include <errno.h>
14 #include <math.h>
15
16 #include <map>
17 #include <memory>
18 #include <vector>
19
20 #include "absl/algorithm/container.h"
21 #include "api/units/time_delta.h"
22 #include "rtc_base/checks.h"
23 #include "rtc_base/event.h"
24 #include "rtc_base/fake_clock.h"
25 #include "rtc_base/logging.h"
26 #include "rtc_base/physical_socket_server.h"
27 #include "rtc_base/socket_address_pair.h"
28 #include "rtc_base/thread.h"
29 #include "rtc_base/time_utils.h"
30
31 namespace rtc {
32
33 using ::webrtc::MutexLock;
34 using ::webrtc::TaskQueueBase;
35 using ::webrtc::TimeDelta;
36
37 #if defined(WEBRTC_WIN)
38 const in_addr kInitialNextIPv4 = {{{0x01, 0, 0, 0}}};
39 #else
40 // This value is entirely arbitrary, hence the lack of concern about endianness.
41 const in_addr kInitialNextIPv4 = {0x01000000};
42 #endif
43 // Starts at ::2 so as to not cause confusion with ::1.
44 const in6_addr kInitialNextIPv6 = {
45 {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}}};
46
47 const uint16_t kFirstEphemeralPort = 49152;
48 const uint16_t kLastEphemeralPort = 65535;
49 const uint16_t kEphemeralPortCount =
50 kLastEphemeralPort - kFirstEphemeralPort + 1;
51 const uint32_t kDefaultNetworkCapacity = 64 * 1024;
52 const uint32_t kDefaultTcpBufferSize = 32 * 1024;
53
54 const uint32_t UDP_HEADER_SIZE = 28; // IP + UDP headers
55 const uint32_t TCP_HEADER_SIZE = 40; // IP + TCP headers
56 const uint32_t TCP_MSS = 1400; // Maximum segment size
57
58 // Note: The current algorithm doesn't work for sample sizes smaller than this.
59 const int NUM_SAMPLES = 1000;
60
61 // Packets are passed between sockets as messages. We copy the data just like
62 // the kernel does.
63 class Packet {
64 public:
Packet(const char * data,size_t size,const SocketAddress & from)65 Packet(const char* data, size_t size, const SocketAddress& from)
66 : size_(size), consumed_(0), from_(from) {
67 RTC_DCHECK(nullptr != data);
68 data_ = new char[size_];
69 memcpy(data_, data, size_);
70 }
71
~Packet()72 ~Packet() { delete[] data_; }
73
data() const74 const char* data() const { return data_ + consumed_; }
size() const75 size_t size() const { return size_ - consumed_; }
from() const76 const SocketAddress& from() const { return from_; }
77
78 // Remove the first size bytes from the data.
Consume(size_t size)79 void Consume(size_t size) {
80 RTC_DCHECK(size + consumed_ < size_);
81 consumed_ += size;
82 }
83
84 private:
85 char* data_;
86 size_t size_, consumed_;
87 SocketAddress from_;
88 };
89
VirtualSocket(VirtualSocketServer * server,int family,int type)90 VirtualSocket::VirtualSocket(VirtualSocketServer* server, int family, int type)
91 : server_(server),
92 type_(type),
93 state_(CS_CLOSED),
94 error_(0),
95 network_size_(0),
96 recv_buffer_size_(0),
97 bound_(false),
98 was_any_(false) {
99 RTC_DCHECK((type_ == SOCK_DGRAM) || (type_ == SOCK_STREAM));
100 server->SignalReadyToSend.connect(this,
101 &VirtualSocket::OnSocketServerReadyToSend);
102 }
103
~VirtualSocket()104 VirtualSocket::~VirtualSocket() {
105 Close();
106 }
107
GetLocalAddress() const108 SocketAddress VirtualSocket::GetLocalAddress() const {
109 return local_addr_;
110 }
111
GetRemoteAddress() const112 SocketAddress VirtualSocket::GetRemoteAddress() const {
113 return remote_addr_;
114 }
115
SetLocalAddress(const SocketAddress & addr)116 void VirtualSocket::SetLocalAddress(const SocketAddress& addr) {
117 local_addr_ = addr;
118 }
119
Bind(const SocketAddress & addr)120 int VirtualSocket::Bind(const SocketAddress& addr) {
121 if (!local_addr_.IsNil()) {
122 error_ = EINVAL;
123 return -1;
124 }
125 local_addr_ = server_->AssignBindAddress(addr);
126 int result = server_->Bind(this, local_addr_);
127 if (result != 0) {
128 local_addr_.Clear();
129 error_ = EADDRINUSE;
130 } else {
131 bound_ = true;
132 was_any_ = addr.IsAnyIP();
133 }
134 return result;
135 }
136
Connect(const SocketAddress & addr)137 int VirtualSocket::Connect(const SocketAddress& addr) {
138 return InitiateConnect(addr, true);
139 }
140
SafetyBlock(VirtualSocket * socket)141 VirtualSocket::SafetyBlock::SafetyBlock(VirtualSocket* socket)
142 : socket_(*socket) {}
143
~SafetyBlock()144 VirtualSocket::SafetyBlock::~SafetyBlock() {
145 // Ensure `SetNotAlive` was called and there is nothing left to cleanup.
146 RTC_DCHECK(!alive_);
147 RTC_DCHECK(posted_connects_.empty());
148 RTC_DCHECK(recv_buffer_.empty());
149 RTC_DCHECK(!listen_queue_.has_value());
150 }
151
SetNotAlive()152 void VirtualSocket::SafetyBlock::SetNotAlive() {
153 VirtualSocketServer* const server = socket_.server_;
154 const SocketAddress& local_addr = socket_.local_addr_;
155
156 MutexLock lock(&mutex_);
157 // Cancel pending sockets
158 if (listen_queue_.has_value()) {
159 for (const SocketAddress& remote_addr : *listen_queue_) {
160 server->Disconnect(remote_addr);
161 }
162 listen_queue_ = absl::nullopt;
163 }
164
165 // Cancel potential connects
166 for (const SocketAddress& remote_addr : posted_connects_) {
167 // Lookup remote side.
168 VirtualSocket* lookup_socket =
169 server->LookupConnection(local_addr, remote_addr);
170 if (lookup_socket) {
171 // Server socket, remote side is a socket retreived by accept. Accepted
172 // sockets are not bound so we will not find it by looking in the
173 // bindings table.
174 server->Disconnect(lookup_socket);
175 server->RemoveConnection(local_addr, remote_addr);
176 } else {
177 server->Disconnect(remote_addr);
178 }
179 }
180 posted_connects_.clear();
181
182 recv_buffer_.clear();
183
184 alive_ = false;
185 }
186
PostSignalReadEvent()187 void VirtualSocket::SafetyBlock::PostSignalReadEvent() {
188 if (pending_read_signal_event_) {
189 // Avoid posting multiple times.
190 return;
191 }
192
193 pending_read_signal_event_ = true;
194 rtc::scoped_refptr<SafetyBlock> safety(this);
195 socket_.server_->msg_queue_->PostTask(
196 [safety = std::move(safety)] { safety->MaybeSignalReadEvent(); });
197 }
198
MaybeSignalReadEvent()199 void VirtualSocket::SafetyBlock::MaybeSignalReadEvent() {
200 {
201 MutexLock lock(&mutex_);
202 pending_read_signal_event_ = false;
203 if (!alive_ || recv_buffer_.empty()) {
204 return;
205 }
206 }
207 socket_.SignalReadEvent(&socket_);
208 }
209
Close()210 int VirtualSocket::Close() {
211 if (!local_addr_.IsNil() && bound_) {
212 // Remove from the binding table.
213 server_->Unbind(local_addr_, this);
214 bound_ = false;
215 }
216
217 // Disconnect stream sockets
218 if (state_ == CS_CONNECTED && type_ == SOCK_STREAM) {
219 server_->Disconnect(local_addr_, remote_addr_);
220 }
221
222 safety_->SetNotAlive();
223
224 state_ = CS_CLOSED;
225 local_addr_.Clear();
226 remote_addr_.Clear();
227 return 0;
228 }
229
Send(const void * pv,size_t cb)230 int VirtualSocket::Send(const void* pv, size_t cb) {
231 if (CS_CONNECTED != state_) {
232 error_ = ENOTCONN;
233 return -1;
234 }
235 if (SOCK_DGRAM == type_) {
236 return SendUdp(pv, cb, remote_addr_);
237 } else {
238 return SendTcp(pv, cb);
239 }
240 }
241
SendTo(const void * pv,size_t cb,const SocketAddress & addr)242 int VirtualSocket::SendTo(const void* pv,
243 size_t cb,
244 const SocketAddress& addr) {
245 if (SOCK_DGRAM == type_) {
246 return SendUdp(pv, cb, addr);
247 } else {
248 if (CS_CONNECTED != state_) {
249 error_ = ENOTCONN;
250 return -1;
251 }
252 return SendTcp(pv, cb);
253 }
254 }
255
Recv(void * pv,size_t cb,int64_t * timestamp)256 int VirtualSocket::Recv(void* pv, size_t cb, int64_t* timestamp) {
257 SocketAddress addr;
258 return RecvFrom(pv, cb, &addr, timestamp);
259 }
260
RecvFrom(void * pv,size_t cb,SocketAddress * paddr,int64_t * timestamp)261 int VirtualSocket::RecvFrom(void* pv,
262 size_t cb,
263 SocketAddress* paddr,
264 int64_t* timestamp) {
265 if (timestamp) {
266 *timestamp = -1;
267 }
268
269 int data_read = safety_->RecvFrom(pv, cb, *paddr);
270 if (data_read < 0) {
271 error_ = EAGAIN;
272 return -1;
273 }
274
275 if (type_ == SOCK_STREAM) {
276 bool was_full = (recv_buffer_size_ == server_->recv_buffer_capacity());
277 recv_buffer_size_ -= data_read;
278 if (was_full) {
279 server_->SendTcp(remote_addr_);
280 }
281 }
282
283 return data_read;
284 }
285
RecvFrom(void * buffer,size_t size,SocketAddress & addr)286 int VirtualSocket::SafetyBlock::RecvFrom(void* buffer,
287 size_t size,
288 SocketAddress& addr) {
289 MutexLock lock(&mutex_);
290 // If we don't have a packet, then either error or wait for one to arrive.
291 if (recv_buffer_.empty()) {
292 return -1;
293 }
294
295 // Return the packet at the front of the queue.
296 Packet& packet = *recv_buffer_.front();
297 size_t data_read = std::min(size, packet.size());
298 memcpy(buffer, packet.data(), data_read);
299 addr = packet.from();
300
301 if (data_read < packet.size()) {
302 packet.Consume(data_read);
303 } else {
304 recv_buffer_.pop_front();
305 }
306
307 // To behave like a real socket, SignalReadEvent should fire if there's still
308 // data buffered.
309 if (!recv_buffer_.empty()) {
310 PostSignalReadEvent();
311 }
312
313 return data_read;
314 }
315
Listen(int backlog)316 int VirtualSocket::Listen(int backlog) {
317 RTC_DCHECK(SOCK_STREAM == type_);
318 RTC_DCHECK(CS_CLOSED == state_);
319 if (local_addr_.IsNil()) {
320 error_ = EINVAL;
321 return -1;
322 }
323 safety_->Listen();
324 state_ = CS_CONNECTING;
325 return 0;
326 }
327
Listen()328 void VirtualSocket::SafetyBlock::Listen() {
329 MutexLock lock(&mutex_);
330 RTC_DCHECK(!listen_queue_.has_value());
331 listen_queue_.emplace();
332 }
333
Accept(SocketAddress * paddr)334 VirtualSocket* VirtualSocket::Accept(SocketAddress* paddr) {
335 SafetyBlock::AcceptResult result = safety_->Accept();
336 if (result.error != 0) {
337 error_ = result.error;
338 return nullptr;
339 }
340 if (paddr) {
341 *paddr = result.remote_addr;
342 }
343 return result.socket.release();
344 }
345
Accept()346 VirtualSocket::SafetyBlock::AcceptResult VirtualSocket::SafetyBlock::Accept() {
347 AcceptResult result;
348 MutexLock lock(&mutex_);
349 RTC_DCHECK(alive_);
350 if (!listen_queue_.has_value()) {
351 result.error = EINVAL;
352 return result;
353 }
354 while (!listen_queue_->empty()) {
355 auto socket = std::make_unique<VirtualSocket>(socket_.server_, AF_INET,
356 socket_.type_);
357
358 // Set the new local address to the same as this server socket.
359 socket->SetLocalAddress(socket_.local_addr_);
360 // Sockets made from a socket that 'was Any' need to inherit that.
361 socket->set_was_any(socket_.was_any());
362 SocketAddress remote_addr = listen_queue_->front();
363 listen_queue_->pop_front();
364 if (socket->InitiateConnect(remote_addr, false) != 0) {
365 continue;
366 }
367 socket->CompleteConnect(remote_addr);
368 result.socket = std::move(socket);
369 result.remote_addr = remote_addr;
370 return result;
371 }
372 result.error = EWOULDBLOCK;
373 return result;
374 }
375
GetError() const376 int VirtualSocket::GetError() const {
377 return error_;
378 }
379
SetError(int error)380 void VirtualSocket::SetError(int error) {
381 error_ = error;
382 }
383
GetState() const384 Socket::ConnState VirtualSocket::GetState() const {
385 return state_;
386 }
387
GetOption(Option opt,int * value)388 int VirtualSocket::GetOption(Option opt, int* value) {
389 OptionsMap::const_iterator it = options_map_.find(opt);
390 if (it == options_map_.end()) {
391 return -1;
392 }
393 *value = it->second;
394 return 0; // 0 is success to emulate getsockopt()
395 }
396
SetOption(Option opt,int value)397 int VirtualSocket::SetOption(Option opt, int value) {
398 options_map_[opt] = value;
399 return 0; // 0 is success to emulate setsockopt()
400 }
401
PostPacket(TimeDelta delay,std::unique_ptr<Packet> packet)402 void VirtualSocket::PostPacket(TimeDelta delay,
403 std::unique_ptr<Packet> packet) {
404 rtc::scoped_refptr<SafetyBlock> safety = safety_;
405 VirtualSocket* socket = this;
406 server_->msg_queue_->PostDelayedTask(
407 [safety = std::move(safety), socket,
408 packet = std::move(packet)]() mutable {
409 if (safety->AddPacket(std::move(packet))) {
410 socket->SignalReadEvent(socket);
411 }
412 },
413 delay);
414 }
415
AddPacket(std::unique_ptr<Packet> packet)416 bool VirtualSocket::SafetyBlock::AddPacket(std::unique_ptr<Packet> packet) {
417 MutexLock lock(&mutex_);
418 if (alive_) {
419 recv_buffer_.push_back(std::move(packet));
420 }
421 return alive_;
422 }
423
PostConnect(TimeDelta delay,const SocketAddress & remote_addr)424 void VirtualSocket::PostConnect(TimeDelta delay,
425 const SocketAddress& remote_addr) {
426 safety_->PostConnect(delay, remote_addr);
427 }
428
PostConnect(TimeDelta delay,const SocketAddress & remote_addr)429 void VirtualSocket::SafetyBlock::PostConnect(TimeDelta delay,
430 const SocketAddress& remote_addr) {
431 rtc::scoped_refptr<SafetyBlock> safety(this);
432
433 MutexLock lock(&mutex_);
434 RTC_DCHECK(alive_);
435 // Save addresses of the pending connects to allow propertly disconnect them
436 // if socket closes before delayed task below runs.
437 // `posted_connects_` is an std::list, thus its iterators are valid while the
438 // element is in the list. It can be removed either in the `Connect` just
439 // below or by calling SetNotAlive function, thus inside `Connect` `it` should
440 // be valid when alive_ == true.
441 auto it = posted_connects_.insert(posted_connects_.end(), remote_addr);
442 auto task = [safety = std::move(safety), it] {
443 switch (safety->Connect(it)) {
444 case Signal::kNone:
445 break;
446 case Signal::kReadEvent:
447 safety->socket_.SignalReadEvent(&safety->socket_);
448 break;
449 case Signal::kConnectEvent:
450 safety->socket_.SignalConnectEvent(&safety->socket_);
451 break;
452 }
453 };
454 socket_.server_->msg_queue_->PostDelayedTask(std::move(task), delay);
455 }
456
Connect(VirtualSocket::SafetyBlock::PostedConnects::iterator remote_addr_it)457 VirtualSocket::SafetyBlock::Signal VirtualSocket::SafetyBlock::Connect(
458 VirtualSocket::SafetyBlock::PostedConnects::iterator remote_addr_it) {
459 MutexLock lock(&mutex_);
460 if (!alive_) {
461 return Signal::kNone;
462 }
463 RTC_DCHECK(!posted_connects_.empty());
464 SocketAddress remote_addr = *remote_addr_it;
465 posted_connects_.erase(remote_addr_it);
466
467 if (listen_queue_.has_value()) {
468 listen_queue_->push_back(remote_addr);
469 return Signal::kReadEvent;
470 }
471 if (socket_.type_ == SOCK_STREAM && socket_.state_ == CS_CONNECTING) {
472 socket_.CompleteConnect(remote_addr);
473 return Signal::kConnectEvent;
474 }
475 RTC_LOG(LS_VERBOSE) << "Socket at " << socket_.local_addr_.ToString()
476 << " is not listening";
477 socket_.server_->Disconnect(remote_addr);
478 return Signal::kNone;
479 }
480
IsAlive()481 bool VirtualSocket::SafetyBlock::IsAlive() {
482 MutexLock lock(&mutex_);
483 return alive_;
484 }
485
PostDisconnect(TimeDelta delay)486 void VirtualSocket::PostDisconnect(TimeDelta delay) {
487 // Posted task may outlive this. Use different name for `this` inside the task
488 // to avoid accidental unsafe `this->safety_` instead of safe `safety`
489 VirtualSocket* socket = this;
490 rtc::scoped_refptr<SafetyBlock> safety = safety_;
491 auto task = [safety = std::move(safety), socket] {
492 if (!safety->IsAlive()) {
493 return;
494 }
495 RTC_DCHECK_EQ(socket->type_, SOCK_STREAM);
496 if (socket->state_ == CS_CLOSED) {
497 return;
498 }
499 int error_to_signal = (socket->state_ == CS_CONNECTING) ? ECONNREFUSED : 0;
500 socket->state_ = CS_CLOSED;
501 socket->remote_addr_.Clear();
502 socket->SignalCloseEvent(socket, error_to_signal);
503 };
504 server_->msg_queue_->PostDelayedTask(std::move(task), delay);
505 }
506
InitiateConnect(const SocketAddress & addr,bool use_delay)507 int VirtualSocket::InitiateConnect(const SocketAddress& addr, bool use_delay) {
508 if (!remote_addr_.IsNil()) {
509 error_ = (CS_CONNECTED == state_) ? EISCONN : EINPROGRESS;
510 return -1;
511 }
512 if (local_addr_.IsNil()) {
513 // If there's no local address set, grab a random one in the correct AF.
514 int result = 0;
515 if (addr.ipaddr().family() == AF_INET) {
516 result = Bind(SocketAddress("0.0.0.0", 0));
517 } else if (addr.ipaddr().family() == AF_INET6) {
518 result = Bind(SocketAddress("::", 0));
519 }
520 if (result != 0) {
521 return result;
522 }
523 }
524 if (type_ == SOCK_DGRAM) {
525 remote_addr_ = addr;
526 state_ = CS_CONNECTED;
527 } else {
528 int result = server_->Connect(this, addr, use_delay);
529 if (result != 0) {
530 error_ = EHOSTUNREACH;
531 return -1;
532 }
533 state_ = CS_CONNECTING;
534 }
535 return 0;
536 }
537
CompleteConnect(const SocketAddress & addr)538 void VirtualSocket::CompleteConnect(const SocketAddress& addr) {
539 RTC_DCHECK(CS_CONNECTING == state_);
540 remote_addr_ = addr;
541 state_ = CS_CONNECTED;
542 server_->AddConnection(remote_addr_, local_addr_, this);
543 }
544
SendUdp(const void * pv,size_t cb,const SocketAddress & addr)545 int VirtualSocket::SendUdp(const void* pv,
546 size_t cb,
547 const SocketAddress& addr) {
548 // If we have not been assigned a local port, then get one.
549 if (local_addr_.IsNil()) {
550 local_addr_ = server_->AssignBindAddress(
551 EmptySocketAddressWithFamily(addr.ipaddr().family()));
552 int result = server_->Bind(this, local_addr_);
553 if (result != 0) {
554 local_addr_.Clear();
555 error_ = EADDRINUSE;
556 return result;
557 }
558 }
559
560 // Send the data in a message to the appropriate socket.
561 return server_->SendUdp(this, static_cast<const char*>(pv), cb, addr);
562 }
563
SendTcp(const void * pv,size_t cb)564 int VirtualSocket::SendTcp(const void* pv, size_t cb) {
565 size_t capacity = server_->send_buffer_capacity() - send_buffer_.size();
566 if (0 == capacity) {
567 ready_to_send_ = false;
568 error_ = EWOULDBLOCK;
569 return -1;
570 }
571 size_t consumed = std::min(cb, capacity);
572 const char* cpv = static_cast<const char*>(pv);
573 send_buffer_.insert(send_buffer_.end(), cpv, cpv + consumed);
574 server_->SendTcp(this);
575 return static_cast<int>(consumed);
576 }
577
OnSocketServerReadyToSend()578 void VirtualSocket::OnSocketServerReadyToSend() {
579 if (ready_to_send_) {
580 // This socket didn't encounter EWOULDBLOCK, so there's nothing to do.
581 return;
582 }
583 if (type_ == SOCK_DGRAM) {
584 ready_to_send_ = true;
585 SignalWriteEvent(this);
586 } else {
587 RTC_DCHECK(type_ == SOCK_STREAM);
588 // This will attempt to empty the full send buffer, and will fire
589 // SignalWriteEvent if successful.
590 server_->SendTcp(this);
591 }
592 }
593
SetToBlocked()594 void VirtualSocket::SetToBlocked() {
595 ready_to_send_ = false;
596 error_ = EWOULDBLOCK;
597 }
598
UpdateRecv(size_t data_size)599 void VirtualSocket::UpdateRecv(size_t data_size) {
600 recv_buffer_size_ += data_size;
601 }
602
UpdateSend(size_t data_size)603 void VirtualSocket::UpdateSend(size_t data_size) {
604 size_t new_buffer_size = send_buffer_.size() - data_size;
605 // Avoid undefined access beyond the last element of the vector.
606 // This only happens when new_buffer_size is 0.
607 if (data_size < send_buffer_.size()) {
608 // memmove is required for potentially overlapping source/destination.
609 memmove(&send_buffer_[0], &send_buffer_[data_size], new_buffer_size);
610 }
611 send_buffer_.resize(new_buffer_size);
612 }
613
MaybeSignalWriteEvent(size_t capacity)614 void VirtualSocket::MaybeSignalWriteEvent(size_t capacity) {
615 if (!ready_to_send_ && (send_buffer_.size() < capacity)) {
616 ready_to_send_ = true;
617 SignalWriteEvent(this);
618 }
619 }
620
AddPacket(int64_t cur_time,size_t packet_size)621 uint32_t VirtualSocket::AddPacket(int64_t cur_time, size_t packet_size) {
622 network_size_ += packet_size;
623 uint32_t send_delay =
624 server_->SendDelay(static_cast<uint32_t>(network_size_));
625
626 NetworkEntry entry;
627 entry.size = packet_size;
628 entry.done_time = cur_time + send_delay;
629 network_.push_back(entry);
630
631 return send_delay;
632 }
633
UpdateOrderedDelivery(int64_t ts)634 int64_t VirtualSocket::UpdateOrderedDelivery(int64_t ts) {
635 // Ensure that new packets arrive after previous ones
636 ts = std::max(ts, last_delivery_time_);
637 // A socket should not have both ordered and unordered delivery, so its last
638 // delivery time only needs to be updated when it has ordered delivery.
639 last_delivery_time_ = ts;
640 return ts;
641 }
642
PurgeNetworkPackets(int64_t cur_time)643 size_t VirtualSocket::PurgeNetworkPackets(int64_t cur_time) {
644 while (!network_.empty() && (network_.front().done_time <= cur_time)) {
645 RTC_DCHECK(network_size_ >= network_.front().size);
646 network_size_ -= network_.front().size;
647 network_.pop_front();
648 }
649 return network_size_;
650 }
651
VirtualSocketServer()652 VirtualSocketServer::VirtualSocketServer() : VirtualSocketServer(nullptr) {}
653
VirtualSocketServer(ThreadProcessingFakeClock * fake_clock)654 VirtualSocketServer::VirtualSocketServer(ThreadProcessingFakeClock* fake_clock)
655 : fake_clock_(fake_clock),
656 msg_queue_(nullptr),
657 stop_on_idle_(false),
658 next_ipv4_(kInitialNextIPv4),
659 next_ipv6_(kInitialNextIPv6),
660 next_port_(kFirstEphemeralPort),
661 bindings_(new AddressMap()),
662 connections_(new ConnectionMap()),
663 bandwidth_(0),
664 network_capacity_(kDefaultNetworkCapacity),
665 send_buffer_capacity_(kDefaultTcpBufferSize),
666 recv_buffer_capacity_(kDefaultTcpBufferSize),
667 delay_mean_(0),
668 delay_stddev_(0),
669 delay_samples_(NUM_SAMPLES),
670 drop_prob_(0.0) {
671 UpdateDelayDistribution();
672 }
673
~VirtualSocketServer()674 VirtualSocketServer::~VirtualSocketServer() {
675 delete bindings_;
676 delete connections_;
677 }
678
GetNextIP(int family)679 IPAddress VirtualSocketServer::GetNextIP(int family) {
680 if (family == AF_INET) {
681 IPAddress next_ip(next_ipv4_);
682 next_ipv4_.s_addr = HostToNetwork32(NetworkToHost32(next_ipv4_.s_addr) + 1);
683 return next_ip;
684 } else if (family == AF_INET6) {
685 IPAddress next_ip(next_ipv6_);
686 uint32_t* as_ints = reinterpret_cast<uint32_t*>(&next_ipv6_.s6_addr);
687 as_ints[3] += 1;
688 return next_ip;
689 }
690 return IPAddress();
691 }
692
GetNextPort()693 uint16_t VirtualSocketServer::GetNextPort() {
694 uint16_t port = next_port_;
695 if (next_port_ < kLastEphemeralPort) {
696 ++next_port_;
697 } else {
698 next_port_ = kFirstEphemeralPort;
699 }
700 return port;
701 }
702
SetSendingBlocked(bool blocked)703 void VirtualSocketServer::SetSendingBlocked(bool blocked) {
704 {
705 webrtc::MutexLock lock(&mutex_);
706 if (blocked == sending_blocked_) {
707 // Unchanged; nothing to do.
708 return;
709 }
710 sending_blocked_ = blocked;
711 }
712 if (!blocked) {
713 // Sending was blocked, but is now unblocked. This signal gives sockets a
714 // chance to fire SignalWriteEvent, and for TCP, send buffered data.
715 SignalReadyToSend();
716 }
717 }
718
CreateSocket(int family,int type)719 VirtualSocket* VirtualSocketServer::CreateSocket(int family, int type) {
720 return new VirtualSocket(this, family, type);
721 }
722
SetMessageQueue(Thread * msg_queue)723 void VirtualSocketServer::SetMessageQueue(Thread* msg_queue) {
724 msg_queue_ = msg_queue;
725 }
726
Wait(webrtc::TimeDelta max_wait_duration,bool process_io)727 bool VirtualSocketServer::Wait(webrtc::TimeDelta max_wait_duration,
728 bool process_io) {
729 RTC_DCHECK_RUN_ON(msg_queue_);
730 if (stop_on_idle_ && Thread::Current()->empty()) {
731 return false;
732 }
733 // Note: we don't need to do anything with `process_io` since we don't have
734 // any real I/O. Received packets come in the form of queued messages, so
735 // Thread will ensure WakeUp is called if another thread sends a
736 // packet.
737 wakeup_.Wait(max_wait_duration);
738 return true;
739 }
740
WakeUp()741 void VirtualSocketServer::WakeUp() {
742 wakeup_.Set();
743 }
744
SetAlternativeLocalAddress(const rtc::IPAddress & address,const rtc::IPAddress & alternative)745 void VirtualSocketServer::SetAlternativeLocalAddress(
746 const rtc::IPAddress& address,
747 const rtc::IPAddress& alternative) {
748 alternative_address_mapping_[address] = alternative;
749 }
750
ProcessMessagesUntilIdle()751 bool VirtualSocketServer::ProcessMessagesUntilIdle() {
752 RTC_DCHECK_RUN_ON(msg_queue_);
753 stop_on_idle_ = true;
754 while (!msg_queue_->empty()) {
755 if (fake_clock_) {
756 // If using a fake clock, advance it in millisecond increments until the
757 // queue is empty.
758 fake_clock_->AdvanceTime(webrtc::TimeDelta::Millis(1));
759 } else {
760 // Otherwise, run a normal message loop.
761 msg_queue_->ProcessMessages(Thread::kForever);
762 }
763 }
764 stop_on_idle_ = false;
765 return !msg_queue_->IsQuitting();
766 }
767
SetNextPortForTesting(uint16_t port)768 void VirtualSocketServer::SetNextPortForTesting(uint16_t port) {
769 next_port_ = port;
770 }
771
CloseTcpConnections(const SocketAddress & addr_local,const SocketAddress & addr_remote)772 bool VirtualSocketServer::CloseTcpConnections(
773 const SocketAddress& addr_local,
774 const SocketAddress& addr_remote) {
775 VirtualSocket* socket = LookupConnection(addr_local, addr_remote);
776 if (!socket) {
777 return false;
778 }
779 // Signal the close event on the local connection first.
780 socket->SignalCloseEvent(socket, 0);
781
782 // Trigger the remote connection's close event.
783 socket->Close();
784
785 return true;
786 }
787
Bind(VirtualSocket * socket,const SocketAddress & addr)788 int VirtualSocketServer::Bind(VirtualSocket* socket,
789 const SocketAddress& addr) {
790 RTC_DCHECK(nullptr != socket);
791 // Address must be completely specified at this point
792 RTC_DCHECK(!IPIsUnspec(addr.ipaddr()));
793 RTC_DCHECK(addr.port() != 0);
794
795 // Normalize the address (turns v6-mapped addresses into v4-addresses).
796 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
797
798 AddressMap::value_type entry(normalized, socket);
799 return bindings_->insert(entry).second ? 0 : -1;
800 }
801
AssignBindAddress(const SocketAddress & app_addr)802 SocketAddress VirtualSocketServer::AssignBindAddress(
803 const SocketAddress& app_addr) {
804 RTC_DCHECK(!IPIsUnspec(app_addr.ipaddr()));
805
806 // Normalize the IP.
807 SocketAddress addr;
808 addr.SetIP(app_addr.ipaddr().Normalized());
809
810 // If the IP appears in `alternative_address_mapping_`, meaning the test has
811 // configured sockets bound to this IP to actually use another IP, replace
812 // the IP here.
813 auto alternative = alternative_address_mapping_.find(addr.ipaddr());
814 if (alternative != alternative_address_mapping_.end()) {
815 addr.SetIP(alternative->second);
816 }
817
818 if (app_addr.port() != 0) {
819 addr.SetPort(app_addr.port());
820 } else {
821 // Assign a port.
822 for (int i = 0; i < kEphemeralPortCount; ++i) {
823 addr.SetPort(GetNextPort());
824 if (bindings_->find(addr) == bindings_->end()) {
825 break;
826 }
827 }
828 }
829
830 return addr;
831 }
832
LookupBinding(const SocketAddress & addr)833 VirtualSocket* VirtualSocketServer::LookupBinding(const SocketAddress& addr) {
834 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
835 AddressMap::iterator it = bindings_->find(normalized);
836 if (it != bindings_->end()) {
837 return it->second;
838 }
839
840 IPAddress default_ip = GetDefaultSourceAddress(addr.ipaddr().family());
841 if (!IPIsUnspec(default_ip) && addr.ipaddr() == default_ip) {
842 // If we can't find a binding for the packet which is sent to the interface
843 // corresponding to the default route, it should match a binding with the
844 // correct port to the any address.
845 SocketAddress sock_addr =
846 EmptySocketAddressWithFamily(addr.ipaddr().family());
847 sock_addr.SetPort(addr.port());
848 return LookupBinding(sock_addr);
849 }
850
851 return nullptr;
852 }
853
Unbind(const SocketAddress & addr,VirtualSocket * socket)854 int VirtualSocketServer::Unbind(const SocketAddress& addr,
855 VirtualSocket* socket) {
856 SocketAddress normalized(addr.ipaddr().Normalized(), addr.port());
857 RTC_DCHECK((*bindings_)[normalized] == socket);
858 bindings_->erase(bindings_->find(normalized));
859 return 0;
860 }
861
AddConnection(const SocketAddress & local,const SocketAddress & remote,VirtualSocket * remote_socket)862 void VirtualSocketServer::AddConnection(const SocketAddress& local,
863 const SocketAddress& remote,
864 VirtualSocket* remote_socket) {
865 // Add this socket pair to our routing table. This will allow
866 // multiple clients to connect to the same server address.
867 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
868 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
869 SocketAddressPair address_pair(local_normalized, remote_normalized);
870 connections_->insert(std::pair<SocketAddressPair, VirtualSocket*>(
871 address_pair, remote_socket));
872 }
873
LookupConnection(const SocketAddress & local,const SocketAddress & remote)874 VirtualSocket* VirtualSocketServer::LookupConnection(
875 const SocketAddress& local,
876 const SocketAddress& remote) {
877 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
878 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
879 SocketAddressPair address_pair(local_normalized, remote_normalized);
880 ConnectionMap::iterator it = connections_->find(address_pair);
881 return (connections_->end() != it) ? it->second : nullptr;
882 }
883
RemoveConnection(const SocketAddress & local,const SocketAddress & remote)884 void VirtualSocketServer::RemoveConnection(const SocketAddress& local,
885 const SocketAddress& remote) {
886 SocketAddress local_normalized(local.ipaddr().Normalized(), local.port());
887 SocketAddress remote_normalized(remote.ipaddr().Normalized(), remote.port());
888 SocketAddressPair address_pair(local_normalized, remote_normalized);
889 connections_->erase(address_pair);
890 }
891
Random()892 static double Random() {
893 return static_cast<double>(rand()) / RAND_MAX;
894 }
895
Connect(VirtualSocket * socket,const SocketAddress & remote_addr,bool use_delay)896 int VirtualSocketServer::Connect(VirtualSocket* socket,
897 const SocketAddress& remote_addr,
898 bool use_delay) {
899 RTC_DCHECK(msg_queue_);
900
901 TimeDelta delay = TimeDelta::Millis(use_delay ? GetTransitDelay(socket) : 0);
902 VirtualSocket* remote = LookupBinding(remote_addr);
903 if (!CanInteractWith(socket, remote)) {
904 RTC_LOG(LS_INFO) << "Address family mismatch between "
905 << socket->GetLocalAddress().ToString() << " and "
906 << remote_addr.ToString();
907 return -1;
908 }
909 if (remote != nullptr) {
910 remote->PostConnect(delay, socket->GetLocalAddress());
911 } else {
912 RTC_LOG(LS_INFO) << "No one listening at " << remote_addr.ToString();
913 socket->PostDisconnect(delay);
914 }
915 return 0;
916 }
917
Disconnect(VirtualSocket * socket)918 bool VirtualSocketServer::Disconnect(VirtualSocket* socket) {
919 if (!socket || !msg_queue_)
920 return false;
921
922 // If we simulate packets being delayed, we should simulate the
923 // equivalent of a FIN being delayed as well.
924 socket->PostDisconnect(TimeDelta::Millis(GetTransitDelay(socket)));
925 return true;
926 }
927
Disconnect(const SocketAddress & addr)928 bool VirtualSocketServer::Disconnect(const SocketAddress& addr) {
929 return Disconnect(LookupBinding(addr));
930 }
931
Disconnect(const SocketAddress & local_addr,const SocketAddress & remote_addr)932 bool VirtualSocketServer::Disconnect(const SocketAddress& local_addr,
933 const SocketAddress& remote_addr) {
934 // Disconnect remote socket, check if it is a child of a server socket.
935 VirtualSocket* socket = LookupConnection(local_addr, remote_addr);
936 if (!socket) {
937 // Not a server socket child, then see if it is bound.
938 // TODO(tbd): If this is indeed a server socket that has no
939 // children this will cause the server socket to be
940 // closed. This might lead to unexpected results, how to fix this?
941 socket = LookupBinding(remote_addr);
942 }
943 Disconnect(socket);
944
945 // Remove mapping for both directions.
946 RemoveConnection(remote_addr, local_addr);
947 RemoveConnection(local_addr, remote_addr);
948 return socket != nullptr;
949 }
950
SendUdp(VirtualSocket * socket,const char * data,size_t data_size,const SocketAddress & remote_addr)951 int VirtualSocketServer::SendUdp(VirtualSocket* socket,
952 const char* data,
953 size_t data_size,
954 const SocketAddress& remote_addr) {
955 {
956 webrtc::MutexLock lock(&mutex_);
957 ++sent_packets_;
958 if (sending_blocked_) {
959 socket->SetToBlocked();
960 return -1;
961 }
962
963 // See if we want to drop this packet.
964 if (data_size > max_udp_payload_) {
965 RTC_LOG(LS_VERBOSE) << "Dropping too large UDP payload of size "
966 << data_size << ", UDP payload limit is "
967 << max_udp_payload_;
968 // Return as if send was successful; packet disappears.
969 return data_size;
970 }
971
972 if (Random() < drop_prob_) {
973 RTC_LOG(LS_VERBOSE) << "Dropping packet: bad luck";
974 return static_cast<int>(data_size);
975 }
976 }
977
978 VirtualSocket* recipient = LookupBinding(remote_addr);
979 if (!recipient) {
980 // Make a fake recipient for address family checking.
981 std::unique_ptr<VirtualSocket> dummy_socket(
982 CreateSocket(AF_INET, SOCK_DGRAM));
983 dummy_socket->SetLocalAddress(remote_addr);
984 if (!CanInteractWith(socket, dummy_socket.get())) {
985 RTC_LOG(LS_VERBOSE) << "Incompatible address families: "
986 << socket->GetLocalAddress().ToString() << " and "
987 << remote_addr.ToString();
988 return -1;
989 }
990 RTC_LOG(LS_VERBOSE) << "No one listening at " << remote_addr.ToString();
991 return static_cast<int>(data_size);
992 }
993
994 if (!CanInteractWith(socket, recipient)) {
995 RTC_LOG(LS_VERBOSE) << "Incompatible address families: "
996 << socket->GetLocalAddress().ToString() << " and "
997 << remote_addr.ToString();
998 return -1;
999 }
1000
1001 {
1002 int64_t cur_time = TimeMillis();
1003 size_t network_size = socket->PurgeNetworkPackets(cur_time);
1004
1005 // Determine whether we have enough bandwidth to accept this packet. To do
1006 // this, we need to update the send queue. Once we know it's current size,
1007 // we know whether we can fit this packet.
1008 //
1009 // NOTE: There are better algorithms for maintaining such a queue (such as
1010 // "Derivative Random Drop"); however, this algorithm is a more accurate
1011 // simulation of what a normal network would do.
1012 {
1013 webrtc::MutexLock lock(&mutex_);
1014 size_t packet_size = data_size + UDP_HEADER_SIZE;
1015 if (network_size + packet_size > network_capacity_) {
1016 RTC_LOG(LS_VERBOSE) << "Dropping packet: network capacity exceeded";
1017 return static_cast<int>(data_size);
1018 }
1019 }
1020
1021 AddPacketToNetwork(socket, recipient, cur_time, data, data_size,
1022 UDP_HEADER_SIZE, false);
1023
1024 return static_cast<int>(data_size);
1025 }
1026 }
1027
SendTcp(VirtualSocket * socket)1028 void VirtualSocketServer::SendTcp(VirtualSocket* socket) {
1029 {
1030 webrtc::MutexLock lock(&mutex_);
1031 ++sent_packets_;
1032 if (sending_blocked_) {
1033 // Eventually the socket's buffer will fill and VirtualSocket::SendTcp
1034 // will set EWOULDBLOCK.
1035 return;
1036 }
1037 }
1038
1039 // TCP can't send more data than will fill up the receiver's buffer.
1040 // We track the data that is in the buffer plus data in flight using the
1041 // recipient's recv_buffer_size_. Anything beyond that must be stored in the
1042 // sender's buffer. We will trigger the buffered data to be sent when data
1043 // is read from the recv_buffer.
1044
1045 // Lookup the local/remote pair in the connections table.
1046 VirtualSocket* recipient =
1047 LookupConnection(socket->GetLocalAddress(), socket->GetRemoteAddress());
1048 if (!recipient) {
1049 RTC_LOG(LS_VERBOSE) << "Sending data to no one.";
1050 return;
1051 }
1052
1053 int64_t cur_time = TimeMillis();
1054 socket->PurgeNetworkPackets(cur_time);
1055
1056 while (true) {
1057 size_t available = recv_buffer_capacity() - recipient->recv_buffer_size();
1058 size_t max_data_size =
1059 std::min<size_t>(available, TCP_MSS - TCP_HEADER_SIZE);
1060 size_t data_size = std::min(socket->send_buffer_size(), max_data_size);
1061 if (0 == data_size)
1062 break;
1063
1064 AddPacketToNetwork(socket, recipient, cur_time, socket->send_buffer_data(),
1065 data_size, TCP_HEADER_SIZE, true);
1066 recipient->UpdateRecv(data_size);
1067 socket->UpdateSend(data_size);
1068 }
1069
1070 socket->MaybeSignalWriteEvent(send_buffer_capacity());
1071 }
1072
SendTcp(const SocketAddress & addr)1073 void VirtualSocketServer::SendTcp(const SocketAddress& addr) {
1074 VirtualSocket* sender = LookupBinding(addr);
1075 RTC_DCHECK(nullptr != sender);
1076 SendTcp(sender);
1077 }
1078
AddPacketToNetwork(VirtualSocket * sender,VirtualSocket * recipient,int64_t cur_time,const char * data,size_t data_size,size_t header_size,bool ordered)1079 void VirtualSocketServer::AddPacketToNetwork(VirtualSocket* sender,
1080 VirtualSocket* recipient,
1081 int64_t cur_time,
1082 const char* data,
1083 size_t data_size,
1084 size_t header_size,
1085 bool ordered) {
1086 RTC_DCHECK(msg_queue_);
1087 uint32_t send_delay = sender->AddPacket(cur_time, data_size + header_size);
1088
1089 // Find the delay for crossing the many virtual hops of the network.
1090 uint32_t transit_delay = GetTransitDelay(sender);
1091
1092 // When the incoming packet is from a binding of the any address, translate it
1093 // to the default route here such that the recipient will see the default
1094 // route.
1095 SocketAddress sender_addr = sender->GetLocalAddress();
1096 IPAddress default_ip = GetDefaultSourceAddress(sender_addr.ipaddr().family());
1097 if (sender_addr.IsAnyIP() && !IPIsUnspec(default_ip)) {
1098 sender_addr.SetIP(default_ip);
1099 }
1100
1101 int64_t ts = cur_time + send_delay + transit_delay;
1102 if (ordered) {
1103 ts = sender->UpdateOrderedDelivery(ts);
1104 }
1105 recipient->PostPacket(TimeDelta::Millis(ts - cur_time),
1106 std::make_unique<Packet>(data, data_size, sender_addr));
1107 }
1108
SendDelay(uint32_t size)1109 uint32_t VirtualSocketServer::SendDelay(uint32_t size) {
1110 webrtc::MutexLock lock(&mutex_);
1111 if (bandwidth_ == 0)
1112 return 0;
1113 else
1114 return 1000 * size / bandwidth_;
1115 }
1116
1117 #if 0
1118 void PrintFunction(std::vector<std::pair<double, double> >* f) {
1119 return;
1120 double sum = 0;
1121 for (uint32_t i = 0; i < f->size(); ++i) {
1122 std::cout << (*f)[i].first << '\t' << (*f)[i].second << std::endl;
1123 sum += (*f)[i].second;
1124 }
1125 if (!f->empty()) {
1126 const double mean = sum / f->size();
1127 double sum_sq_dev = 0;
1128 for (uint32_t i = 0; i < f->size(); ++i) {
1129 double dev = (*f)[i].second - mean;
1130 sum_sq_dev += dev * dev;
1131 }
1132 std::cout << "Mean = " << mean << " StdDev = "
1133 << sqrt(sum_sq_dev / f->size()) << std::endl;
1134 }
1135 }
1136 #endif // <unused>
1137
UpdateDelayDistribution()1138 void VirtualSocketServer::UpdateDelayDistribution() {
1139 webrtc::MutexLock lock(&mutex_);
1140 delay_dist_ = CreateDistribution(delay_mean_, delay_stddev_, delay_samples_);
1141 }
1142
1143 static double PI = 4 * atan(1.0);
1144
Normal(double x,double mean,double stddev)1145 static double Normal(double x, double mean, double stddev) {
1146 double a = (x - mean) * (x - mean) / (2 * stddev * stddev);
1147 return exp(-a) / (stddev * sqrt(2 * PI));
1148 }
1149
1150 #if 0 // static unused gives a warning
1151 static double Pareto(double x, double min, double k) {
1152 if (x < min)
1153 return 0;
1154 else
1155 return k * std::pow(min, k) / std::pow(x, k+1);
1156 }
1157 #endif
1158
1159 std::unique_ptr<VirtualSocketServer::Function>
CreateDistribution(uint32_t mean,uint32_t stddev,uint32_t samples)1160 VirtualSocketServer::CreateDistribution(uint32_t mean,
1161 uint32_t stddev,
1162 uint32_t samples) {
1163 auto f = std::make_unique<Function>();
1164
1165 if (0 == stddev) {
1166 f->push_back(Point(mean, 1.0));
1167 } else {
1168 double start = 0;
1169 if (mean >= 4 * static_cast<double>(stddev))
1170 start = mean - 4 * static_cast<double>(stddev);
1171 double end = mean + 4 * static_cast<double>(stddev);
1172
1173 for (uint32_t i = 0; i < samples; i++) {
1174 double x = start + (end - start) * i / (samples - 1);
1175 double y = Normal(x, mean, stddev);
1176 f->push_back(Point(x, y));
1177 }
1178 }
1179 return Resample(Invert(Accumulate(std::move(f))), 0, 1, samples);
1180 }
1181
GetTransitDelay(Socket * socket)1182 uint32_t VirtualSocketServer::GetTransitDelay(Socket* socket) {
1183 // Use the delay based on the address if it is set.
1184 auto iter = delay_by_ip_.find(socket->GetLocalAddress().ipaddr());
1185 if (iter != delay_by_ip_.end()) {
1186 return static_cast<uint32_t>(iter->second);
1187 }
1188 // Otherwise, use the delay from the distribution distribution.
1189 size_t index = rand() % delay_dist_->size();
1190 double delay = (*delay_dist_)[index].second;
1191 // RTC_LOG_F(LS_INFO) << "random[" << index << "] = " << delay;
1192 return static_cast<uint32_t>(delay);
1193 }
1194
1195 struct FunctionDomainCmp {
operator ()rtc::FunctionDomainCmp1196 bool operator()(const VirtualSocketServer::Point& p1,
1197 const VirtualSocketServer::Point& p2) {
1198 return p1.first < p2.first;
1199 }
operator ()rtc::FunctionDomainCmp1200 bool operator()(double v1, const VirtualSocketServer::Point& p2) {
1201 return v1 < p2.first;
1202 }
operator ()rtc::FunctionDomainCmp1203 bool operator()(const VirtualSocketServer::Point& p1, double v2) {
1204 return p1.first < v2;
1205 }
1206 };
1207
Accumulate(std::unique_ptr<Function> f)1208 std::unique_ptr<VirtualSocketServer::Function> VirtualSocketServer::Accumulate(
1209 std::unique_ptr<Function> f) {
1210 RTC_DCHECK(f->size() >= 1);
1211 double v = 0;
1212 for (Function::size_type i = 0; i < f->size() - 1; ++i) {
1213 double dx = (*f)[i + 1].first - (*f)[i].first;
1214 double avgy = ((*f)[i + 1].second + (*f)[i].second) / 2;
1215 (*f)[i].second = v;
1216 v = v + dx * avgy;
1217 }
1218 (*f)[f->size() - 1].second = v;
1219 return f;
1220 }
1221
Invert(std::unique_ptr<Function> f)1222 std::unique_ptr<VirtualSocketServer::Function> VirtualSocketServer::Invert(
1223 std::unique_ptr<Function> f) {
1224 for (Function::size_type i = 0; i < f->size(); ++i)
1225 std::swap((*f)[i].first, (*f)[i].second);
1226
1227 absl::c_sort(*f, FunctionDomainCmp());
1228 return f;
1229 }
1230
Resample(std::unique_ptr<Function> f,double x1,double x2,uint32_t samples)1231 std::unique_ptr<VirtualSocketServer::Function> VirtualSocketServer::Resample(
1232 std::unique_ptr<Function> f,
1233 double x1,
1234 double x2,
1235 uint32_t samples) {
1236 auto g = std::make_unique<Function>();
1237
1238 for (size_t i = 0; i < samples; i++) {
1239 double x = x1 + (x2 - x1) * i / (samples - 1);
1240 double y = Evaluate(f.get(), x);
1241 g->push_back(Point(x, y));
1242 }
1243
1244 return g;
1245 }
1246
Evaluate(const Function * f,double x)1247 double VirtualSocketServer::Evaluate(const Function* f, double x) {
1248 Function::const_iterator iter =
1249 absl::c_lower_bound(*f, x, FunctionDomainCmp());
1250 if (iter == f->begin()) {
1251 return (*f)[0].second;
1252 } else if (iter == f->end()) {
1253 RTC_DCHECK(f->size() >= 1);
1254 return (*f)[f->size() - 1].second;
1255 } else if (iter->first == x) {
1256 return iter->second;
1257 } else {
1258 double x1 = (iter - 1)->first;
1259 double y1 = (iter - 1)->second;
1260 double x2 = iter->first;
1261 double y2 = iter->second;
1262 return y1 + (y2 - y1) * (x - x1) / (x2 - x1);
1263 }
1264 }
1265
CanInteractWith(VirtualSocket * local,VirtualSocket * remote)1266 bool VirtualSocketServer::CanInteractWith(VirtualSocket* local,
1267 VirtualSocket* remote) {
1268 if (!local || !remote) {
1269 return false;
1270 }
1271 IPAddress local_ip = local->GetLocalAddress().ipaddr();
1272 IPAddress remote_ip = remote->GetLocalAddress().ipaddr();
1273 IPAddress local_normalized = local_ip.Normalized();
1274 IPAddress remote_normalized = remote_ip.Normalized();
1275 // Check if the addresses are the same family after Normalization (turns
1276 // mapped IPv6 address into IPv4 addresses).
1277 // This will stop unmapped V6 addresses from talking to mapped V6 addresses.
1278 if (local_normalized.family() == remote_normalized.family()) {
1279 return true;
1280 }
1281
1282 // If ip1 is IPv4 and ip2 is :: and ip2 is not IPV6_V6ONLY.
1283 int remote_v6_only = 0;
1284 remote->GetOption(Socket::OPT_IPV6_V6ONLY, &remote_v6_only);
1285 if (local_ip.family() == AF_INET && !remote_v6_only && IPIsAny(remote_ip)) {
1286 return true;
1287 }
1288 // Same check, backwards.
1289 int local_v6_only = 0;
1290 local->GetOption(Socket::OPT_IPV6_V6ONLY, &local_v6_only);
1291 if (remote_ip.family() == AF_INET && !local_v6_only && IPIsAny(local_ip)) {
1292 return true;
1293 }
1294
1295 // Check to see if either socket was explicitly bound to IPv6-any.
1296 // These sockets can talk with anyone.
1297 if (local_ip.family() == AF_INET6 && local->was_any()) {
1298 return true;
1299 }
1300 if (remote_ip.family() == AF_INET6 && remote->was_any()) {
1301 return true;
1302 }
1303
1304 return false;
1305 }
1306
GetDefaultSourceAddress(int family)1307 IPAddress VirtualSocketServer::GetDefaultSourceAddress(int family) {
1308 if (family == AF_INET) {
1309 return default_source_address_v4_;
1310 }
1311 if (family == AF_INET6) {
1312 return default_source_address_v6_;
1313 }
1314 return IPAddress();
1315 }
SetDefaultSourceAddress(const IPAddress & from_addr)1316 void VirtualSocketServer::SetDefaultSourceAddress(const IPAddress& from_addr) {
1317 RTC_DCHECK(!IPIsAny(from_addr));
1318 if (from_addr.family() == AF_INET) {
1319 default_source_address_v4_ = from_addr;
1320 } else if (from_addr.family() == AF_INET6) {
1321 default_source_address_v6_ = from_addr;
1322 }
1323 }
1324
set_bandwidth(uint32_t bandwidth)1325 void VirtualSocketServer::set_bandwidth(uint32_t bandwidth) {
1326 webrtc::MutexLock lock(&mutex_);
1327 bandwidth_ = bandwidth;
1328 }
set_network_capacity(uint32_t capacity)1329 void VirtualSocketServer::set_network_capacity(uint32_t capacity) {
1330 webrtc::MutexLock lock(&mutex_);
1331 network_capacity_ = capacity;
1332 }
1333
send_buffer_capacity() const1334 uint32_t VirtualSocketServer::send_buffer_capacity() const {
1335 webrtc::MutexLock lock(&mutex_);
1336 return send_buffer_capacity_;
1337 }
set_send_buffer_capacity(uint32_t capacity)1338 void VirtualSocketServer::set_send_buffer_capacity(uint32_t capacity) {
1339 webrtc::MutexLock lock(&mutex_);
1340 send_buffer_capacity_ = capacity;
1341 }
1342
recv_buffer_capacity() const1343 uint32_t VirtualSocketServer::recv_buffer_capacity() const {
1344 webrtc::MutexLock lock(&mutex_);
1345 return recv_buffer_capacity_;
1346 }
set_recv_buffer_capacity(uint32_t capacity)1347 void VirtualSocketServer::set_recv_buffer_capacity(uint32_t capacity) {
1348 webrtc::MutexLock lock(&mutex_);
1349 recv_buffer_capacity_ = capacity;
1350 }
1351
set_delay_mean(uint32_t delay_mean)1352 void VirtualSocketServer::set_delay_mean(uint32_t delay_mean) {
1353 webrtc::MutexLock lock(&mutex_);
1354 delay_mean_ = delay_mean;
1355 }
set_delay_stddev(uint32_t delay_stddev)1356 void VirtualSocketServer::set_delay_stddev(uint32_t delay_stddev) {
1357 webrtc::MutexLock lock(&mutex_);
1358 delay_stddev_ = delay_stddev;
1359 }
set_delay_samples(uint32_t delay_samples)1360 void VirtualSocketServer::set_delay_samples(uint32_t delay_samples) {
1361 webrtc::MutexLock lock(&mutex_);
1362 delay_samples_ = delay_samples;
1363 }
1364
set_drop_probability(double drop_prob)1365 void VirtualSocketServer::set_drop_probability(double drop_prob) {
1366 RTC_DCHECK_GE(drop_prob, 0.0);
1367 RTC_DCHECK_LE(drop_prob, 1.0);
1368
1369 webrtc::MutexLock lock(&mutex_);
1370 drop_prob_ = drop_prob;
1371 }
1372
set_max_udp_payload(size_t payload_size)1373 void VirtualSocketServer::set_max_udp_payload(size_t payload_size) {
1374 webrtc::MutexLock lock(&mutex_);
1375 max_udp_payload_ = payload_size;
1376 }
1377
sent_packets() const1378 uint32_t VirtualSocketServer::sent_packets() const {
1379 webrtc::MutexLock lock(&mutex_);
1380 return sent_packets_;
1381 }
1382
1383 } // namespace rtc
1384