physical_socket_server.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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_PHYSICAL_SOCKET_SERVER_H_
  11. #define RTC_BASE_PHYSICAL_SOCKET_SERVER_H_
  12. #if defined(WEBRTC_POSIX) && defined(WEBRTC_LINUX)
  13. #include <sys/epoll.h>
  14. #define WEBRTC_USE_EPOLL 1
  15. #endif
  16. #include <array>
  17. #include <memory>
  18. #include <unordered_map>
  19. #include <vector>
  20. #include "rtc_base/deprecated/recursive_critical_section.h"
  21. #include "rtc_base/net_helpers.h"
  22. #include "rtc_base/socket_server.h"
  23. #include "rtc_base/system/rtc_export.h"
  24. #include "rtc_base/thread_annotations.h"
  25. #if defined(WEBRTC_POSIX)
  26. typedef int SOCKET;
  27. #endif // WEBRTC_POSIX
  28. namespace rtc {
  29. // Event constants for the Dispatcher class.
  30. enum DispatcherEvent {
  31. DE_READ = 0x0001,
  32. DE_WRITE = 0x0002,
  33. DE_CONNECT = 0x0004,
  34. DE_CLOSE = 0x0008,
  35. DE_ACCEPT = 0x0010,
  36. };
  37. class Signaler;
  38. class Dispatcher {
  39. public:
  40. virtual ~Dispatcher() {}
  41. virtual uint32_t GetRequestedEvents() = 0;
  42. virtual void OnPreEvent(uint32_t ff) = 0;
  43. virtual void OnEvent(uint32_t ff, int err) = 0;
  44. #if defined(WEBRTC_WIN)
  45. virtual WSAEVENT GetWSAEvent() = 0;
  46. virtual SOCKET GetSocket() = 0;
  47. virtual bool CheckSignalClose() = 0;
  48. #elif defined(WEBRTC_POSIX)
  49. virtual int GetDescriptor() = 0;
  50. virtual bool IsDescriptorClosed() = 0;
  51. #endif
  52. };
  53. // A socket server that provides the real sockets of the underlying OS.
  54. class RTC_EXPORT PhysicalSocketServer : public SocketServer {
  55. public:
  56. PhysicalSocketServer();
  57. ~PhysicalSocketServer() override;
  58. // SocketFactory:
  59. Socket* CreateSocket(int family, int type) override;
  60. AsyncSocket* CreateAsyncSocket(int family, int type) override;
  61. // Internal Factory for Accept (virtual so it can be overwritten in tests).
  62. virtual AsyncSocket* WrapSocket(SOCKET s);
  63. // SocketServer:
  64. bool Wait(int cms, bool process_io) override;
  65. void WakeUp() override;
  66. void Add(Dispatcher* dispatcher);
  67. void Remove(Dispatcher* dispatcher);
  68. void Update(Dispatcher* dispatcher);
  69. private:
  70. // The number of events to process with one call to "epoll_wait".
  71. static constexpr size_t kNumEpollEvents = 128;
  72. #if defined(WEBRTC_POSIX)
  73. bool WaitSelect(int cms, bool process_io);
  74. #endif // WEBRTC_POSIX
  75. #if defined(WEBRTC_USE_EPOLL)
  76. void AddEpoll(Dispatcher* dispatcher, uint64_t key);
  77. void RemoveEpoll(Dispatcher* dispatcher);
  78. void UpdateEpoll(Dispatcher* dispatcher, uint64_t key);
  79. bool WaitEpoll(int cms);
  80. bool WaitPoll(int cms, Dispatcher* dispatcher);
  81. // This array is accessed in isolation by a thread calling into Wait().
  82. // It's useless to use a SequenceChecker to guard it because a socket
  83. // server can outlive the thread it's bound to, forcing the Wait call
  84. // to have to reset the sequence checker on Wait calls.
  85. std::array<epoll_event, kNumEpollEvents> epoll_events_;
  86. const int epoll_fd_ = INVALID_SOCKET;
  87. #endif // WEBRTC_USE_EPOLL
  88. // uint64_t keys are used to uniquely identify a dispatcher in order to avoid
  89. // the ABA problem during the epoll loop (a dispatcher being destroyed and
  90. // replaced by one with the same address).
  91. uint64_t next_dispatcher_key_ RTC_GUARDED_BY(crit_) = 0;
  92. std::unordered_map<uint64_t, Dispatcher*> dispatcher_by_key_
  93. RTC_GUARDED_BY(crit_);
  94. // Reverse lookup necessary for removals/updates.
  95. std::unordered_map<Dispatcher*, uint64_t> key_by_dispatcher_
  96. RTC_GUARDED_BY(crit_);
  97. // A list of dispatcher keys that we're interested in for the current
  98. // select() or WSAWaitForMultipleEvents() loop. Again, used to avoid the ABA
  99. // problem (a socket being destroyed and a new one created with the same
  100. // handle, erroneously receiving the events from the destroyed socket).
  101. //
  102. // Kept as a member variable just for efficiency.
  103. std::vector<uint64_t> current_dispatcher_keys_;
  104. Signaler* signal_wakeup_; // Assigned in constructor only
  105. RecursiveCriticalSection crit_;
  106. #if defined(WEBRTC_WIN)
  107. const WSAEVENT socket_ev_;
  108. #endif
  109. bool fWait_;
  110. // Are we currently in a select()/epoll()/WSAWaitForMultipleEvents loop?
  111. // Used for a DCHECK, because we don't support reentrant waiting.
  112. bool waiting_ = false;
  113. };
  114. class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
  115. public:
  116. PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET);
  117. ~PhysicalSocket() override;
  118. // Creates the underlying OS socket (same as the "socket" function).
  119. virtual bool Create(int family, int type);
  120. SocketAddress GetLocalAddress() const override;
  121. SocketAddress GetRemoteAddress() const override;
  122. int Bind(const SocketAddress& bind_addr) override;
  123. int Connect(const SocketAddress& addr) override;
  124. int GetError() const override;
  125. void SetError(int error) override;
  126. ConnState GetState() const override;
  127. int GetOption(Option opt, int* value) override;
  128. int SetOption(Option opt, int value) override;
  129. int Send(const void* pv, size_t cb) override;
  130. int SendTo(const void* buffer,
  131. size_t length,
  132. const SocketAddress& addr) override;
  133. int Recv(void* buffer, size_t length, int64_t* timestamp) override;
  134. int RecvFrom(void* buffer,
  135. size_t length,
  136. SocketAddress* out_addr,
  137. int64_t* timestamp) override;
  138. int Listen(int backlog) override;
  139. AsyncSocket* Accept(SocketAddress* out_addr) override;
  140. int Close() override;
  141. SocketServer* socketserver() { return ss_; }
  142. protected:
  143. int DoConnect(const SocketAddress& connect_addr);
  144. // Make virtual so ::accept can be overwritten in tests.
  145. virtual SOCKET DoAccept(SOCKET socket, sockaddr* addr, socklen_t* addrlen);
  146. // Make virtual so ::send can be overwritten in tests.
  147. virtual int DoSend(SOCKET socket, const char* buf, int len, int flags);
  148. // Make virtual so ::sendto can be overwritten in tests.
  149. virtual int DoSendTo(SOCKET socket,
  150. const char* buf,
  151. int len,
  152. int flags,
  153. const struct sockaddr* dest_addr,
  154. socklen_t addrlen);
  155. void OnResolveResult(AsyncResolverInterface* resolver);
  156. void UpdateLastError();
  157. void MaybeRemapSendError();
  158. uint8_t enabled_events() const { return enabled_events_; }
  159. virtual void SetEnabledEvents(uint8_t events);
  160. virtual void EnableEvents(uint8_t events);
  161. virtual void DisableEvents(uint8_t events);
  162. int TranslateOption(Option opt, int* slevel, int* sopt);
  163. PhysicalSocketServer* ss_;
  164. SOCKET s_;
  165. bool udp_;
  166. int family_ = 0;
  167. RecursiveCriticalSection crit_;
  168. int error_ RTC_GUARDED_BY(crit_);
  169. ConnState state_;
  170. AsyncResolver* resolver_;
  171. #if !defined(NDEBUG)
  172. std::string dbg_addr_;
  173. #endif
  174. private:
  175. uint8_t enabled_events_ = 0;
  176. };
  177. class SocketDispatcher : public Dispatcher, public PhysicalSocket {
  178. public:
  179. explicit SocketDispatcher(PhysicalSocketServer* ss);
  180. SocketDispatcher(SOCKET s, PhysicalSocketServer* ss);
  181. ~SocketDispatcher() override;
  182. bool Initialize();
  183. virtual bool Create(int type);
  184. bool Create(int family, int type) override;
  185. #if defined(WEBRTC_WIN)
  186. WSAEVENT GetWSAEvent() override;
  187. SOCKET GetSocket() override;
  188. bool CheckSignalClose() override;
  189. #elif defined(WEBRTC_POSIX)
  190. int GetDescriptor() override;
  191. bool IsDescriptorClosed() override;
  192. #endif
  193. uint32_t GetRequestedEvents() override;
  194. void OnPreEvent(uint32_t ff) override;
  195. void OnEvent(uint32_t ff, int err) override;
  196. int Close() override;
  197. #if defined(WEBRTC_USE_EPOLL)
  198. protected:
  199. void StartBatchedEventUpdates();
  200. void FinishBatchedEventUpdates();
  201. void SetEnabledEvents(uint8_t events) override;
  202. void EnableEvents(uint8_t events) override;
  203. void DisableEvents(uint8_t events) override;
  204. #endif
  205. private:
  206. #if defined(WEBRTC_WIN)
  207. static int next_id_;
  208. int id_;
  209. bool signal_close_;
  210. int signal_err_;
  211. #endif // WEBRTC_WIN
  212. #if defined(WEBRTC_USE_EPOLL)
  213. void MaybeUpdateDispatcher(uint8_t old_events);
  214. int saved_enabled_events_ = -1;
  215. #endif
  216. };
  217. } // namespace rtc
  218. #endif // RTC_BASE_PHYSICAL_SOCKET_SERVER_H_