blob: 5a09aacc9b22e86feae503c6cc9b478972f9af34 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#ifndef RTC_BASE_PHYSICAL_SOCKET_SERVER_H_
12#define RTC_BASE_PHYSICAL_SOCKET_SERVER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#if defined(WEBRTC_POSIX) && defined(WEBRTC_LINUX)
15#include <sys/epoll.h>
16#define WEBRTC_USE_EPOLL 1
17#endif
jbauchde4db112017-05-31 13:09:18 -070018
Markus Handellb7c63ab2020-05-26 18:09:55 +020019#include <array>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020020#include <memory>
Taylor Brandstetter7b69a442020-08-20 23:43:13 +000021#include <unordered_map>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020022#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
Mirko Bonadeie5f4c6b2021-01-15 10:41:01 +010024#include "rtc_base/async_resolver.h"
25#include "rtc_base/async_resolver_interface.h"
Markus Handell3cb525b2020-07-16 16:16:09 +020026#include "rtc_base/deprecated/recursive_critical_section.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/socket_server.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020028#include "rtc_base/system/rtc_export.h"
Niels Möller8ce078d2020-05-18 10:17:41 +020029#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020030
31#if defined(WEBRTC_POSIX)
32typedef int SOCKET;
Yves Gerey665174f2018-06-19 15:03:05 +020033#endif // WEBRTC_POSIX
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020034
35namespace rtc {
36
37// Event constants for the Dispatcher class.
38enum DispatcherEvent {
Yves Gerey665174f2018-06-19 15:03:05 +020039 DE_READ = 0x0001,
40 DE_WRITE = 0x0002,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020041 DE_CONNECT = 0x0004,
Yves Gerey665174f2018-06-19 15:03:05 +020042 DE_CLOSE = 0x0008,
43 DE_ACCEPT = 0x0010,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020044};
45
46class Signaler;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020047
48class Dispatcher {
49 public:
50 virtual ~Dispatcher() {}
51 virtual uint32_t GetRequestedEvents() = 0;
52 virtual void OnPreEvent(uint32_t ff) = 0;
53 virtual void OnEvent(uint32_t ff, int err) = 0;
54#if defined(WEBRTC_WIN)
55 virtual WSAEVENT GetWSAEvent() = 0;
56 virtual SOCKET GetSocket() = 0;
57 virtual bool CheckSignalClose() = 0;
58#elif defined(WEBRTC_POSIX)
59 virtual int GetDescriptor() = 0;
60 virtual bool IsDescriptorClosed() = 0;
61#endif
62};
63
64// A socket server that provides the real sockets of the underlying OS.
Mirko Bonadei35214fc2019-09-23 14:54:28 +020065class RTC_EXPORT PhysicalSocketServer : public SocketServer {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020066 public:
67 PhysicalSocketServer();
68 ~PhysicalSocketServer() override;
69
70 // SocketFactory:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071 Socket* CreateSocket(int family, int type) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020072 AsyncSocket* CreateAsyncSocket(int family, int type) override;
73
74 // Internal Factory for Accept (virtual so it can be overwritten in tests).
75 virtual AsyncSocket* WrapSocket(SOCKET s);
76
77 // SocketServer:
78 bool Wait(int cms, 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
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020085 private:
Markus Handellb7c63ab2020-05-26 18:09:55 +020086 // The number of events to process with one call to "epoll_wait".
87 static constexpr size_t kNumEpollEvents = 128;
88
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020089#if defined(WEBRTC_POSIX)
90 bool WaitSelect(int cms, bool process_io);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020091#endif // WEBRTC_POSIX
92#if defined(WEBRTC_USE_EPOLL)
Taylor Brandstetter7b69a442020-08-20 23:43:13 +000093 void AddEpoll(Dispatcher* dispatcher, uint64_t key);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020094 void RemoveEpoll(Dispatcher* dispatcher);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +000095 void UpdateEpoll(Dispatcher* dispatcher, uint64_t key);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020096 bool WaitEpoll(int cms);
97 bool WaitPoll(int cms, Dispatcher* dispatcher);
98
Markus Handellb7c63ab2020-05-26 18:09:55 +020099 // This array is accessed in isolation by a thread calling into Wait().
100 // It's useless to use a SequenceChecker to guard it because a socket
101 // server can outlive the thread it's bound to, forcing the Wait call
102 // to have to reset the sequence checker on Wait calls.
103 std::array<epoll_event, kNumEpollEvents> epoll_events_;
Niels Möller611fba42020-05-13 14:42:22 +0200104 const int epoll_fd_ = INVALID_SOCKET;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200105#endif // WEBRTC_USE_EPOLL
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000106 // uint64_t keys are used to uniquely identify a dispatcher in order to avoid
107 // the ABA problem during the epoll loop (a dispatcher being destroyed and
108 // replaced by one with the same address).
109 uint64_t next_dispatcher_key_ RTC_GUARDED_BY(crit_) = 0;
110 std::unordered_map<uint64_t, Dispatcher*> dispatcher_by_key_
111 RTC_GUARDED_BY(crit_);
112 // Reverse lookup necessary for removals/updates.
113 std::unordered_map<Dispatcher*, uint64_t> key_by_dispatcher_
114 RTC_GUARDED_BY(crit_);
115 // A list of dispatcher keys that we're interested in for the current
116 // select() or WSAWaitForMultipleEvents() loop. Again, used to avoid the ABA
117 // problem (a socket being destroyed and a new one created with the same
118 // handle, erroneously receiving the events from the destroyed socket).
119 //
120 // Kept as a member variable just for efficiency.
121 std::vector<uint64_t> current_dispatcher_keys_;
Niels Möller8ce078d2020-05-18 10:17:41 +0200122 Signaler* signal_wakeup_; // Assigned in constructor only
Markus Handell3cb525b2020-07-16 16:16:09 +0200123 RecursiveCriticalSection crit_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200124#if defined(WEBRTC_WIN)
Niels Möller611fba42020-05-13 14:42:22 +0200125 const WSAEVENT socket_ev_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200126#endif
Niels Möller611fba42020-05-13 14:42:22 +0200127 bool fWait_;
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000128 // Are we currently in a select()/epoll()/WSAWaitForMultipleEvents loop?
129 // Used for a DCHECK, because we don't support reentrant waiting.
130 bool waiting_ = false;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200131};
132
133class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
134 public:
135 PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET);
136 ~PhysicalSocket() override;
137
138 // Creates the underlying OS socket (same as the "socket" function).
139 virtual bool Create(int family, int type);
140
141 SocketAddress GetLocalAddress() const override;
142 SocketAddress GetRemoteAddress() const override;
143
144 int Bind(const SocketAddress& bind_addr) override;
145 int Connect(const SocketAddress& addr) override;
146
147 int GetError() const override;
148 void SetError(int error) override;
149
150 ConnState GetState() const override;
151
152 int GetOption(Option opt, int* value) override;
153 int SetOption(Option opt, int value) override;
154
155 int Send(const void* pv, size_t cb) override;
156 int SendTo(const void* buffer,
157 size_t length,
158 const SocketAddress& addr) override;
159
160 int Recv(void* buffer, size_t length, int64_t* timestamp) override;
161 int RecvFrom(void* buffer,
162 size_t length,
163 SocketAddress* out_addr,
164 int64_t* timestamp) override;
165
166 int Listen(int backlog) override;
167 AsyncSocket* Accept(SocketAddress* out_addr) override;
168
169 int Close() override;
170
171 SocketServer* socketserver() { return ss_; }
172
173 protected:
174 int DoConnect(const SocketAddress& connect_addr);
175
176 // Make virtual so ::accept can be overwritten in tests.
177 virtual SOCKET DoAccept(SOCKET socket, sockaddr* addr, socklen_t* addrlen);
178
179 // Make virtual so ::send can be overwritten in tests.
180 virtual int DoSend(SOCKET socket, const char* buf, int len, int flags);
181
182 // Make virtual so ::sendto can be overwritten in tests.
Yves Gerey665174f2018-06-19 15:03:05 +0200183 virtual int DoSendTo(SOCKET socket,
184 const char* buf,
185 int len,
186 int flags,
187 const struct sockaddr* dest_addr,
188 socklen_t addrlen);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200189
190 void OnResolveResult(AsyncResolverInterface* resolver);
191
192 void UpdateLastError();
193 void MaybeRemapSendError();
194
195 uint8_t enabled_events() const { return enabled_events_; }
196 virtual void SetEnabledEvents(uint8_t events);
197 virtual void EnableEvents(uint8_t events);
198 virtual void DisableEvents(uint8_t events);
199
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800200 int TranslateOption(Option opt, int* slevel, int* sopt);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200201
202 PhysicalSocketServer* ss_;
203 SOCKET s_;
204 bool udp_;
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800205 int family_ = 0;
Markus Handell3cb525b2020-07-16 16:16:09 +0200206 RecursiveCriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700207 int error_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200208 ConnState state_;
209 AsyncResolver* resolver_;
210
211#if !defined(NDEBUG)
212 std::string dbg_addr_;
213#endif
214
215 private:
216 uint8_t enabled_events_ = 0;
217};
218
219class SocketDispatcher : public Dispatcher, public PhysicalSocket {
220 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200221 explicit SocketDispatcher(PhysicalSocketServer* ss);
222 SocketDispatcher(SOCKET s, PhysicalSocketServer* ss);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200223 ~SocketDispatcher() override;
224
225 bool Initialize();
226
227 virtual bool Create(int type);
228 bool Create(int family, int type) override;
229
230#if defined(WEBRTC_WIN)
231 WSAEVENT GetWSAEvent() override;
232 SOCKET GetSocket() override;
233 bool CheckSignalClose() override;
234#elif defined(WEBRTC_POSIX)
235 int GetDescriptor() override;
236 bool IsDescriptorClosed() override;
237#endif
238
239 uint32_t GetRequestedEvents() override;
240 void OnPreEvent(uint32_t ff) override;
241 void OnEvent(uint32_t ff, int err) override;
242
243 int Close() override;
244
245#if defined(WEBRTC_USE_EPOLL)
246 protected:
247 void StartBatchedEventUpdates();
248 void FinishBatchedEventUpdates();
249
250 void SetEnabledEvents(uint8_t events) override;
251 void EnableEvents(uint8_t events) override;
252 void DisableEvents(uint8_t events) override;
253#endif
254
255 private:
256#if defined(WEBRTC_WIN)
257 static int next_id_;
258 int id_;
259 bool signal_close_;
260 int signal_err_;
Yves Gerey665174f2018-06-19 15:03:05 +0200261#endif // WEBRTC_WIN
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200262#if defined(WEBRTC_USE_EPOLL)
263 void MaybeUpdateDispatcher(uint8_t old_events);
264
265 int saved_enabled_events_ = -1;
266#endif
267};
268
Yves Gerey665174f2018-06-19 15:03:05 +0200269} // namespace rtc
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200270
Steve Anton10542f22019-01-11 09:11:00 -0800271#endif // RTC_BASE_PHYSICAL_SOCKET_SERVER_H_