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