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.

1208 lines
38 KiB

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