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