physical_socket_server.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 <set>
  19. #include <vector>
  20. #include "rtc_base/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. typedef std::set<Dispatcher*> DispatcherSet;
  73. void AddRemovePendingDispatchers() RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
  74. #if defined(WEBRTC_POSIX)
  75. bool WaitSelect(int cms, bool process_io);
  76. #endif // WEBRTC_POSIX
  77. #if defined(WEBRTC_USE_EPOLL)
  78. void AddEpoll(Dispatcher* dispatcher);
  79. void RemoveEpoll(Dispatcher* dispatcher);
  80. void UpdateEpoll(Dispatcher* dispatcher);
  81. bool WaitEpoll(int cms);
  82. bool WaitPoll(int cms, Dispatcher* dispatcher);
  83. // This array is accessed in isolation by a thread calling into Wait().
  84. // It's useless to use a SequenceChecker to guard it because a socket
  85. // server can outlive the thread it's bound to, forcing the Wait call
  86. // to have to reset the sequence checker on Wait calls.
  87. std::array<epoll_event, kNumEpollEvents> epoll_events_;
  88. const int epoll_fd_ = INVALID_SOCKET;
  89. #endif // WEBRTC_USE_EPOLL
  90. DispatcherSet dispatchers_ RTC_GUARDED_BY(crit_);
  91. DispatcherSet pending_add_dispatchers_ RTC_GUARDED_BY(crit_);
  92. DispatcherSet pending_remove_dispatchers_ RTC_GUARDED_BY(crit_);
  93. bool processing_dispatchers_ RTC_GUARDED_BY(crit_) = false;
  94. Signaler* signal_wakeup_; // Assigned in constructor only
  95. CriticalSection crit_;
  96. #if defined(WEBRTC_WIN)
  97. const WSAEVENT socket_ev_;
  98. #endif
  99. bool fWait_;
  100. };
  101. class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
  102. public:
  103. PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET);
  104. ~PhysicalSocket() override;
  105. // Creates the underlying OS socket (same as the "socket" function).
  106. virtual bool Create(int family, int type);
  107. SocketAddress GetLocalAddress() const override;
  108. SocketAddress GetRemoteAddress() const override;
  109. int Bind(const SocketAddress& bind_addr) override;
  110. int Connect(const SocketAddress& addr) override;
  111. int GetError() const override;
  112. void SetError(int error) override;
  113. ConnState GetState() const override;
  114. int GetOption(Option opt, int* value) override;
  115. int SetOption(Option opt, int value) override;
  116. int Send(const void* pv, size_t cb) override;
  117. int SendTo(const void* buffer,
  118. size_t length,
  119. const SocketAddress& addr) override;
  120. int Recv(void* buffer, size_t length, int64_t* timestamp) override;
  121. int RecvFrom(void* buffer,
  122. size_t length,
  123. SocketAddress* out_addr,
  124. int64_t* timestamp) override;
  125. int Listen(int backlog) override;
  126. AsyncSocket* Accept(SocketAddress* out_addr) override;
  127. int Close() override;
  128. SocketServer* socketserver() { return ss_; }
  129. protected:
  130. int DoConnect(const SocketAddress& connect_addr);
  131. // Make virtual so ::accept can be overwritten in tests.
  132. virtual SOCKET DoAccept(SOCKET socket, sockaddr* addr, socklen_t* addrlen);
  133. // Make virtual so ::send can be overwritten in tests.
  134. virtual int DoSend(SOCKET socket, const char* buf, int len, int flags);
  135. // Make virtual so ::sendto can be overwritten in tests.
  136. virtual int DoSendTo(SOCKET socket,
  137. const char* buf,
  138. int len,
  139. int flags,
  140. const struct sockaddr* dest_addr,
  141. socklen_t addrlen);
  142. void OnResolveResult(AsyncResolverInterface* resolver);
  143. void UpdateLastError();
  144. void MaybeRemapSendError();
  145. uint8_t enabled_events() const { return enabled_events_; }
  146. virtual void SetEnabledEvents(uint8_t events);
  147. virtual void EnableEvents(uint8_t events);
  148. virtual void DisableEvents(uint8_t events);
  149. int TranslateOption(Option opt, int* slevel, int* sopt);
  150. PhysicalSocketServer* ss_;
  151. SOCKET s_;
  152. bool udp_;
  153. int family_ = 0;
  154. CriticalSection crit_;
  155. int error_ RTC_GUARDED_BY(crit_);
  156. ConnState state_;
  157. AsyncResolver* resolver_;
  158. #if !defined(NDEBUG)
  159. std::string dbg_addr_;
  160. #endif
  161. private:
  162. uint8_t enabled_events_ = 0;
  163. };
  164. class SocketDispatcher : public Dispatcher, public PhysicalSocket {
  165. public:
  166. explicit SocketDispatcher(PhysicalSocketServer* ss);
  167. SocketDispatcher(SOCKET s, PhysicalSocketServer* ss);
  168. ~SocketDispatcher() override;
  169. bool Initialize();
  170. virtual bool Create(int type);
  171. bool Create(int family, int type) override;
  172. #if defined(WEBRTC_WIN)
  173. WSAEVENT GetWSAEvent() override;
  174. SOCKET GetSocket() override;
  175. bool CheckSignalClose() override;
  176. #elif defined(WEBRTC_POSIX)
  177. int GetDescriptor() override;
  178. bool IsDescriptorClosed() override;
  179. #endif
  180. uint32_t GetRequestedEvents() override;
  181. void OnPreEvent(uint32_t ff) override;
  182. void OnEvent(uint32_t ff, int err) override;
  183. int Close() override;
  184. #if defined(WEBRTC_USE_EPOLL)
  185. protected:
  186. void StartBatchedEventUpdates();
  187. void FinishBatchedEventUpdates();
  188. void SetEnabledEvents(uint8_t events) override;
  189. void EnableEvents(uint8_t events) override;
  190. void DisableEvents(uint8_t events) override;
  191. #endif
  192. private:
  193. #if defined(WEBRTC_WIN)
  194. static int next_id_;
  195. int id_;
  196. bool signal_close_;
  197. int signal_err_;
  198. #endif // WEBRTC_WIN
  199. #if defined(WEBRTC_USE_EPOLL)
  200. void MaybeUpdateDispatcher(uint8_t old_events);
  201. int saved_enabled_events_ = -1;
  202. #endif
  203. };
  204. } // namespace rtc
  205. #endif // RTC_BASE_PHYSICAL_SOCKET_SERVER_H_