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