You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1117 lines
35 KiB

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