virtual_socket_server.h 15 KB

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