blob: f83bf524874cf36483a20b685309b264b9bb6595 [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"
Niels Möller6d176022021-02-09 14:44:48 +010028#include "rtc_base/synchronization/mutex.h"
Mirko Bonadei35214fc2019-09-23 14:54:28 +020029#include "rtc_base/system/rtc_export.h"
Niels Möller8ce078d2020-05-18 10:17:41 +020030#include "rtc_base/thread_annotations.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020031
32#if defined(WEBRTC_POSIX)
33typedef int SOCKET;
Yves Gerey665174f2018-06-19 15:03:05 +020034#endif // WEBRTC_POSIX
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020035
36namespace rtc {
37
38// Event constants for the Dispatcher class.
39enum DispatcherEvent {
Yves Gerey665174f2018-06-19 15:03:05 +020040 DE_READ = 0x0001,
41 DE_WRITE = 0x0002,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020042 DE_CONNECT = 0x0004,
Yves Gerey665174f2018-06-19 15:03:05 +020043 DE_CLOSE = 0x0008,
44 DE_ACCEPT = 0x0010,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020045};
46
47class Signaler;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020048
49class Dispatcher {
50 public:
51 virtual ~Dispatcher() {}
52 virtual uint32_t GetRequestedEvents() = 0;
53 virtual void OnPreEvent(uint32_t ff) = 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.
Mirko Bonadei35214fc2019-09-23 14:54:28 +020066class RTC_EXPORT PhysicalSocketServer : public SocketServer {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020067 public:
68 PhysicalSocketServer();
69 ~PhysicalSocketServer() override;
70
71 // SocketFactory:
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020072 Socket* CreateSocket(int family, int type) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020073 AsyncSocket* CreateAsyncSocket(int family, int type) override;
74
75 // Internal Factory for Accept (virtual so it can be overwritten in tests).
76 virtual AsyncSocket* WrapSocket(SOCKET s);
77
78 // SocketServer:
79 bool Wait(int cms, bool process_io) override;
80 void WakeUp() override;
81
82 void Add(Dispatcher* dispatcher);
83 void Remove(Dispatcher* dispatcher);
84 void Update(Dispatcher* dispatcher);
85
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020086 private:
Markus Handellb7c63ab2020-05-26 18:09:55 +020087 // The number of events to process with one call to "epoll_wait".
88 static constexpr size_t kNumEpollEvents = 128;
89
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020090#if defined(WEBRTC_POSIX)
91 bool WaitSelect(int cms, bool process_io);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020092#endif // WEBRTC_POSIX
93#if defined(WEBRTC_USE_EPOLL)
Taylor Brandstetter7b69a442020-08-20 23:43:13 +000094 void AddEpoll(Dispatcher* dispatcher, uint64_t key);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020095 void RemoveEpoll(Dispatcher* dispatcher);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +000096 void UpdateEpoll(Dispatcher* dispatcher, uint64_t key);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020097 bool WaitEpoll(int cms);
98 bool WaitPoll(int cms, Dispatcher* dispatcher);
99
Markus Handellb7c63ab2020-05-26 18:09:55 +0200100 // This array is accessed in isolation by a thread calling into Wait().
101 // It's useless to use a SequenceChecker to guard it because a socket
102 // server can outlive the thread it's bound to, forcing the Wait call
103 // to have to reset the sequence checker on Wait calls.
104 std::array<epoll_event, kNumEpollEvents> epoll_events_;
Niels Möller611fba42020-05-13 14:42:22 +0200105 const int epoll_fd_ = INVALID_SOCKET;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200106#endif // WEBRTC_USE_EPOLL
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000107 // uint64_t keys are used to uniquely identify a dispatcher in order to avoid
108 // the ABA problem during the epoll loop (a dispatcher being destroyed and
109 // replaced by one with the same address).
110 uint64_t next_dispatcher_key_ RTC_GUARDED_BY(crit_) = 0;
111 std::unordered_map<uint64_t, Dispatcher*> dispatcher_by_key_
112 RTC_GUARDED_BY(crit_);
113 // Reverse lookup necessary for removals/updates.
114 std::unordered_map<Dispatcher*, uint64_t> key_by_dispatcher_
115 RTC_GUARDED_BY(crit_);
116 // A list of dispatcher keys that we're interested in for the current
117 // select() or WSAWaitForMultipleEvents() loop. Again, used to avoid the ABA
118 // problem (a socket being destroyed and a new one created with the same
119 // handle, erroneously receiving the events from the destroyed socket).
120 //
121 // Kept as a member variable just for efficiency.
122 std::vector<uint64_t> current_dispatcher_keys_;
Niels Möller8ce078d2020-05-18 10:17:41 +0200123 Signaler* signal_wakeup_; // Assigned in constructor only
Markus Handell3cb525b2020-07-16 16:16:09 +0200124 RecursiveCriticalSection crit_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200125#if defined(WEBRTC_WIN)
Niels Möller611fba42020-05-13 14:42:22 +0200126 const WSAEVENT socket_ev_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200127#endif
Niels Möller611fba42020-05-13 14:42:22 +0200128 bool fWait_;
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000129 // Are we currently in a select()/epoll()/WSAWaitForMultipleEvents loop?
130 // Used for a DCHECK, because we don't support reentrant waiting.
131 bool waiting_ = false;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200132};
133
134class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
135 public:
136 PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET);
137 ~PhysicalSocket() override;
138
139 // Creates the underlying OS socket (same as the "socket" function).
140 virtual bool Create(int family, int type);
141
142 SocketAddress GetLocalAddress() const override;
143 SocketAddress GetRemoteAddress() const override;
144
145 int Bind(const SocketAddress& bind_addr) override;
146 int Connect(const SocketAddress& addr) override;
147
148 int GetError() const override;
149 void SetError(int error) override;
150
151 ConnState GetState() const override;
152
153 int GetOption(Option opt, int* value) override;
154 int SetOption(Option opt, int value) override;
155
156 int Send(const void* pv, size_t cb) override;
157 int SendTo(const void* buffer,
158 size_t length,
159 const SocketAddress& addr) override;
160
161 int Recv(void* buffer, size_t length, int64_t* timestamp) override;
162 int RecvFrom(void* buffer,
163 size_t length,
164 SocketAddress* out_addr,
165 int64_t* timestamp) override;
166
167 int Listen(int backlog) override;
168 AsyncSocket* Accept(SocketAddress* out_addr) override;
169
170 int Close() override;
171
172 SocketServer* socketserver() { return ss_; }
173
174 protected:
175 int DoConnect(const SocketAddress& connect_addr);
176
177 // Make virtual so ::accept can be overwritten in tests.
178 virtual SOCKET DoAccept(SOCKET socket, sockaddr* addr, socklen_t* addrlen);
179
180 // Make virtual so ::send can be overwritten in tests.
181 virtual int DoSend(SOCKET socket, const char* buf, int len, int flags);
182
183 // Make virtual so ::sendto can be overwritten in tests.
Yves Gerey665174f2018-06-19 15:03:05 +0200184 virtual int DoSendTo(SOCKET socket,
185 const char* buf,
186 int len,
187 int flags,
188 const struct sockaddr* dest_addr,
189 socklen_t addrlen);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200190
191 void OnResolveResult(AsyncResolverInterface* resolver);
192
193 void UpdateLastError();
194 void MaybeRemapSendError();
195
196 uint8_t enabled_events() const { return enabled_events_; }
197 virtual void SetEnabledEvents(uint8_t events);
198 virtual void EnableEvents(uint8_t events);
199 virtual void DisableEvents(uint8_t events);
200
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800201 int TranslateOption(Option opt, int* slevel, int* sopt);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200202
203 PhysicalSocketServer* ss_;
204 SOCKET s_;
205 bool udp_;
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800206 int family_ = 0;
Niels Möller6d176022021-02-09 14:44:48 +0100207 mutable webrtc::Mutex mutex_;
208 int error_ RTC_GUARDED_BY(mutex_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200209 ConnState state_;
210 AsyncResolver* resolver_;
211
212#if !defined(NDEBUG)
213 std::string dbg_addr_;
214#endif
215
216 private:
217 uint8_t enabled_events_ = 0;
218};
219
220class SocketDispatcher : public Dispatcher, public PhysicalSocket {
221 public:
Yves Gerey665174f2018-06-19 15:03:05 +0200222 explicit SocketDispatcher(PhysicalSocketServer* ss);
223 SocketDispatcher(SOCKET s, PhysicalSocketServer* ss);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200224 ~SocketDispatcher() override;
225
226 bool Initialize();
227
228 virtual bool Create(int type);
229 bool Create(int family, int type) override;
230
231#if defined(WEBRTC_WIN)
232 WSAEVENT GetWSAEvent() override;
233 SOCKET GetSocket() override;
234 bool CheckSignalClose() override;
235#elif defined(WEBRTC_POSIX)
236 int GetDescriptor() override;
237 bool IsDescriptorClosed() override;
238#endif
239
240 uint32_t GetRequestedEvents() override;
241 void OnPreEvent(uint32_t ff) override;
242 void OnEvent(uint32_t ff, int err) override;
243
244 int Close() override;
245
246#if defined(WEBRTC_USE_EPOLL)
247 protected:
248 void StartBatchedEventUpdates();
249 void FinishBatchedEventUpdates();
250
251 void SetEnabledEvents(uint8_t events) override;
252 void EnableEvents(uint8_t events) override;
253 void DisableEvents(uint8_t events) override;
254#endif
255
256 private:
257#if defined(WEBRTC_WIN)
258 static int next_id_;
259 int id_;
260 bool signal_close_;
261 int signal_err_;
Yves Gerey665174f2018-06-19 15:03:05 +0200262#endif // WEBRTC_WIN
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200263#if defined(WEBRTC_USE_EPOLL)
264 void MaybeUpdateDispatcher(uint8_t old_events);
265
266 int saved_enabled_events_ = -1;
267#endif
268};
269
Yves Gerey665174f2018-06-19 15:03:05 +0200270} // namespace rtc
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200271
Steve Anton10542f22019-01-11 09:11:00 -0800272#endif // RTC_BASE_PHYSICAL_SOCKET_SERVER_H_