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