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.

412 lines
16 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. #ifndef RTC_BASE_VIRTUAL_SOCKET_SERVER_H_
  11. #define RTC_BASE_VIRTUAL_SOCKET_SERVER_H_
  12. #include <deque>
  13. #include <map>
  14. #include "rtc_base/checks.h"
  15. #include "rtc_base/constructor_magic.h"
  16. #include "rtc_base/event.h"
  17. #include "rtc_base/fake_clock.h"
  18. #include "rtc_base/message_queue.h"
  19. #include "rtc_base/socket_server.h"
  20. namespace rtc {
  21. class Packet;
  22. class VirtualSocket;
  23. class SocketAddressPair;
  24. // Simulates a network in the same manner as a loopback interface. The
  25. // interface can create as many addresses as you want. All of the sockets
  26. // created by this network will be able to communicate with one another, unless
  27. // they are bound to addresses from incompatible families.
  28. class VirtualSocketServer : public SocketServer, public sigslot::has_slots<> {
  29. public:
  30. VirtualSocketServer();
  31. // This constructor needs to be used if the test uses a fake clock and
  32. // ProcessMessagesUntilIdle, since ProcessMessagesUntilIdle needs a way of
  33. // advancing time.
  34. explicit VirtualSocketServer(ThreadProcessingFakeClock* fake_clock);
  35. ~VirtualSocketServer() override;
  36. // The default route indicates which local address to use when a socket is
  37. // bound to the 'any' address, e.g. 0.0.0.0.
  38. IPAddress GetDefaultRoute(int family);
  39. void SetDefaultRoute(const IPAddress& from_addr);
  40. // Limits the network bandwidth (maximum bytes per second). Zero means that
  41. // all sends occur instantly. Defaults to 0.
  42. uint32_t bandwidth() const { return bandwidth_; }
  43. void set_bandwidth(uint32_t bandwidth) { bandwidth_ = bandwidth; }
  44. // Limits the amount of data which can be in flight on the network without
  45. // packet loss (on a per sender basis). Defaults to 64 KB.
  46. uint32_t network_capacity() const { return network_capacity_; }
  47. void set_network_capacity(uint32_t capacity) { network_capacity_ = capacity; }
  48. // The amount of data which can be buffered by tcp on the sender's side
  49. uint32_t send_buffer_capacity() const { return send_buffer_capacity_; }
  50. void set_send_buffer_capacity(uint32_t capacity) {
  51. send_buffer_capacity_ = capacity;
  52. }
  53. // The amount of data which can be buffered by tcp on the receiver's side
  54. uint32_t recv_buffer_capacity() const { return recv_buffer_capacity_; }
  55. void set_recv_buffer_capacity(uint32_t capacity) {
  56. recv_buffer_capacity_ = capacity;
  57. }
  58. // Controls the (transit) delay for packets sent in the network. This does
  59. // not inclue the time required to sit in the send queue. Both of these
  60. // values are measured in milliseconds. Defaults to no delay.
  61. uint32_t delay_mean() const { return delay_mean_; }
  62. uint32_t delay_stddev() const { return delay_stddev_; }
  63. uint32_t delay_samples() const { return delay_samples_; }
  64. void set_delay_mean(uint32_t delay_mean) { delay_mean_ = delay_mean; }
  65. void set_delay_stddev(uint32_t delay_stddev) { delay_stddev_ = delay_stddev; }
  66. void set_delay_samples(uint32_t delay_samples) {
  67. delay_samples_ = delay_samples;
  68. }
  69. // If the (transit) delay parameters are modified, this method should be
  70. // called to recompute the new distribution.
  71. void UpdateDelayDistribution();
  72. // Controls the (uniform) probability that any sent packet is dropped. This
  73. // is separate from calculations to drop based on queue size.
  74. double drop_probability() { return drop_prob_; }
  75. void set_drop_probability(double drop_prob) {
  76. RTC_DCHECK_GE(drop_prob, 0.0);
  77. RTC_DCHECK_LE(drop_prob, 1.0);
  78. drop_prob_ = drop_prob;
  79. }
  80. // If |blocked| is true, subsequent attempts to send will result in -1 being
  81. // returned, with the socket error set to EWOULDBLOCK.
  82. //
  83. // If this method is later called with |blocked| set to false, any sockets
  84. // that previously failed to send with EWOULDBLOCK will emit SignalWriteEvent.
  85. //
  86. // This can be used to simulate the send buffer on a network interface being
  87. // full, and test functionality related to EWOULDBLOCK/SignalWriteEvent.
  88. void SetSendingBlocked(bool blocked);
  89. // SocketFactory:
  90. Socket* CreateSocket(int family, int type) override;
  91. AsyncSocket* CreateAsyncSocket(int family, int type) override;
  92. // SocketServer:
  93. void SetMessageQueue(MessageQueue* queue) override;
  94. bool Wait(int cms, bool process_io) override;
  95. void WakeUp() override;
  96. void SetDelayOnAddress(const rtc::SocketAddress& address, int delay_ms) {
  97. delay_by_ip_[address.ipaddr()] = delay_ms;
  98. }
  99. // Used by TurnPortTest and TcpPortTest (for example), to mimic a case where
  100. // a proxy returns the local host address instead of the original one the
  101. // port was bound against. Please see WebRTC issue 3927 for more detail.
  102. //
  103. // If SetAlternativeLocalAddress(A, B) is called, then when something
  104. // attempts to bind a socket to address A, it will get a socket bound to
  105. // address B instead.
  106. void SetAlternativeLocalAddress(const rtc::IPAddress& address,
  107. const rtc::IPAddress& alternative);
  108. typedef std::pair<double, double> Point;
  109. typedef std::vector<Point> Function;
  110. static Function* CreateDistribution(uint32_t mean,
  111. uint32_t stddev,
  112. uint32_t samples);
  113. // Similar to Thread::ProcessMessages, but it only processes messages until
  114. // there are no immediate messages or pending network traffic. Returns false
  115. // if Thread::Stop() was called.
  116. bool ProcessMessagesUntilIdle();
  117. // Sets the next port number to use for testing.
  118. void SetNextPortForTesting(uint16_t port);
  119. // Close a pair of Tcp connections by addresses. Both connections will have
  120. // its own OnClose invoked.
  121. bool CloseTcpConnections(const SocketAddress& addr_local,
  122. const SocketAddress& addr_remote);
  123. // Number of packets that clients have attempted to send through this virtual
  124. // socket server. Intended to be used for test assertions.
  125. uint32_t sent_packets() const { return sent_packets_; }
  126. // For testing purpose only. Fired when a client socket is created.
  127. sigslot::signal1<VirtualSocket*> SignalSocketCreated;
  128. protected:
  129. // Returns a new IP not used before in this network.
  130. IPAddress GetNextIP(int family);
  131. uint16_t GetNextPort();
  132. VirtualSocket* CreateSocketInternal(int family, int type);
  133. // Binds the given socket to addr, assigning and IP and Port if necessary
  134. int Bind(VirtualSocket* socket, SocketAddress* addr);
  135. // Binds the given socket to the given (fully-defined) address.
  136. int Bind(VirtualSocket* socket, const SocketAddress& addr);
  137. // Find the socket bound to the given address
  138. VirtualSocket* LookupBinding(const SocketAddress& addr);
  139. int Unbind(const SocketAddress& addr, VirtualSocket* socket);
  140. // Adds a mapping between this socket pair and the socket.
  141. void AddConnection(const SocketAddress& client,
  142. const SocketAddress& server,
  143. VirtualSocket* socket);
  144. // Find the socket pair corresponding to this server address.
  145. VirtualSocket* LookupConnection(const SocketAddress& client,
  146. const SocketAddress& server);
  147. void RemoveConnection(const SocketAddress& client,
  148. const SocketAddress& server);
  149. // Connects the given socket to the socket at the given address
  150. int Connect(VirtualSocket* socket,
  151. const SocketAddress& remote_addr,
  152. bool use_delay);
  153. // Sends a disconnect message to the socket at the given address
  154. bool Disconnect(VirtualSocket* socket);
  155. // Sends the given packet to the socket at the given address (if one exists).
  156. int SendUdp(VirtualSocket* socket,
  157. const char* data,
  158. size_t data_size,
  159. const SocketAddress& remote_addr);
  160. // Moves as much data as possible from the sender's buffer to the network
  161. void SendTcp(VirtualSocket* socket);
  162. // Places a packet on the network.
  163. void AddPacketToNetwork(VirtualSocket* socket,
  164. VirtualSocket* recipient,
  165. int64_t cur_time,
  166. const char* data,
  167. size_t data_size,
  168. size_t header_size,
  169. bool ordered);
  170. // Removes stale packets from the network
  171. void PurgeNetworkPackets(VirtualSocket* socket, int64_t cur_time);
  172. // Computes the number of milliseconds required to send a packet of this size.
  173. uint32_t SendDelay(uint32_t size);
  174. // If the delay has been set for the address of the socket, returns the set
  175. // delay. Otherwise, returns a random transit delay chosen from the
  176. // appropriate distribution.
  177. uint32_t GetTransitDelay(Socket* socket);
  178. // Basic operations on functions. Those that return a function also take
  179. // ownership of the function given (and hence, may modify or delete it).
  180. static Function* Accumulate(Function* f);
  181. static Function* Invert(Function* f);
  182. static Function* Resample(Function* f,
  183. double x1,
  184. double x2,
  185. uint32_t samples);
  186. static double Evaluate(Function* f, double x);
  187. // Null out our message queue if it goes away. Necessary in the case where
  188. // our lifetime is greater than that of the thread we are using, since we
  189. // try to send Close messages for all connected sockets when we shutdown.
  190. void OnMessageQueueDestroyed() { msg_queue_ = nullptr; }
  191. // Determine if two sockets should be able to communicate.
  192. // We don't (currently) specify an address family for sockets; instead,
  193. // the currently bound address is used to infer the address family.
  194. // Any socket that is not explicitly bound to an IPv4 address is assumed to be
  195. // dual-stack capable.
  196. // This function tests if two addresses can communicate, as well as the
  197. // sockets to which they may be bound (the addresses may or may not yet be
  198. // bound to the sockets).
  199. // First the addresses are tested (after normalization):
  200. // If both have the same family, then communication is OK.
  201. // If only one is IPv4 then false, unless the other is bound to ::.
  202. // This applies even if the IPv4 address is 0.0.0.0.
  203. // The socket arguments are optional; the sockets are checked to see if they
  204. // were explicitly bound to IPv6-any ('::'), and if so communication is
  205. // permitted.
  206. // NB: This scheme doesn't permit non-dualstack IPv6 sockets.
  207. static bool CanInteractWith(VirtualSocket* local, VirtualSocket* remote);
  208. private:
  209. friend class VirtualSocket;
  210. // Sending was previously blocked, but now isn't.
  211. sigslot::signal0<> SignalReadyToSend;
  212. typedef std::map<SocketAddress, VirtualSocket*> AddressMap;
  213. typedef std::map<SocketAddressPair, VirtualSocket*> ConnectionMap;
  214. // May be null if the test doesn't use a fake clock, or it does but doesn't
  215. // use ProcessMessagesUntilIdle.
  216. ThreadProcessingFakeClock* fake_clock_ = nullptr;
  217. // Used to implement Wait/WakeUp.
  218. Event wakeup_;
  219. MessageQueue* msg_queue_;
  220. bool stop_on_idle_;
  221. in_addr next_ipv4_;
  222. in6_addr next_ipv6_;
  223. uint16_t next_port_;
  224. AddressMap* bindings_;
  225. ConnectionMap* connections_;
  226. IPAddress default_route_v4_;
  227. IPAddress default_route_v6_;
  228. uint32_t bandwidth_;
  229. uint32_t network_capacity_;
  230. uint32_t send_buffer_capacity_;
  231. uint32_t recv_buffer_capacity_;
  232. uint32_t delay_mean_;
  233. uint32_t delay_stddev_;
  234. uint32_t delay_samples_;
  235. // Used for testing.
  236. uint32_t sent_packets_ = 0;
  237. std::map<rtc::IPAddress, int> delay_by_ip_;
  238. std::map<rtc::IPAddress, rtc::IPAddress> alternative_address_mapping_;
  239. std::unique_ptr<Function> delay_dist_;
  240. CriticalSection delay_crit_;
  241. double drop_prob_;
  242. bool sending_blocked_ = false;
  243. RTC_DISALLOW_COPY_AND_ASSIGN(VirtualSocketServer);
  244. };
  245. // Implements the socket interface using the virtual network. Packets are
  246. // passed as messages using the message queue of the socket server.
  247. class VirtualSocket : public AsyncSocket,
  248. public MessageHandler,
  249. public sigslot::has_slots<> {
  250. public:
  251. VirtualSocket(VirtualSocketServer* server, int family, int type, bool async);
  252. ~VirtualSocket() override;
  253. SocketAddress GetLocalAddress() const override;
  254. SocketAddress GetRemoteAddress() const override;
  255. int Bind(const SocketAddress& addr) override;
  256. int Connect(const SocketAddress& addr) override;
  257. int Close() override;
  258. int Send(const void* pv, size_t cb) override;
  259. int SendTo(const void* pv, size_t cb, const SocketAddress& addr) override;
  260. int Recv(void* pv, size_t cb, int64_t* timestamp) override;
  261. int RecvFrom(void* pv,
  262. size_t cb,
  263. SocketAddress* paddr,
  264. int64_t* timestamp) override;
  265. int Listen(int backlog) override;
  266. VirtualSocket* Accept(SocketAddress* paddr) override;
  267. int GetError() const override;
  268. void SetError(int error) override;
  269. ConnState GetState() const override;
  270. int GetOption(Option opt, int* value) override;
  271. int SetOption(Option opt, int value) override;
  272. void OnMessage(Message* pmsg) override;
  273. bool was_any() { return was_any_; }
  274. void set_was_any(bool was_any) { was_any_ = was_any; }
  275. // For testing purpose only. Fired when client socket is bound to an address.
  276. sigslot::signal2<VirtualSocket*, const SocketAddress&> SignalAddressReady;
  277. private:
  278. struct NetworkEntry {
  279. size_t size;
  280. int64_t done_time;
  281. };
  282. typedef std::deque<SocketAddress> ListenQueue;
  283. typedef std::deque<NetworkEntry> NetworkQueue;
  284. typedef std::vector<char> SendBuffer;
  285. typedef std::list<Packet*> RecvBuffer;
  286. typedef std::map<Option, int> OptionsMap;
  287. int InitiateConnect(const SocketAddress& addr, bool use_delay);
  288. void CompleteConnect(const SocketAddress& addr, bool notify);
  289. int SendUdp(const void* pv, size_t cb, const SocketAddress& addr);
  290. int SendTcp(const void* pv, size_t cb);
  291. // Used by server sockets to set the local address without binding.
  292. void SetLocalAddress(const SocketAddress& addr);
  293. void OnSocketServerReadyToSend();
  294. VirtualSocketServer* server_;
  295. int type_;
  296. bool async_;
  297. ConnState state_;
  298. int error_;
  299. SocketAddress local_addr_;
  300. SocketAddress remote_addr_;
  301. // Pending sockets which can be Accepted
  302. ListenQueue* listen_queue_;
  303. // Data which tcp has buffered for sending
  304. SendBuffer send_buffer_;
  305. // Set to false if the last attempt to send resulted in EWOULDBLOCK.
  306. // Set back to true when the socket can send again.
  307. bool ready_to_send_ = true;
  308. // Critical section to protect the recv_buffer and queue_
  309. CriticalSection crit_;
  310. // Network model that enforces bandwidth and capacity constraints
  311. NetworkQueue network_;
  312. size_t network_size_;
  313. // The scheduled delivery time of the last packet sent on this socket.
  314. // It is used to ensure ordered delivery of packets sent on this socket.
  315. int64_t last_delivery_time_ = 0;
  316. // Data which has been received from the network
  317. RecvBuffer recv_buffer_;
  318. // The amount of data which is in flight or in recv_buffer_
  319. size_t recv_buffer_size_;
  320. // Is this socket bound?
  321. bool bound_;
  322. // When we bind a socket to Any, VSS's Bind gives it another address. For
  323. // dual-stack sockets, we want to distinguish between sockets that were
  324. // explicitly given a particular address and sockets that had one picked
  325. // for them by VSS.
  326. bool was_any_;
  327. // Store the options that are set
  328. OptionsMap options_map_;
  329. friend class VirtualSocketServer;
  330. };
  331. } // namespace rtc
  332. #endif // RTC_BASE_VIRTUAL_SOCKET_SERVER_H_