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