virtual_socket_server.h 16 KB

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