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